|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License; |
| 4 | + * you may not use this file except in compliance with the Elastic License. |
| 5 | + */ |
| 6 | +package org.elasticsearch.xpack.ml.logstructurefinder; |
| 7 | + |
| 8 | +import java.util.ArrayList; |
| 9 | +import java.util.Collection; |
| 10 | +import java.util.Comparator; |
| 11 | +import java.util.LinkedHashMap; |
| 12 | +import java.util.List; |
| 13 | +import java.util.Map; |
| 14 | +import java.util.SortedMap; |
| 15 | +import java.util.TreeMap; |
| 16 | +import java.util.stream.Collectors; |
| 17 | + |
| 18 | +/** |
| 19 | + * Calculate statistics for a set of scalar field values. |
| 20 | + * Count, cardinality (distinct count) and top hits (most common values) are always calculated. |
| 21 | + * Extra statistics are calculated if the field is numeric: min, max, mean and median. |
| 22 | + */ |
| 23 | +public class FieldStatsCalculator { |
| 24 | + |
| 25 | + private long count; |
| 26 | + private SortedMap<String, Integer> countsByStringValue = new TreeMap<>(); |
| 27 | + private SortedMap<Double, Integer> countsByNumericValue = new TreeMap<>(); |
| 28 | + |
| 29 | + /** |
| 30 | + * Add a collection of values to the calculator. |
| 31 | + * The values to be added can be combined by the caller and added in a |
| 32 | + * single call to this method or added in multiple calls to this method. |
| 33 | + * @param fieldValues Zero or more values to add. May not be <code>null</code>. |
| 34 | + */ |
| 35 | + public void accept(Collection<String> fieldValues) { |
| 36 | + |
| 37 | + count += fieldValues.size(); |
| 38 | + |
| 39 | + for (String fieldValue : fieldValues) { |
| 40 | + |
| 41 | + countsByStringValue.compute(fieldValue, (k, v) -> (v == null) ? 1 : (1 + v)); |
| 42 | + |
| 43 | + if (countsByNumericValue != null) { |
| 44 | + |
| 45 | + try { |
| 46 | + countsByNumericValue.compute(Double.valueOf(fieldValue), (k, v) -> (v == null) ? 1 : (1 + v)); |
| 47 | + } catch (NumberFormatException e) { |
| 48 | + countsByNumericValue = null; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Calculate field statistics based on the previously accepted values. |
| 56 | + * @param numTopHits The maximum number of entries to include in the top hits. |
| 57 | + * @return The calculated field statistics. |
| 58 | + */ |
| 59 | + public FieldStats calculate(int numTopHits) { |
| 60 | + |
| 61 | + if (countsByNumericValue != null && countsByNumericValue.isEmpty() == false) { |
| 62 | + return new FieldStats(count, countsByNumericValue.size(), countsByNumericValue.firstKey(), countsByNumericValue.lastKey(), |
| 63 | + calculateMean(), calculateMedian(), findNumericTopHits(numTopHits)); |
| 64 | + } else { |
| 65 | + return new FieldStats(count, countsByStringValue.size(), findStringTopHits(numTopHits)); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + Double calculateMean() { |
| 70 | + |
| 71 | + assert countsByNumericValue != null; |
| 72 | + |
| 73 | + if (countsByNumericValue.isEmpty()) { |
| 74 | + return null; |
| 75 | + } |
| 76 | + |
| 77 | + double runningCount = 0.0; |
| 78 | + double runningMean = Double.NaN; |
| 79 | + |
| 80 | + for (Map.Entry<Double, Integer> entry : countsByNumericValue.entrySet()) { |
| 81 | + |
| 82 | + double entryCount = (double) entry.getValue(); |
| 83 | + double newRunningCount = runningCount + entryCount; |
| 84 | + |
| 85 | + // Updating a running mean like this is more numerically stable than using (sum / count) |
| 86 | + if (runningCount > 0.0) { |
| 87 | + runningMean = runningMean * (runningCount / newRunningCount) + entry.getKey() * (entryCount / newRunningCount); |
| 88 | + } else if (entryCount > 0.0) { |
| 89 | + runningMean = entry.getKey(); |
| 90 | + } |
| 91 | + |
| 92 | + runningCount = newRunningCount; |
| 93 | + } |
| 94 | + |
| 95 | + return runningMean; |
| 96 | + } |
| 97 | + |
| 98 | + Double calculateMedian() { |
| 99 | + |
| 100 | + assert countsByNumericValue != null; |
| 101 | + |
| 102 | + if (count % 2 == 1) { |
| 103 | + |
| 104 | + // Simple case - median is middle value |
| 105 | + long targetCount = count / 2 + 1; |
| 106 | + long currentUpperBound = 0; |
| 107 | + |
| 108 | + for (Map.Entry<Double, Integer> entry : countsByNumericValue.entrySet()) { |
| 109 | + |
| 110 | + currentUpperBound += entry.getValue(); |
| 111 | + |
| 112 | + if (currentUpperBound >= targetCount) { |
| 113 | + return entry.getKey(); |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + } else { |
| 118 | + |
| 119 | + // More complicated case - median is average of two middle values |
| 120 | + long target1Count = count / 2; |
| 121 | + long target2Count = target1Count + 1; |
| 122 | + double target1Value = Double.NaN; |
| 123 | + long prevUpperBound = -1; |
| 124 | + long currentUpperBound = 0; |
| 125 | + |
| 126 | + for (Map.Entry<Double, Integer> entry : countsByNumericValue.entrySet()) { |
| 127 | + |
| 128 | + currentUpperBound += entry.getValue(); |
| 129 | + |
| 130 | + if (currentUpperBound >= target2Count) { |
| 131 | + |
| 132 | + if (prevUpperBound < target1Count) { |
| 133 | + // Both target values are the same |
| 134 | + return entry.getKey(); |
| 135 | + } else { |
| 136 | + return (target1Value + entry.getKey()) / 2.0; |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + if (currentUpperBound >= target1Count) { |
| 141 | + target1Value = entry.getKey(); |
| 142 | + } |
| 143 | + |
| 144 | + prevUpperBound = currentUpperBound; |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + return null; |
| 149 | + } |
| 150 | + |
| 151 | + List<Map<String, Object>> findNumericTopHits(int numTopHits) { |
| 152 | + assert countsByNumericValue != null; |
| 153 | + return findTopHits(numTopHits, countsByNumericValue, Comparator.comparing(Map.Entry<Double, Integer>::getKey)); |
| 154 | + } |
| 155 | + |
| 156 | + List<Map<String, Object>> findStringTopHits(int numTopHits) { |
| 157 | + return findTopHits(numTopHits, countsByStringValue, Comparator.comparing(Map.Entry<String, Integer>::getKey)); |
| 158 | + } |
| 159 | + |
| 160 | + /** |
| 161 | + * Order by descending count, with a secondary sort to ensure reproducibility of results. |
| 162 | + */ |
| 163 | + private static <T> List<Map<String, Object>> findTopHits(int numTopHits, Map<T, Integer> countsByValue, |
| 164 | + Comparator<Map.Entry<T, Integer>> secondarySort) { |
| 165 | + |
| 166 | + List<Map.Entry<T, Integer>> sortedByCount = countsByValue.entrySet().stream() |
| 167 | + .sorted(Comparator.comparing(Map.Entry<T, Integer>::getValue, Comparator.reverseOrder()).thenComparing(secondarySort)) |
| 168 | + .limit(numTopHits).collect(Collectors.toList()); |
| 169 | + |
| 170 | + List<Map<String, Object>> topHits = new ArrayList<>(sortedByCount.size()); |
| 171 | + |
| 172 | + for (Map.Entry<T, Integer> entry : sortedByCount) { |
| 173 | + |
| 174 | + Map<String, Object> topHit = new LinkedHashMap<>(3); |
| 175 | + topHit.put("value", entry.getKey()); |
| 176 | + topHit.put("count", entry.getValue()); |
| 177 | + topHits.add(topHit); |
| 178 | + } |
| 179 | + |
| 180 | + return topHits; |
| 181 | + } |
| 182 | +} |
0 commit comments