public void testEquivalentStreams() { // For datasets of many double values created from an array, we test many combinations of finite // and non-finite values: for (ManyValues values : ALL_MANY_VALUES) { double[] array = values.asArray(); Stats stats = Stats.of(array); // instance methods on Stats vs on instance methods on DoubleStream assertThat(stats.count()).isEqualTo(stream(array).count()); assertEquivalent(stats.mean(), stream(array).average().getAsDouble()); assertEquivalent(stats.sum(), stream(array).sum()); assertEquivalent(stats.max(), stream(array).max().getAsDouble()); assertEquivalent(stats.min(), stream(array).min().getAsDouble()); // static method on Stats vs on instance method on DoubleStream assertEquivalent(Stats.meanOf(array), stream(array).average().getAsDouble()); // instance methods on Stats vs instance methods on DoubleSummaryStatistics DoubleSummaryStatistics streamStats = stream(array).summaryStatistics(); assertThat(stats.count()).isEqualTo(streamStats.getCount()); assertEquivalent(stats.mean(), streamStats.getAverage()); assertEquivalent(stats.sum(), streamStats.getSum()); assertEquivalent(stats.max(), streamStats.getMax()); assertEquivalent(stats.min(), streamStats.getMin()); } }
private double getMinOfMdBottom(ObjMudLog mudLog) { List<CsGeologyInterval> geologyIntervals = mudLog.getGeologyInterval(); DoubleSummaryStatistics summaryStat = geologyIntervals.stream() .map(CsGeologyInterval::getMdBottom) .mapToDouble(MeasuredDepthCoord::getValue) .summaryStatistics(); double mdMax = -1; for (CsGeologyInterval geologyInterval : geologyIntervals) { if (geologyInterval.getMdBottom() != null) { double value = geologyInterval.getMdBottom().getValue(); if (mdMax < value) { mdMax = value; } } } return mdMax; }
public void testDoubleStatistics() { List<DoubleSummaryStatistics> instances = new ArrayList<>(); instances.add(countTo(1000).stream().collect(Collectors.summarizingDouble(i -> i))); instances.add(countTo(1000).stream().mapToDouble(i -> i).summaryStatistics()); instances.add(countTo(1000).stream().mapToDouble(i -> i).collect(DoubleSummaryStatistics::new, DoubleSummaryStatistics::accept, DoubleSummaryStatistics::combine)); instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingDouble(i -> i))); instances.add(countTo(1000).parallelStream().mapToDouble(i -> i).summaryStatistics()); instances.add(countTo(1000).parallelStream().mapToDouble(i -> i).collect(DoubleSummaryStatistics::new, DoubleSummaryStatistics::accept, DoubleSummaryStatistics::combine)); for (DoubleSummaryStatistics stats : instances) { assertEquals(stats.getCount(), 1000); assertEquals(stats.getSum(), (double) countTo(1000).stream().mapToInt(i -> i).sum()); assertEquals(stats.getAverage(), stats.getSum() / stats.getCount()); assertEquals(stats.getMax(), 1000.0); assertEquals(stats.getMin(), 1.0); } }
@Override public <S> void selectSolutions(Generation<S> generation, GenerationSelectorConfiguration configuration) { int selectionSize = (int) Math.round(generation.getSolutions().size() * configuration.getSelectionRatio()); DoubleSummaryStatistics statistics = calculateFitnessStatistics(generation); Random random = new Random(configuration.getRandomSeed()); while (!isSelectionSizeReached(selectionSize, generation)) { for (S solution : generation.getSolutions()) { if (selectSolution(solution, generation, random, statistics)) { generation.selectSolution(solution); if (isSelectionSizeReached(selectionSize, generation)) { break; } } } } }
private void updateFitnesses(FishState simState) { ObservableList<Fisher> fishers = simState.getFishers(); DoubleSummaryStatistics statistics[] = new DoubleSummaryStatistics[lastObservedFitnesses.length]; Arrays.setAll(statistics, value -> new DoubleSummaryStatistics()); //get each fishers' utility for(Fisher fisher : fishers) { int index = ((ReplicatorDrivenDestinationStrategy) fisher.getDestinationStrategy()).getStrategyIndex(); statistics[index].accept(objectiveFunction.computeCurrentFitness(fisher, fisher)); } for(int i=0; i<options.size(); i++) { lastObservedFitnesses[i] = statistics[i].getAverage(); } }
private void addDataGatherers(FishState state) { //first add data gatherers state.getYearlyDataSet().registerGatherer("Average Prediction Error", model -> { double size =model.getFishers().size(); if(size == 0) return Double.NaN; else { double total = 0; for(Fisher fisher1 : state.getFishers()) { DoubleSummaryStatistics errors = new DoubleSummaryStatistics(); for(Double error : ((HeatmapDestinationStrategy) fisher1.getDestinationStrategy()).getErrors()) errors.accept(error); total += errors.getAverage(); } return total/size; } }, Double.NaN); }
public MetaScores(List<Double> scores) { // A meta alert could be entirely alerts with no values. DoubleSummaryStatistics stats = scores .stream() .mapToDouble(a -> a) .summaryStatistics(); metaScores.put("max", stats.getMax()); metaScores.put("min", stats.getMin()); metaScores.put("average", stats.getAverage()); metaScores.put("count", stats.getCount()); metaScores.put("sum", stats.getSum()); // median isn't in the stats summary double[] arr = scores .stream() .mapToDouble(d -> d) .toArray(); metaScores.put("median", new Median().evaluate(arr)); }
@Test public void gauges() { Registry r = newRegistry(true, 10000); r.gauge(r.createId("foo", "a", "1")).set(1.0); r.gauge(r.createId("foo", "a", "2")).set(2.0); r.gauge(r.createId("bar")).set(7.0); Assert.assertEquals(3, r.gauges().count()); final DoubleSummaryStatistics valueSummary = r.gauges() .filter(Functions.nameEquals("foo")) .collect(Collectors.summarizingDouble(Gauge::value)); Assert.assertEquals(2, valueSummary.getCount()); Assert.assertEquals(3.0, valueSummary.getSum(), 1e-12); Assert.assertEquals(1.5, valueSummary.getAverage(), 1e-12); }
@Test public void double_summary_stats_with_stream() { DoubleSummaryStatistics stats = companies.stream() .mapToDouble((x) -> x.getRevenue()).summaryStatistics(); // average assertEquals(109.9425, stats.getAverage(), 0); // count assertEquals(4, stats.getCount(), 0); // max assertEquals(184.9, stats.getMax(), 0); // min assertEquals(12.1, stats.getMin(), 0); // sum assertEquals(439.77, stats.getSum(), 0); }
@Test public void double_summary_stats_stream_reduction_target() { DoubleSummaryStatistics stats = companies.stream().collect( Collectors.summarizingDouble(Company::getRevenue)); // average assertEquals(109.9425, stats.getAverage(), 0); // count assertEquals(4, stats.getCount(), 0); // max assertEquals(184.9, stats.getMax(), 0); // min assertEquals(12.1, stats.getMin(), 0); // sum assertEquals(439.77, stats.getSum(), 0); }
public static void main(String[] args) throws IOException { Path salesDataPath = Paths .get("src/main/resources/com/levelup/java/exercises/beginner/SalesData.txt") .toAbsolutePath(); //read all lines into a list of strings List<String> fileByLines = java.nio.file.Files .readAllLines(salesDataPath); //convert each string into a DoubleSummaryStatistics object List<DoubleSummaryStatistics> weeksSummary = new ArrayList<>(); for (String row : fileByLines) { // split on comma, map to double weeksSummary.add(Arrays.stream(row.split(",")) .mapToDouble(Double::valueOf).summaryStatistics()); } displayWeeklyStats(weeksSummary); displaySummaryResults(weeksSummary); }
public static void displaySummaryResults( List<DoubleSummaryStatistics> weeksSummary) { System.out.println("Total sales for all weeks: $" + weeksSummary.stream().mapToDouble(p -> p.getSum()).sum()); System.out.println("Average weekly sales: $" + weeksSummary.stream().mapToDouble(p -> p.getSum()).average() .getAsDouble()); System.out.println("The highest sales was $" + weeksSummary.stream().mapToDouble(p -> p.getSum()).max() .getAsDouble()); System.out.println("The lowest sales were made during " + weeksSummary.stream().mapToDouble(p -> p.getSum()).min() .getAsDouble()); }
public static void main(String[] args) { // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get a string of digits. System.out.print("Enter a string of digits: "); String input = keyboard.nextLine(); // close keyboard keyboard.close(); DoubleSummaryStatistics summaryStats = Stream.of(input.split("")) .mapToDouble(Double::valueOf).summaryStatistics(); System.out.println("The sum of numbers " + summaryStats.getSum()); System.out.println("The highest digit is " + summaryStats.getMax()); System.out.println("The lowest digit is " + summaryStats.getMin()); }
@Benchmark public Object[] combinedStatisticsJDK_parallel() { DoubleSummaryStatistics stats1 = Person.getJDKPeople().parallelStream().mapToDouble(Person::getHeightInInches).summaryStatistics(); DoubleSummaryStatistics stats2 = Person.getJDKPeople().parallelStream().mapToDouble(Person::getWeightInPounds).summaryStatistics(); IntSummaryStatistics stats3 = Person.getJDKPeople().parallelStream().mapToInt(Person::getAge).summaryStatistics(); return new Object[]{stats1, stats2, stats3}; }
@Benchmark public Object[] combinedStatisticsECStream_parallel() { DoubleSummaryStatistics stats1 = Person.getECPeople().parallelStream().mapToDouble(Person::getHeightInInches).summaryStatistics(); DoubleSummaryStatistics stats2 = Person.getECPeople().parallelStream().mapToDouble(Person::getWeightInPounds).summaryStatistics(); IntSummaryStatistics stats3 = Person.getECPeople().parallelStream().mapToInt(Person::getAge).summaryStatistics(); return new Object[]{stats1, stats2, stats3}; }
@Benchmark public Object[] combinedStatisticsJDK_serial() { DoubleSummaryStatistics stats1 = Person.getJDKPeople().stream().mapToDouble(Person::getHeightInInches).summaryStatistics(); DoubleSummaryStatistics stats2 = Person.getJDKPeople().stream().mapToDouble(Person::getWeightInPounds).summaryStatistics(); IntSummaryStatistics stats3 = Person.getJDKPeople().stream().mapToInt(Person::getAge).summaryStatistics(); return new Object[]{stats1, stats2, stats3}; }
@Benchmark public Object[] combinedStatisticsECLazy_serial() { DoubleSummaryStatistics stats1 = Person.getECPeople().asLazy().collectDouble(Person::getHeightInInches).summaryStatistics(); DoubleSummaryStatistics stats2 = Person.getECPeople().asLazy().collectDouble(Person::getWeightInPounds).summaryStatistics(); IntSummaryStatistics stats3 = Person.getECPeople().asLazy().collectInt(Person::getAge).summaryStatistics(); return new Object[]{stats1, stats2, stats3}; }
@Benchmark public Object[] combinedStatisticsECEager_serial() { DoubleSummaryStatistics stats1 = Person.getECPeople().summarizeDouble(Person::getHeightInInches); DoubleSummaryStatistics stats2 = Person.getECPeople().summarizeDouble(Person::getWeightInPounds); IntSummaryStatistics stats3 = Person.getECPeople().summarizeInt(Person::getAge); return new Object[]{stats1, stats2, stats3}; }
@Test public void weightStatisticsJDK() { DoubleSummaryStatistics stats = Person.getJDKPeople().stream().mapToDouble(Person::getWeightInPounds).summaryStatistics(); Assert.assertEquals(Person.NUMBER_OF_PEOPLE, stats.getCount()); }
@Test public void weightStatisticsEC() { DoubleSummaryStatistics stats = Person.getECPeople().asLazy().collectDouble(Person::getWeightInPounds).summaryStatistics(); Assert.assertEquals(Person.NUMBER_OF_PEOPLE, stats.getCount()); }
@Test public void heightStatisticsJDK() { DoubleSummaryStatistics stats = Person.getJDKPeople().stream().mapToDouble(Person::getHeightInInches).summaryStatistics(); Assert.assertEquals(Person.NUMBER_OF_PEOPLE, stats.getCount()); }
@Test public void heightStatisticsEC() { DoubleSummaryStatistics stats = Person.getECPeople().asLazy().collectDouble(Person::getHeightInInches).summaryStatistics(); Assert.assertEquals(Person.NUMBER_OF_PEOPLE, stats.getCount()); }
@Test public void getDonutPriceStatistics() { DoubleSummaryStatistics stats1 = this.donutShop.getDonutPriceStatistics(this.today, this.today); Assert.assertEquals(9.45d, stats1.getSum(), 0.01); Assert.assertEquals(1.35d, stats1.getAverage(), 0.01); Assert.assertEquals(7, stats1.getCount(), 0.01); DoubleSummaryStatistics stats2 = this.donutShop.getDonutPriceStatistics(this.tomorrow, this.tomorrow); Assert.assertEquals(12.0d, stats2.getSum(), 0.01); Assert.assertEquals(1.0d, stats2.getAverage(), 0.01); Assert.assertEquals(12, stats2.getCount(), 0.01); DoubleSummaryStatistics stats3 = this.donutShop.getDonutPriceStatistics(this.yesterday, this.yesterday); Assert.assertEquals(20.9d, stats3.getSum(), 0.001); Assert.assertEquals(0.95d, stats3.getAverage(), 0.01); Assert.assertEquals(22, stats3.getCount(), 0.01); DoubleSummaryStatistics statsTotal = this.donutShop.getDonutPriceStatistics(this.yesterday, this.tomorrow); Assert.assertEquals(42.35d, statsTotal.getSum(), 0.01); Assert.assertEquals(1.03d, statsTotal.getAverage(), 0.01); Assert.assertEquals(41, statsTotal.getCount(), 0.01); Assert.assertEquals(0.95, statsTotal.getMin(), 0.01); Assert.assertEquals(1.35, statsTotal.getMax(), 0.01); }
public void testDoubleStatistics() { List<DoubleSummaryStatistics> instances = new ArrayList<>(); instances.add(countTo(1000).stream().collect(Collectors.summarizingDouble(i -> i))); instances.add(countTo(1000).stream().mapToDouble(i -> i).summaryStatistics()); instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingDouble(i -> i))); instances.add(countTo(1000).parallelStream().mapToDouble(i -> i).summaryStatistics()); for (DoubleSummaryStatistics stats : instances) { assertEquals(stats.getCount(), 1000); assertEquals(stats.getSum(), (double) countTo(1000).stream().mapToInt(i -> i).sum()); assertEquals(stats.getMax(), 1000.0); assertEquals(stats.getMin(), 1.0); } }
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()); }
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)); }
@Test public void summaryStatistics() { DoubleSummaryStatistics result = this.parallelStreamSupportMock.summaryStatistics(); verify(this.delegateMock).summaryStatistics(); assertEquals(this.summaryStatistics, result); }
/** * @param graphTransactions size > 1 */ private void addGraphTransactionsToPointList(List<GraphTransaction> graphTransactions, double minRelativeStartTimeMillis, double maxRelativeEndTimeMillis, double maxDurationMillis) { long intervalCount = Math.min(99, graphTransactions.size()); double totalRange = maxRelativeEndTimeMillis - minRelativeStartTimeMillis; double intervalRange = totalRange / intervalCount; int gtIndex = 0; for (int i = 0; i < intervalCount && gtIndex < graphTransactions.size(); i++) { double rangeStart = minRelativeStartTimeMillis + (intervalRange * i); double rangeEnd = i == intervalCount - 1 ? Double.MAX_VALUE : rangeStart + intervalRange; boolean inRange = true; DoubleStream.Builder durationsBuilders = DoubleStream.builder(); while (gtIndex < graphTransactions.size() && inRange) { GraphTransaction graphTransaction = graphTransactions.get(gtIndex); inRange = graphTransaction.relativeStartTimeMillis >= rangeStart && graphTransaction.relativeStartTimeMillis < rangeEnd; if (inRange) { durationsBuilders.add(graphTransaction.durationMillis); gtIndex++; } } DoubleSummaryStatistics durationsStatistics = durationsBuilders.build().summaryStatistics(); if (durationsStatistics.getCount() > 0) { long y = Math.round(durationsStatistics.getAverage() / maxDurationMillis * 100); points.add(new Point(i, y)); } } }
/** * {@code Serializable} variant of {@link * Collectors#summarizingDouble(ToDoubleFunction) * java.util.stream.Collectors#summarizingDouble(ToDoubleFunction)} */ public static <T> DistributedCollector<T, ?, DoubleSummaryStatistics> summarizingDouble( DistributedToDoubleFunction<? super T> mapper ) { return new DistributedCollectorImpl<>( DistributedDoubleSummaryStatistics::new, (a, t) -> a.accept(mapper.applyAsDouble(t)), (s1, s2) -> { s1.combine(s2); return s1; }); }
@Test public void summaryStatistics() { DoubleSummaryStatistics longSummaryStatistics = stream.summaryStatistics(); assertEquals(COUNT, longSummaryStatistics.getCount()); assertEquals(COUNT - 1, longSummaryStatistics.getMax(), 0D); assertEquals(0, longSummaryStatistics.getMin(), 0D); assertEquals(COUNT * (COUNT - 1) / 2, longSummaryStatistics.getSum(), 0D); assertEquals((COUNT - 1) / 2D, longSummaryStatistics.getAverage(), 0D); }