rx.observers.TestObserver Java Examples

The following examples show how to use rx.observers.TestObserver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileObservableTest.java    From newts with Apache License 2.0 6 votes vote down vote up
@Test
public void testLines() throws IOException {
    
    Path testFile = tempFile("target/testing/lines-test");
    
    List<String> lines = createTestFile(testFile,
       "line1",
       "line2",
       "line3",
       "",
       "line5"
    );

    TestObserver<String> testObserver = new TestObserver<>();
    
    Observable<String> contents = FileObservable.lines(testFile);
    
    contents.subscribe(testObserver);
    
    testObserver.assertReceivedOnNext(lines);
    testObserver.assertTerminalEvent();
}
 
Example #2
Source File: ObservableTestBaseTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Demonstrates that the indirection of the internal PublishSubject within
 * the Network's Layer class is what causes failed assertions to not be
 * recognized by JUnit (i.e. they get swallowed). 
 * 
 * This test passes even though there are errors.
 */
@Test
public void testCheckObservable_Incorrectly_Passes() {
    FauxNetwork network = new FauxNetwork();
    
    TestObserver<Inference> observer = new TestObserver<Inference>() {
        @Override
        public void onNext(Inference i) {
            assertTrue(i.getAnomalyScore() == 0.0);
        }
    };
    
    network.subscribe(observer);
    
    ManualInput inf = new ManualInput();
    inf.anomalyScore(1.0);
    
    network.compute(inf);
    
    // Test that there are errors even though the test passes.
    assertTrue(hasErrors(observer));
}
 
