Created
April 12, 2019 23:18
-
-
Save tdunning/d8d7337cbc6aaf31176f0babc6aaf95d to your computer and use it in GitHub Desktop.
Demonstrates the summarization of database fields using t-digest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.tdunning.tdigest.quality; | |
import com.google.common.collect.ImmutableList; | |
import com.google.common.io.Resources; | |
import com.tdunning.math.stats.MergingDigest; | |
import com.tdunning.math.stats.TDigest; | |
import org.junit.Test; | |
import java.io.File; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.text.ParseException; | |
import java.text.SimpleDateFormat; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Iterator; | |
import java.util.LinkedHashMap; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.stream.Stream; | |
public class DbStatsTest { | |
@Test | |
public void testColumnBreaks() throws IOException { | |
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); | |
List<String> keyFields = ImmutableList.of("c_integer", "c_bigint", "c_float", "c_timestamp"); | |
Map<String, TDigest> digests = new LinkedHashMap<>(); | |
keyFields.stream().forEach((key) -> digests.put(key, new MergingDigest(100))); | |
Stream<String> data = Files.lines(new File(Resources.getResource("db_data.csv").getFile()).toPath()); | |
List<String> headers = new ArrayList<>(); | |
data.forEach((String line) -> { | |
if (headers.size() == 0) { | |
// first line has field names | |
headers.addAll(Arrays.asList(line.split(","))); | |
} else { | |
Iterator<String> i = headers.iterator(); | |
for (String value : line.split(",")) { | |
String key = i.next(); | |
if ("c_timestamp".equals(key)) { | |
try { | |
digests.get(key).add(parser.parse(value).getTime()); | |
} catch (ParseException e) { | |
// ignore bad dates | |
} | |
} else if (keyFields.contains(key) && !"null".equals(value)) { | |
digests.get(key).add(Double.parseDouble(value)); | |
} | |
} | |
} | |
}); | |
for (String key : digests.keySet()) { | |
TDigest digest = digests.get(key); | |
System.out.printf("%s", key); | |
for (double q = 0; q < 1.05; q += 0.1) { | |
System.out.printf(",%10.5g", digest.quantile(q)); | |
} | |
System.out.printf("\n"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output looks like this. Note that the first number on each line is the minimum value and the last is the maximum.