blob: 420b87cbafcba14ce3a4298d4c3fe3a567d99794 [file] [log] [blame]
/*
* Copyright 2017, Yahoo! Inc.
* Licensed under the terms of the Apache License 2.0. See LICENSE file at the project root for terms.
*/
package com.yahoo.sketches.pig.tuple;
import java.io.IOException;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.apache.commons.math3.stat.inference.TTest;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import com.yahoo.memory.Memory;
import com.yahoo.sketches.tuple.ArrayOfDoublesSketch;
import com.yahoo.sketches.tuple.ArrayOfDoublesSketches;
/**
* Calculate p-values given two ArrayOfDoublesSketch. Each value in the sketch
* is treated as a separate metric measurement, and a p-value will be generated
* for each metric.
*/
public class ArrayOfDoublesSketchesToPValueEstimates extends EvalFunc<Tuple> {
@Override
public Tuple exec(final Tuple input) throws IOException {
if ((input == null) || (input.size() != 2)) {
return null;
}
// Get the two sketches
final DataByteArray dbaA = (DataByteArray) input.get(0);
final DataByteArray dbaB = (DataByteArray) input.get(1);
final ArrayOfDoublesSketch sketchA = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dbaA.get()));
final ArrayOfDoublesSketch sketchB = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dbaB.get()));
// Check that the size of the arrays in the sketches are the same
if (sketchA.getNumValues() != sketchB.getNumValues()) {
throw new IllegalArgumentException("Both sketches must have the same number of values");
}
// Store the number of metrics
final int numMetrics = sketchA.getNumValues();
// If the sketches contain fewer than 2 values, the p-value can't be calculated
if (sketchA.getRetainedEntries() < 2 || sketchB.getRetainedEntries() < 2) {
return null;
}
// Get the statistical summary from each sketch
final SummaryStatistics[] summariesA = ArrayOfDoublesSketchStats.sketchToSummaryStatistics(sketchA);
final SummaryStatistics[] summariesB = ArrayOfDoublesSketchStats.sketchToSummaryStatistics(sketchB);
// Calculate the p-values
final TTest tTest = new TTest();
final Tuple pValues = TupleFactory.getInstance().newTuple(numMetrics);
for (int i = 0; i < numMetrics; i++) {
// Pass the sampled values for each metric
pValues.set(i, tTest.tTest(summariesA[i], summariesB[i]));
}
return pValues;
}
}