Example #3
Source File: ObservableTestBase.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
protected <T> void checkObserver(TestObserver<T> obs) {
    if(obs.getOnErrorEvents().size() > 0) {
        Throwable e = (Throwable) obs.getOnErrorEvents().get(0);
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
 
Example #4
Source File: ObservableTestBaseTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Demonstrates that the indirection of the internal PublishSubject within
 * the Network's Layer class is what causes failed assertions to not be
 * recognized by JUnit (i.e. they get swallowed). 
 * 
 * This test passes even though there are errors.
 */
@Test
public void testCheckObservable_Correctly_Fails() {
    FauxNetwork network = new FauxNetwork();
    
    TestObserver<Inference> observer = new TestObserver<Inference>() {
        @Override
        public void onNext(Inference i) {
            assertTrue(i.getAnomalyScore() == 0.0); // Force error: anomalyScore == 1.0
        }
    };
    
    network.subscribe(observer);
    
    ManualInput inf = new ManualInput();
    inf.anomalyScore(1.0);
    
    network.compute(inf);
    
    // Test that there are errors even thought the test passes.
    assertTrue(hasErrors(observer));
    
    try {
        checkObserver(observer);
        // Should not reach this point. We want the checkObserver()
        // method above to throw an exception which will indicate the
        // test failure - though the test failing is what makes the 
        // actual (negative) test pass.
        fail(); 
    }catch(Exception e) {
        // Test passes when this point is reached.
        assertTrue(e.getCause() instanceof AssertionError);
    }
}
 
Example #5
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testBasicSetupEncoder_UsingSubscribe() {
    Parameters p = NetworkTestHarness.getParameters().copy();
    p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
    p.set(KEY.RANDOM, new MersenneTwister(42));

    MultiEncoder me = MultiEncoder.builder().name("").build();
    Layer<Map<String, Object>> l = new Layer<>(p, me, null, null, null, null);

    final int[][] expected = new int[7][8];
    expected[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
    expected[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
    expected[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
    expected[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
    expected[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
    expected[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
    expected[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };

    TestObserver<Inference> tester;
    l.subscribe(tester = new TestObserver<Inference>() {
        int seq = 0;
        @Override public void onCompleted() {}
        @Override public void onNext(Inference output) {
            assertTrue(Arrays.equals(expected[seq++], output.getSDR()));
        }
    });

    Map<String, Object> inputs = new HashMap<String, Object>();
    for(double i = 0;i < 7;i++) {
        inputs.put("dayOfWeek", i);
        l.compute(inputs);
    }
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example #6
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testBasicSetupEncoder_UsingObserve() {
    Parameters p = NetworkTestHarness.getParameters().copy();
    p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
    p.set(KEY.RANDOM, new MersenneTwister(42));

    MultiEncoder me = MultiEncoder.builder().name("").build();
    Layer<Map<String, Object>> l = new Layer<>(p, me, null, null, null, null);

    final int[][] expected = new int[7][8];
    expected[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
    expected[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
    expected[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
    expected[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
    expected[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
    expected[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
    expected[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };

    Observable<Inference> o = l.observe();
    TestObserver<Inference> tester;
    o.subscribe(tester = new TestObserver<Inference>() {
        int seq = 0;
        @Override public void onCompleted() {}
        @Override public void onNext(Inference output) {
            assertTrue(Arrays.equals(expected[seq++], output.getSDR()));
        }
    });

    Map<String, Object> inputs = new HashMap<String, Object>();
    for(double i = 0;i < 7;i++) {
        inputs.put("dayOfWeek", i);
        l.compute(inputs);
    }
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example #7
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Simple test to verify data gets passed through the {@link CLAClassifier}
 * configured within the chain of components.
 */
@Test
public void testBasicClassifierSetup() {
    Parameters p = NetworkTestHarness.getParameters().copy();
    p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
    p.set(KEY.RANDOM, new UniversalRandom(42));
    p.set(KEY.INFERRED_FIELDS, getInferredFieldsMap("dayOfWeek", CLAClassifier.class));

    MultiEncoder me = MultiEncoder.builder().name("").build();
    Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
    TestObserver<Inference> tester;
    l.subscribe(tester = new TestObserver<Inference>() {
        @Override public void onCompleted() {}
        @Override
        public void onNext(Inference i) {
            assertNotNull(i);
            assertEquals(42, i.getSDR().length);
        }
    });

    // Now push some fake data through so that "onNext" is called above
    Map<String, Object> multiInput = new HashMap<>();
    multiInput.put("dayOfWeek", 0.0);
    l.compute(multiInput);
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example #8
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testBasicSetup_SPandTM() {
    Parameters p = NetworkTestHarness.getParameters().copy();
    p.set(KEY.RANDOM, new MersenneTwister(42));

    int[][] inputs = new int[7][8];
    inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
    inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
    inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
    inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
    inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
    inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
    inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };

    Layer<int[]> l = new Layer<>(p, null, new SpatialPooler(), new TemporalMemory(), null, null);
    TestObserver<Inference> tester;
    l.subscribe(tester = new TestObserver<Inference>() {
        @Override public void onCompleted() {}
        @Override
        public void onNext(Inference i) {
            assertNotNull(i);
            assertTrue(i.getSDR().length > 0);
        }
    });

    // Now push some fake data through so that "onNext" is called above
    l.compute(inputs[0]);
    l.compute(inputs[1]);
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example #9
Source File: DeliverReplayTest.java    From nucleus with MIT License 4 votes vote down vote up
@Test
public void testPagingCapabilities() {
    PublishSubject<Object> view = PublishSubject.create();
    BehaviorSubject<Integer> nextPageRequests = BehaviorSubject.create();
    final TestObserver<Delivery<Object, String>> testObserver = new TestObserver<>();

    nextPageRequests
        .concatMap(new Func1<Integer, Observable<Integer>>() {
            @Override
            public Observable<Integer> call(Integer targetPage) {
                return targetPage <= requestedPageCount ?
                    Observable.<Integer>never() :
                    Observable.range(requestedPageCount, targetPage - requestedPageCount);
            }
        })
        .doOnNext(new Action1<Integer>() {
            @Override
            public void call(Integer it) {
                requestedPageCount = it + 1;
            }
        })
        .startWith(Observable.range(0, requestedPageCount))
        .concatMap(new Func1<Integer, Observable<String>>() {
            @Override
            public Observable<String> call(final Integer page) {
                return requestPage(page, PAGE_SIZE);
            }
        })
        .compose(new DeliverReplay<Object, String>(view))
        .subscribe(testObserver);

    ArrayList<Delivery<Object, String>> onNext = new ArrayList<>();

    testObserver.assertReceivedOnNext(onNext);

    view.onNext(999);
    addOnNext(onNext, 999, 0, 1, 2);

    testObserver.assertReceivedOnNext(onNext);

    nextPageRequests.onNext(2);
    addOnNext(onNext, 999, 3, 4, 5);

    testObserver.assertReceivedOnNext(onNext);

    view.onNext(null);

    assertEquals(0, testObserver.getOnCompletedEvents().size());
    testObserver.assertReceivedOnNext(onNext);

    nextPageRequests.onNext(3);

    assertEquals(0, testObserver.getOnCompletedEvents().size());
    testObserver.assertReceivedOnNext(onNext);

    view.onNext(9999);
    addOnNext(onNext, 9999, 0, 1, 2, 3, 4, 5, 6, 7, 8);

    assertEquals(0, testObserver.getOnCompletedEvents().size());
    testObserver.assertReceivedOnNext(onNext);
}
 
Example #10
Source File: DeliverReplayTest.java    From FlowGeek with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testPagingCapabilities() {
    PublishSubject<Object> view = PublishSubject.create();
    BehaviorSubject<Integer> nextPageRequests = BehaviorSubject.create();
    final TestObserver<Delivery<Object, String>> testObserver = new TestObserver<>();

    nextPageRequests
        .concatMap(new Func1<Integer, Observable<Integer>>() {
            @Override
            public Observable<Integer> call(Integer targetPage) {
                return targetPage <= requestedPageCount ?
                    Observable.<Integer>never() :
                    Observable.range(requestedPageCount, targetPage - requestedPageCount);
            }
        })
        .doOnNext(new Action1<Integer>() {
            @Override
            public void call(Integer it) {
                requestedPageCount = it + 1;
            }
        })
        .startWith(Observable.range(0, requestedPageCount))
        .concatMap(new Func1<Integer, Observable<String>>() {
            @Override
            public Observable<String> call(final Integer page) {
                return requestPage(page, PAGE_SIZE);
            }
        })
        .compose(new DeliverReplay<Object, String>(view))
        .subscribe(testObserver);

    ArrayList<Delivery<Object, String>> onNext = new ArrayList<>();

    testObserver.assertReceivedOnNext(onNext);

    view.onNext(999);
    addOnNext(onNext, 999, 0, 1, 2);

    testObserver.assertReceivedOnNext(onNext);

    nextPageRequests.onNext(2);
    addOnNext(onNext, 999, 3, 4, 5);

    testObserver.assertReceivedOnNext(onNext);

    view.onNext(null);

    assertEquals(0, testObserver.getOnCompletedEvents().size());
    testObserver.assertReceivedOnNext(onNext);

    nextPageRequests.onNext(3);

    assertEquals(0, testObserver.getOnCompletedEvents().size());
    testObserver.assertReceivedOnNext(onNext);

    view.onNext(9999);
    addOnNext(onNext, 9999, 0, 1, 2, 3, 4, 5, 6, 7, 8);

    assertEquals(0, testObserver.getOnCompletedEvents().size());
    testObserver.assertReceivedOnNext(onNext);
}
 
Example #11
Source File: FileObservableTest.java    From newts with Apache License 2.0 4 votes vote down vote up
@Test
public void testWalking() throws IOException, InterruptedException {

    Path dir = tempFolder.getRoot().toPath();

    List<Path> files = createTestTree(dir, "a/a", "a/b", "b/a", "b/b");

    TestObserver<Path> testObserver = new TestObserver<>();
    
    Observable<Path> walk = FileObservable.fileTreeWalker(dir);
    
    walk.subscribe(testObserver);
    
    List<Path> observedFiles = testObserver.getOnNextEvents();
    
    assertTrue(files.containsAll(observedFiles) && observedFiles.containsAll(files));
    testObserver.assertTerminalEvent();
}
 
Example #12
Source File: PersistenceAPITest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * The {@link DateEncoder} presents a special challenge because its main
 * field (the DateFormatter) is not serializable and requires its state (format)
 * to be saved and re-installed following de-serialization.
 */
@Test
public void testSerializedUnStartedNetworkRuns_DateEncoder() {
    final int NUM_CYCLES = 100;
    
    Network network = getLoadedHotGymNetwork();
    
    SerialConfig config = new SerialConfig("testSerializedUnStartedNetworkRuns_DateEncoderFST", 
        SerialConfig.SERIAL_TEST_DIR);
    PersistenceAPI api = Persistence.get(config);
    api.store(network);
    
    //Serialize above Connections for comparison with same run but unserialized below...
    Network serializedNetwork = api.load();
    assertEquals(serializedNetwork, network);
    deepCompare(network, serializedNetwork);
    
    TestObserver<Inference> tester;
    serializedNetwork.observe().subscribe(tester = new TestObserver<Inference>() { 
        @Override public void onCompleted() {}
        @Override
        public void onNext(Inference inf) {
            assertNotNull(inf);
        }
    });
    
    Publisher pub = serializedNetwork.getPublisher();
    
    serializedNetwork.start();
    
    int cycleCount = 0;
    List<String> hotStream = makeStream().collect(Collectors.toList());
    for(;cycleCount < NUM_CYCLES;cycleCount++) {
        for(String s : hotStream) {
            pub.onNext(s);
        }
        
        serializedNetwork.reset();
    }
    
    pub.onComplete();
    
    try {
        Region r1 = serializedNetwork.lookup("r1");
        r1.lookup("1").getLayerThread().join();
    }catch(Exception e) {
        e.printStackTrace();
    }
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example #13
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * The {@link SpatialPooler} sometimes needs to have data run through it 
 * prior to passing the data on to subsequent algorithmic components. This
 * tests the ability to specify exactly the number of input records for 
 * the SpatialPooler to consume before passing records on.
 */
@Test
public void testMoreComplexSpatialPoolerPriming() {
    final int PRIME_COUNT = 35;
    final int NUM_CYCLES = 20;
    final int INPUT_GROUP_COUNT = 7; // Days of Week
    TOTAL = 0;

    Parameters p = NetworkTestHarness.getParameters().copy();
    p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
    p.set(KEY.RANDOM, new MersenneTwister(42));
    p.set(KEY.INFERRED_FIELDS, getInferredFieldsMap("dayOfWeek", CLAClassifier.class));
    p.set(KEY.SP_PRIMER_DELAY, PRIME_COUNT);

    MultiEncoder me = MultiEncoder.builder().name("").build();
    Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
    TestObserver<Inference> tester;
    l.subscribe(tester = new TestObserver<Inference>() {
        @Override public void onCompleted() {}
        @Override
        public void onNext(Inference i) {
            assertNotNull(i);
            TOTAL++;
        }
    });

    // Now push some fake data through so that "onNext" is called above
    Map<String, Object> multiInput = new HashMap<>();
    for(int i = 0;i < NUM_CYCLES;i++) {
        for(double j = 0;j < INPUT_GROUP_COUNT;j++) {
            multiInput.put("dayOfWeek", j);
            l.compute(multiInput);
        }
    }

    // Assert we can accurately specify how many inputs to "prime" the spatial pooler
    // and subtract that from the total input to get the total entries sent through
    // the event chain from bottom to top.
    assertEquals((NUM_CYCLES * INPUT_GROUP_COUNT) - PRIME_COUNT, TOTAL);
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example #14
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void testBasicSetup_TemporalMemory_MANUAL_MODE() {
    Parameters p = NetworkTestHarness.getParameters().copy();
    p.set(KEY.RANDOM, new MersenneTwister(42));

    final int[] input1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
    final int[] input2 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
    final int[] input3 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
    final int[] input4 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 };
    final int[] input5 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 };
    final int[] input6 = new int[] { 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 };
    final int[] input7 = new int[] { 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 };
    final int[][] inputs = { input1, input2, input3, input4, input5, input6, input7 };

    
    Layer<int[]> l = new Layer<>(p, null, null, new TemporalMemory(), null, null);
    
    int timeUntilStable = 600;

    TestObserver<Inference> observer;
    
    l.subscribe(observer = new TestObserver<Inference>() {
        int test = 0;
        @Override
        public void onNext(Inference output) {
            if(seq / 7 >= timeUntilStable) {
                System.out.println("seq: " + (seq) + "  --> " + (test) + "  output = " + Arrays.toString(output.getSDR()) +
                    ", \t\t\t\t cols = " + Arrays.toString(SDR.asColumnIndices(output.getSDR(), l.getConnections().getCellsPerColumn())));
                assertTrue(output.getSDR().length >= 5);
            }
            
            ++seq;
            
            if(test == 6) test = 0;
            else test++;                
        }
    });
    
    // Now push some warm up data through so that "onNext" is called above
    for(int j = 0;j < timeUntilStable;j++) {
        for(int i = 0;i < inputs.length;i++) {
            l.compute(inputs[i]);
        }
    }

    for(int j = 0;j < 2;j++) {
        for(int i = 0;i < inputs.length;i++) {
            l.compute(inputs[i]);
        }
    }
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(observer);
}
 
Example #15
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Temporary test to test basic sequence mechanisms
 */
@Test
public void testBasicSetup_SpatialPooler_AUTO_MODE() {
    Sensor<File> sensor = Sensor.create(
        FileSensor::create, 
        SensorParams.create(
            Keys::path, "", ResourceLocator.path("days-of-week.csv")));

    Parameters p = NetworkTestHarness.getParameters().copy();
    p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
    p.set(KEY.RANDOM, new UniversalRandom(42));
    p.set(KEY.AUTO_CLASSIFY, Boolean.TRUE);
    p.set(KEY.INFERRED_FIELDS, getInferredFieldsMap("dayOfWeek", CLAClassifier.class));

    HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;

    Network n = Network.create("test network", p);
    Layer<int[]> l = new Layer<>(n);
    l.add(htmSensor).add(new SpatialPooler());
    
    final int[] expected0 = new int[] { 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0 };
    final int[] expected1 = new int[] { 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 };
    TestObserver<Inference> tester;
    l.subscribe(tester = new TestObserver<Inference>() {
        int test = 0;

        @Override public void onCompleted() {}
        @Override
        public void onNext(Inference spatialPoolerOutput) {
            if(test == 0) {
                assertTrue(Arrays.equals(expected0, spatialPoolerOutput.getSDR()));
            }
            if(test == 1) {
                assertTrue(Arrays.equals(expected1, spatialPoolerOutput.getSDR()));
            }
            ++test; 
        }
    });
    
    l.start();

    try {
        l.getLayerThread().join();
    }catch(Exception e) {
        e.printStackTrace();
    }
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example #16
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Temporary test to test basic sequence mechanisms
 */
@Test
public void testBasicSetup_SpatialPooler_MANUAL_MODE() {
    Parameters p = NetworkTestHarness.getParameters().copy();
    p.set(KEY.RANDOM, new UniversalRandom(42));

    int[][] inputs = new int[7][8];
    inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
    inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
    inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
    inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
    inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
    inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
    inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };

    final int[] expected0 = new int[] { 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0 };
    final int[] expected1 = new int[] { 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 };

    Layer<int[]> l = new Layer<>(p, null, new SpatialPooler(), null, null, null);

    TestObserver<Inference> tester;
    l.subscribe(tester = new TestObserver<Inference>() {
        int test = 0;

        @Override public void onCompleted() {}
        @Override
        public void onNext(Inference spatialPoolerOutput) {
            if(test == 0) {
                assertTrue(Arrays.equals(expected0, spatialPoolerOutput.getSDR()));
            }
            if(test == 1) {
                assertTrue(Arrays.equals(expected1, spatialPoolerOutput.getSDR()));
            }
            ++test; 
        }
    });

    // Now push some fake data through so that "onNext" is called above
    l.compute(inputs[0]);
    l.compute(inputs[1]);
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example #17
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void testLayerWithObservableInputIntegerArray() {
    Publisher manual = Publisher.builder()
        .addHeader("sdr_in")
        .addHeader("darr")
        .addHeader("B")
        .build();

    Sensor<ObservableSensor<String[]>> sensor = Sensor.create(
        ObservableSensor::create, 
            SensorParams.create(
                Keys::obs, new Object[] {"name", manual}));

    Parameters p = Parameters.getAllDefaultParameters();
    p = p.union(getArrayTestParams());
    p.set(KEY.RANDOM, new MersenneTwister(42));

    HTMSensor<ObservableSensor<String[]>> htmSensor = (HTMSensor<ObservableSensor<String[]>>)sensor;

    Network n = Network.create("test network", p);
    final Layer<int[]> l = new Layer<>(n);
    l.add(htmSensor);

    String input = "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, "
                    + "1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, "
                    + "0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, "
                    + "1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, "
                    + "1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
                    + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0]";

    TestObserver<Inference> tester;
    l.subscribe(tester = new TestObserver<Inference>() {
        @Override public void onCompleted() {}
        @Override public void onNext(Inference output) {
            assertEquals(input, Arrays.toString((int[])output.getLayerInput()));
        }
    });
    
    l.start();

    try {
        String[] entries = { 
              input
        };

        // Send inputs through the observable
        for(String s : entries) {
            manual.onNext(s);
            manual.onComplete();
        }

        l.getLayerThread().join();
    }catch(Exception e) {
        e.printStackTrace();
        fail();
    }
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example #18
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void testHalt() {
    Sensor<File> sensor = Sensor.create(
        FileSensor::create, SensorParams.create(
            Keys::path, "", ResourceLocator.path("rec-center-hourly-small.csv")));

    Parameters p = NetworkTestHarness.getParameters().copy();
    p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
    p.set(KEY.RANDOM, new MersenneTwister(42));
    p.set(KEY.AUTO_CLASSIFY, Boolean.TRUE);
    p.set(KEY.INFERRED_FIELDS, getInferredFieldsMap("consumption", CLAClassifier.class));

    HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;

    Network n = Network.create("test network", p);
    final Layer<int[]> l = new Layer<>(n);
    l.add(htmSensor);

    TestObserver<Inference> tester;
    l.subscribe(tester = new TestObserver<Inference>() {
        @Override public void onCompleted() {
            assertTrue(l.isHalted());
            isHalted = true;
        }
        @Override public void onNext(Inference output) {}
    });
    
    l.start();

    try {
        l.halt();
        l.getLayerThread().join();
        assertTrue(isHalted);
    }catch(Exception e) {
        e.printStackTrace();
        fail();
    }
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example #19
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void testGetAllValues() {
    Parameters p = NetworkTestHarness.getParameters().copy();
    p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
    p.set(KEY.RANDOM, new UniversalRandom(42));
    p.set(KEY.INFERRED_FIELDS, getInferredFieldsMap("dayOfWeek", CLAClassifier.class));

    MultiEncoder me = MultiEncoder.builder().name("").build();
    Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);

    // Test that we get the expected exception if there hasn't been any processing.
    try {
        l.getAllValues("dayOfWeek", 1);
        fail();
    }catch(Exception e) {
        assertEquals("Predictions not available. Either classifiers unspecified or inferencing has not yet begun.", e.getMessage());
    }

    TestObserver<Inference> tester;
    l.subscribe(tester = new TestObserver<Inference>() {
        @Override public void onCompleted() {}
        @Override
        public void onNext(Inference i) {
            assertNotNull(i);
            assertEquals(42, i.getSDR().length);
        }
    });

    // Now push some fake data through so that "onNext" is called above
    Map<String, Object> multiInput = new HashMap<>();
    multiInput.put("dayOfWeek", 0.0);
    l.compute(multiInput);

    Object[] values = l.getAllValues("dayOfWeek", 1);
    assertNotNull(values);
    assertTrue(values.length == 1);
    assertEquals(0.0D, values[0]);
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example #20
Source File: ObservableTestBase.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
protected <T> boolean hasCompletions(TestObserver<T> obs) {
    return !obs.getOnCompletedEvents().isEmpty();
}
 
Example #21
Source File: ObservableTestBase.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
protected <T> boolean hasErrors(TestObserver<T> obs) {
    return !obs.getOnErrorEvents().isEmpty();
}