private void testDropWhileMulti(Consumer<Stream<Integer>> mRef, Consumer<IntStream> mInt, Consumer<LongStream> mLong, Consumer<DoubleStream> mDouble) { Map<String, Supplier<Stream<Integer>>> sources = new HashMap<>(); sources.put("IntStream.range().boxed()", () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed()); sources.put("IntStream.range().boxed().unordered()", () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed().unordered()); sources.put("LinkedList.stream()", () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed() .collect(toCollection(LinkedList::new)) .stream()); sources.put("LinkedList.stream().unordered()", () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed() .collect(toCollection(LinkedList::new)) .stream() .unordered()); testWhileMulti(sources, mRef, mInt, mLong, mDouble); }
@Test(dataProvider = "sizes") public void testWithDoubles(int initialSize) { final Random random = new Random(); final ArrayBuilder<Double> builder = ArrayBuilder.of(initialSize); final double[] expected = new double[1000]; for (int i=0; i<expected.length; ++i) { expected[i] = random.nextDouble(); builder.add(expected[i]); } final Array<Double> actual = builder.toArray(); Assert.assertEquals(actual.length(), expected.length, "The lengths match"); Assert.assertEquals(actual.typeCode(), ArrayType.DOUBLE, "The array type is as expected"); for (int i=0; i<expected.length; ++i) { Assert.assertEquals(actual.getDouble(i), expected[i], "The values match at " + i); } final Array<Double> collected = DoubleStream.of(expected).boxed().collect(ArrayUtils.toArray(expected.length)); for (int i=0; i<expected.length; ++i) { Assert.assertEquals(collected.getDouble(i), expected[i], "The values match at " + i); } }
@Test public void testClose() { AtomicInteger before = new AtomicInteger(); AtomicInteger onClose = new AtomicInteger(); Supplier<Stream<Integer>> s = () -> { before.set(0); onClose.set(0); return Stream.of(1, 2).peek(e -> before.getAndIncrement()); }; s.get().flatMap(i -> Stream.of(i, i).onClose(onClose::getAndIncrement)).count(); assertEquals(before.get(), onClose.get()); s.get().flatMapToInt(i -> IntStream.of(i, i).onClose(onClose::getAndIncrement)).count(); assertEquals(before.get(), onClose.get()); s.get().flatMapToLong(i -> LongStream.of(i, i).onClose(onClose::getAndIncrement)).count(); assertEquals(before.get(), onClose.get()); s.get().flatMapToDouble(i -> DoubleStream.of(i, i).onClose(onClose::getAndIncrement)).count(); assertEquals(before.get(), onClose.get()); }
@Override public @NotNull TimeGraphDrawnEventRender getEventRender(TimeGraphTreeRender treeRender, TimeRange timeRange, @Nullable FutureTask<?> task) { TimeGraphDrawnEventSeries series = getDrawnEventSeries(); List<TimeGraphDrawnEvent> events = treeRender.getAllTreeElements().stream() .filter(treeElem -> treeElem != StubModelProvider.ROOT_ELEMENT) /* Keep only entries (1, 3, 5, 7) */ .filter(treeElem -> getIndexOfTreeElement(treeElem) < 8) .filter(treeElem -> (getIndexOfTreeElement(treeElem) + 1) % 2 == 0) /* Draw symbols at positions (.2, .4, .6, .8) */ .flatMap(treeElem -> DoubleStream.iterate(0.2, i -> i + 0.2).limit(4) .mapToObj(i -> new TimeGraphEvent(ts(timeRange, i), treeElem))) .map(event -> new TimeGraphDrawnEvent(event, series, null)) .collect(ImmutableList.toImmutableList()); /* There should be 16 symbols total */ return new TimeGraphDrawnEventRender(timeRange, events); }
private boolean terminationCriteriaMet(int k, double negCoverRatio) { if (untilIterationK >= 0 && k >= untilIterationK) { System.out.println("Termination criterion met: until iteration k"); return true; } if (timeout >= 0) { long timeDiff = System.currentTimeMillis() - startTime; if(timeDiff / 1000 >= timeout) { System.out.println("Termination criterion met: timeout"); return true; } } if (negCoverThresh >= 0.0) { int index = k % negCoverWindowSize; lastNegCoverRatios[index] = negCoverRatio; double averageRatio = (DoubleStream.of(lastNegCoverRatios).sum()) / (double)negCoverWindowSize; if (averageRatio <= negCoverThresh) { System.out.println("Termination criterion met: neg-cover growth ratio"); return true; } } return false; }
public void testDoubleSize() { assertSized(DoubleStream.concat( IntStream.range(0, Integer.MAX_VALUE).mapToDouble(i -> i), IntStream.range(0, Integer.MAX_VALUE).mapToDouble(i -> i))); assertUnsized(DoubleStream.concat( LongStream.range(0, Long.MAX_VALUE).mapToDouble(i -> i), LongStream.range(0, Long.MAX_VALUE).mapToDouble(i -> i))); assertUnsized(DoubleStream.concat( LongStream.range(0, Long.MAX_VALUE).mapToDouble(i -> i), DoubleStream.iterate(0, i -> i + 1))); assertUnsized(DoubleStream.concat( DoubleStream.iterate(0, i -> i + 1), LongStream.range(0, Long.MAX_VALUE).mapToDouble(i -> i))); }
private void testWhileMulti(TestData.OfRef<Integer> data, ResultAsserter<Iterable<Integer>> ra, Function<Stream<Integer>, Stream<Integer>> mRef, Function<IntStream, IntStream> mInt, Function<LongStream, LongStream> mLong, Function<DoubleStream, DoubleStream> mDouble) { Map<String, Function<Stream<Integer>, Stream<Integer>>> ms = new HashMap<>(); ms.put("Ref", mRef); ms.put("Int", s -> mInt.apply(s.mapToInt(e -> e)).mapToObj(e -> e)); ms.put("Long", s -> mLong.apply(s.mapToLong(e -> e)).mapToObj(e -> (int) e)); ms.put("Double", s -> mDouble.apply(s.mapToDouble(e -> e)).mapToObj(e -> (int) e)); ms.put("Ref using defaults", s -> mRef.apply(DefaultMethodStreams.delegateTo(s))); ms.put("Int using defaults", s -> mInt.apply(DefaultMethodStreams.delegateTo(s.mapToInt(e -> e))).mapToObj(e -> e)); ms.put("Long using defaults", s -> mLong.apply(DefaultMethodStreams.delegateTo(s.mapToLong(e -> e))).mapToObj(e -> (int) e)); ms.put("Double using defaults", s -> mDouble.apply(DefaultMethodStreams.delegateTo(s.mapToDouble(e -> e))).mapToObj(e -> (int) e)); testWhileMulti(data, ra, ms); }
public double calculate(int i) { //synchronized (calculateLock) { this.prop = 2.0 * i; DoubleStream.generate(new Random()::nextDouble).limit(10); return Math.sqrt(this.prop); //} }
private static void demo4_synchronize1() { System.out.println(); Calculator c = new Calculator(); Thread thr1 = new Thread(() -> System.out.println(IntStream.range(1, 4) .peek(x -> DoubleStream.generate(new Random()::nextDouble).limit(10)) .mapToDouble(c::calculate).sum())); thr1.start(); Thread thr2 = new Thread(() -> System.out.println(IntStream.range(1, 4) .mapToDouble(c::calculate).sum())); thr2.start(); }
private void testDoubleStreamBuilder(int size, Function<Integer, DoubleStream> supplier) { TestData.OfDouble data = TestData.Factory.ofDoubleSupplier(String.format("[0, %d)", size), () -> supplier.apply(size)); withData(data). stream(s -> s). expectedResult(IntStream.range(0, size).asDoubleStream().toArray()). exercise(); withData(data). stream(s -> s.map(i -> i)). expectedResult(IntStream.range(0, size).asDoubleStream().toArray()). exercise(); }
@Test public void testNPE() { checkNPE(() -> Stream.iterate("", null, x -> x + "a")); checkNPE(() -> Stream.iterate("", String::isEmpty, null)); checkNPE(() -> IntStream.iterate(0, null, x -> x + 1)); checkNPE(() -> IntStream.iterate(0, x -> x < 10, null)); checkNPE(() -> LongStream.iterate(0, null, x -> x + 1)); checkNPE(() -> LongStream.iterate(0, x -> x < 10, null)); checkNPE(() -> DoubleStream.iterate(0, null, x -> x + 1)); checkNPE(() -> DoubleStream.iterate(0, x -> x < 10, null)); }
public void testDoubleCollectNull() { checkNPE(() -> DoubleStream.of(1).collect(null, DoubleSummaryStatistics::accept, DoubleSummaryStatistics::combine)); checkNPE(() -> DoubleStream.of(1).collect(DoubleSummaryStatistics::new, null, DoubleSummaryStatistics::combine)); checkNPE(() -> DoubleStream.of(1).collect(DoubleSummaryStatistics::new, DoubleSummaryStatistics::accept, null)); }
private double[][] scoreGraphToWeightGraph(double[][] Gs) { double[][] Gw = new double[Gs.length][]; for (int i = 0; i < Gs.length; i++) { Gw[i] = DoubleStream.of(Gs[i]).map(Math::exp).toArray(); } return Gw; }
@Test(dataProvider = "DoubleStreamTestData", dataProviderClass = DoubleStreamTestDataProvider.class) public void testDoubleOps(String name, TestData.OfDouble data) { Collection<Double> result = exerciseOps(data, s -> s.flatMap(i -> Collections.singleton(i).stream().mapToDouble(j -> j))); assertEquals(data.size(), result.size()); assertContents(data, result); result = exerciseOps(data, s -> DoubleStream.empty()); assertEquals(0, result.size()); }
/** * MS == -1 -> total * * @param ms * @return */ private DoubleStream pointsStream(int ms) { ArrayList<Double> points = new ArrayList<>(); for (Group g : groups) { if (ms == -1) { points.add(g.getTotalSum(catalogue)); } else { points.add(g.getSumForMilestone(catalogue.getMilestoneByOrdinal(ms), catalogue)); } } return points.stream().mapToDouble(Double::valueOf); }
/** * Computes the Total Sum of Squares for regressand * @param y the vector with dependent variable observations * @return the Total Sum of Squares for regressand */ protected double computeTSS(RealVector y) { if (!hasIntercept()) { return y.dotProduct(y); } else { final double[] values = y.toArray(); final double mean = DoubleStream.of(values).average().orElse(Double.NaN); final double[] demeaned = DoubleStream.of(values).map(v -> v - mean).toArray(); final RealVector demeanedVector = new ArrayRealVector(demeaned); return demeanedVector.dotProduct(demeanedVector); } }
public void testFindLast_doubleStream() { Truth.assertThat(findLast(DoubleStream.of())).isEqualTo(OptionalDouble.empty()); Truth.assertThat(findLast(DoubleStream.of(1, 2, 3, 4, 5))).isEqualTo(OptionalDouble.of(5)); // test with a large, not-subsized Spliterator List<Long> list = LongStream.rangeClosed(0, 10000).boxed().collect(Collectors.toCollection(LinkedList::new)); Truth.assertThat(findLast(list.stream().mapToDouble(i -> i))) .isEqualTo(OptionalDouble.of(10000)); // no way to find out the stream is empty without walking its spliterator Truth.assertThat(findLast(list.stream().mapToDouble(i -> i).filter(i -> i < 0))) .isEqualTo(OptionalDouble.empty()); }
public void testConcat_doubleStream() { assertThat( Streams.concat( DoubleStream.of(1), DoubleStream.of(2), DoubleStream.empty(), DoubleStream.of(3, 4))) .containsExactly(1.0, 2.0, 3.0, 4.0) .inOrder(); }
public void testSortDistinct() { { double[] range = LongStream.range(0, 10).asDoubleStream().toArray(); assertEquals(LongStream.range(0, 10).asDoubleStream().sorted().distinct().toArray(), range); assertEquals(LongStream.range(0, 10).asDoubleStream().parallel().sorted().distinct().toArray(), range); double[] data = {5, 3, 1, 1, 5, Double.NaN, 3, 9, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 2, 9, 1, 0, 8, Double.NaN, -0.0}; double[] expected = {Double.NEGATIVE_INFINITY, -0.0, 0, 1, 2, 3, 5, 8, 9, Double.POSITIVE_INFINITY, Double.NaN}; assertEquals(DoubleStream.of(data).sorted().distinct().toArray(), expected); assertEquals(DoubleStream.of(data).parallel().sorted().distinct().toArray(), expected); } }
/** * Construct {@link ColumnDecisionTreeTrainer}. * * @param maxDepth Maximal depth of the decision tree. * @param continuousCalculatorProvider Provider of calculator of splits for region projection on continuous * features. * @param categoricalCalculatorProvider Provider of calculator of splits for region projection on categorical * features. * @param regCalc Function used to assign a value to a region. */ public ColumnDecisionTreeTrainer(int maxDepth, IgniteFunction<ColumnDecisionTreeTrainerInput, ? extends ContinuousSplitCalculator<D>> continuousCalculatorProvider, IgniteFunction<ColumnDecisionTreeTrainerInput, IgniteFunction<DoubleStream, Double>> categoricalCalculatorProvider, IgniteFunction<DoubleStream, Double> regCalc, Ignite ignite) { this.maxDepth = maxDepth; this.continuousCalculatorProvider = continuousCalculatorProvider; this.categoricalCalculatorProvider = categoricalCalculatorProvider; this.regCalc = regCalc; this.ignite = ignite; this.log = ignite.log(); }
private void assertDoubleConcat(Stream<Integer> s1, Stream<Integer> s2, boolean parallel, boolean ordered) { DoubleStream result = DoubleStream.concat(s1.mapToDouble(Integer::doubleValue), s2.mapToDouble(Integer::doubleValue)); assertEquals(result.isParallel(), parallel); assertConcatContent(result.spliterator(), ordered, expected.stream().mapToDouble(Integer::doubleValue).spliterator()); }
public static Object arrayToStream(final Object array) { if (array instanceof int[]) { return IntStream.of((int[])array); } else if (array instanceof long[]) { return LongStream.of((long[])array); } else if (array instanceof double[]) { return DoubleStream.of((double[])array); } else if (array instanceof Object[]) { return Stream.of((Object[])array); } else { throw new IllegalArgumentException(); } }
@Test public void testDoubleSingleton() { TestData.OfDouble data = TestData.Factory.ofDoubleSupplier("{1}", () -> DoubleStream.of(1)); withData(data). stream(s -> s). expectedResult(Collections.singletonList(1.0)). exercise(); withData(data). stream(s -> s.map(i -> i)). expectedResult(Collections.singletonList(1.0)). exercise(); }
@DataProvider(name = "DoubleStream.limit") public static Object[][] doubleSliceFunctionsDataProvider() { Function<String, String> f = s -> String.format(s, SKIP_LIMIT_SIZE); List<Object[]> data = new ArrayList<>(); data.add(new Object[]{f.apply("DoubleStream.limit(%d)"), (UnaryOperator<DoubleStream>) s -> s.limit(SKIP_LIMIT_SIZE)}); data.add(new Object[]{f.apply("DoubleStream.skip(%1$d).limit(%1$d)"), (UnaryOperator<DoubleStream>) s -> s.skip(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)}); return data.toArray(new Object[0][]); }
@Test(dataProvider = "DoubleStream.limit") public void testDoubleSubsizedWithRange(String description, UnaryOperator<DoubleStream> fs) { // Range is [0, 2^53), splits are SUBSIZED // Such a size will induce out of memory errors for incorrect // slice implementations withData(doubles()). stream(s -> fs.apply(s)). without(DoubleStreamTestScenario.CLEAR_SIZED_SCENARIOS). exercise(); }
@Test(dataProvider = "DoubleStream.limit") public void testDoubleUnorderedGenerator(String description, UnaryOperator<DoubleStream> fs) { // Source is spliterator of infinite size TestData.OfDouble generator = TestData.Factory.ofDoubleSupplier( "[1.0, 1.0, ...]", () -> DoubleStream.generate(() -> 1.0)); withData(generator). stream(s -> fs.apply(s.filter(i -> true).unordered())). exercise(); }
@DataProvider(name = "IterateStreamsData") public static Object[][] makeIterateStreamsTestData() { Object[][] data = { {List.of(), Factory.ofSupplier("ref.empty", () -> Stream.iterate(1, x -> x < 0, x -> x * 2))}, {List.of(1), Factory.ofSupplier("ref.one", () -> Stream.iterate(1, x -> x < 2, x -> x * 2))}, {List.of(1, 2, 4, 8, 16, 32, 64, 128, 256, 512), Factory.ofSupplier("ref.ten", () -> Stream.iterate(1, x -> x < 1000, x -> x * 2))}, {List.of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0), Factory.ofSupplier("ref.nullCheck", () -> Stream.iterate(10, Objects::nonNull, x -> x > 0 ? x - 1 : null))}, {List.of(), Factory.ofIntSupplier("int.empty", () -> IntStream.iterate(1, x -> x < 0, x -> x + 1))}, {List.of(1), Factory.ofIntSupplier("int.one", () -> IntStream.iterate(1, x -> x < 2, x -> x + 1))}, {List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Factory.ofIntSupplier("int.ten", () -> IntStream.iterate(1, x -> x <= 10, x -> x + 1))}, {List.of(5, 4, 3, 2, 1), Factory.ofIntSupplier("int.divZero", () -> IntStream.iterate(5, x -> x != 0, x -> x - 1/x/2 - 1))}, {List.of(), Factory.ofLongSupplier("long.empty", () -> LongStream.iterate(1L, x -> x < 0, x -> x + 1))}, {List.of(1L), Factory.ofLongSupplier("long.one", () -> LongStream.iterate(1L, x -> x < 2, x -> x + 1))}, {List.of(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), Factory.ofLongSupplier("long.ten", () -> LongStream.iterate(1L, x -> x <= 10, x -> x + 1))}, {List.of(), Factory.ofDoubleSupplier("double.empty", () -> DoubleStream.iterate(1.0, x -> x < 0, x -> x + 1))}, {List.of(1.0), Factory.ofDoubleSupplier("double.one", () -> DoubleStream.iterate(1.0, x -> x < 2, x -> x + 1))}, {List.of(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0), Factory.ofDoubleSupplier("double.ten", () -> DoubleStream.iterate(1.0, x -> x <= 10, x -> x + 1))} }; return data; }
public static DoubleStream generateStreamFromList(List<Double> list) { DoubleStream.Builder builder=DoubleStream.builder(); for (Double number : list) { builder.add(number); } return builder.build(); }
public static void main(String[] args) { final int i = 0; final TIME_FRAME tf = TIME_FRAME.MIN1; IDataSource ds = new SinYeeDataSource("cu", EnumSet.of(tf), str -> str.endsWith(mon[i])); // IDataSource ds = new KTExportFutures("cu", EnumSet.of(tf)); BarSeries bars = ds.getBarSeries(i, tf); int size = bars.closes.length; double[] price = new double[size]; for (int j = 0; j < size; j++) { price[j] = bars.closes[j]; } for (int j = 0; j < 20; j++) { System.out.println(Arrays.stream(price).sorted().map(Math::cos).average()); } Integer[] time = new Integer[size]; for (int j = 0; j < size; j++) { time[j] = bars.times[j]; } Arrays.asList(time); System.out.println(Arrays.stream(bars.times).average()); /** * @see http://stackoverflow.com/questions/23106093/how-to-get-a-stream-from-a-float */ DoubleStream dstream = IntStream.range(0, bars.closes.length) .mapToDouble(j -> bars.closes[j]); dstream.sorted().map(Math::cbrt); DoubleSummaryStatistics dss = StreamHelper.getFloatSummaryStatistics(bars.closes); System.out.println(dss.getMax()); System.out.println(dss.getMin()); }
@Test public void testDoubleSingleton() { TestData.OfDouble data = TestData.Factory.ofDoubleSupplier("[0, 1)", () -> DoubleStream.of(1)); withData(data). stream(s -> s). expectedResult(Collections.singletonList(1.0)). exercise(); withData(data). stream(s -> s.map(i -> i)). expectedResult(Collections.singletonList(1.0)). exercise(); }
@Test public void testDoubleClose() { AtomicInteger before = new AtomicInteger(); AtomicInteger onClose = new AtomicInteger(); DoubleStream.of(1, 2).peek(e -> before.getAndIncrement()). flatMap(i -> DoubleStream.of(i, i).onClose(onClose::getAndIncrement)).count(); assertEquals(before.get(), onClose.get()); }
private void assertDoublePredicates(Supplier<DoubleStream> source, Kind kind, DoublePredicate[] predicates, boolean... answers) { for (int i = 0; i < predicates.length; i++) { setContext("i", i); boolean match = doubleKinds.get(kind).apply(predicates[i]).apply(source.get()); assertEquals(answers[i], match, kind.toString() + predicates[i].toString()); } }
@Test(dataProvider = "DoubleStream.limit") public void testDoubleUnorderedFinite(String description, UnaryOperator<DoubleStream> fs) { // Range is [0, 1L << 53), splits are SUBSIZED // Such a size will induce out of memory errors for incorrect // slice implementations // Upper bound ensures values mapped to doubles will be unique withData(doubles()). stream(s -> fs.apply(s.filter(i -> true).unordered())). resultAsserter(unorderedAsserter()). exercise(); }
/** * Construct an input for {@link ColumnDecisionTreeTrainer}. * * @param cache Bi-indexed cache. * @param catFeaturesInfo Information about categorical feature in the form (feature index -> number of * categories). * @param samplesCnt Count of samples. * @param featuresCnt Count of features. */ public BiIndexedCacheColumnDecisionTreeTrainerInput(IgniteCache<BiIndex, Double> cache, Map<Integer, Integer> catFeaturesInfo, int samplesCnt, int featuresCnt) { super(cache, () -> IntStream.range(0, samplesCnt).mapToObj(s -> new BiIndex(s, featuresCnt)), e -> Stream.of(new IgniteBiTuple<>(e.getKey().row(), e.getValue())), DoubleStream::of, fIdx -> IntStream.range(0, samplesCnt).mapToObj(s -> new BiIndex(s, fIdx)), catFeaturesInfo, featuresCnt, samplesCnt); }