index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/sampling/VarOptCrossLanguageTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.sampling;
import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES;
import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES;
import static org.apache.datasketches.common.TestUtil.cppPath;
import static org.apache.datasketches.common.TestUtil.javaPath;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.memory.Memory;
import org.testng.annotations.Test;
/**
* Serialize binary sketches to be tested by C++ code.
* Test deserialization of binary sketches serialized by C++ code.
*/
public class VarOptCrossLanguageTest {
static final double EPS = 1e-13;
@Test(groups = {GENERATE_JAVA_FILES})
public void generateSketchesLong() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000};
for (int n: nArr) {
final VarOptItemsSketch<Long> sk = VarOptItemsSketch.newInstance(32);
for (int i = 1; i <= n; i++) sk.update(Long.valueOf(i), 1.0);
Files.newOutputStream(javaPath.resolve("varopt_sketch_long_n" + n + "_java.sk"))
.write(sk.toByteArray(new ArrayOfLongsSerDe()));
}
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateSketchStringExact() throws IOException {
final VarOptItemsSketch<String> sketch = VarOptItemsSketch.newInstance(1024);
for (int i = 1; i <= 200; ++i) {
sketch.update(Integer.toString(i), 1000.0 / i);
}
Files.newOutputStream(javaPath.resolve("varopt_sketch_string_exact_java.sk"))
.write(sketch.toByteArray(new ArrayOfStringsSerDe()));
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateSketchLongSampling() throws IOException {
final VarOptItemsSketch<Long> sketch = VarOptItemsSketch.newInstance(1024);
for (long i = 0; i < 2000; ++i) {
sketch.update(i, 1.0);
}
// negative heavy items to allow a simple predicate to filter
sketch.update(-1L, 100000.0);
sketch.update(-2L, 110000.0);
sketch.update(-3L, 120000.0);
Files.newOutputStream(javaPath.resolve("varopt_sketch_long_sampling_java.sk"))
.write(sketch.toByteArray(new ArrayOfLongsSerDe()));
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateUnionDoubleSampling() throws IOException {
final int kSmall = 16;
final int n1 = 32;
final int n2 = 64;
final int kMax = 128;
// small k sketch, but sampling
VarOptItemsSketch<Double> sketch = VarOptItemsSketch.newInstance(kSmall);
for (int i = 0; i < n1; ++i) {
sketch.update(1.0 * i, 1.0);
}
sketch.update(-1.0, n1 * n1); // negative heavy item to allow a simple predicate to filter
final VarOptItemsUnion<Double> union = VarOptItemsUnion.newInstance(kMax);
union.update(sketch);
// another one, but different n to get a different per-item weight
sketch = VarOptItemsSketch.newInstance(kSmall);
for (int i = 0; i < n2; ++i) {
sketch.update(1.0 * i, 1.0);
}
union.update(sketch);
Files.newOutputStream(javaPath.resolve("varopt_union_double_sampling_java.sk"))
.write(union.toByteArray(new ArrayOfDoublesSerDe()));
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCppSketchLongs() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("varopt_sketch_long_n" + n + "_cpp.sk"));
final VarOptItemsSketch<Long> sk = VarOptItemsSketch.heapify(Memory.wrap(bytes), new ArrayOfLongsSerDe());
assertEquals(sk.getK(), 32);
assertEquals(sk.getN(), n);
assertEquals(sk.getNumSamples(), n > 10 ? 32 : n);
}
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCppSketchStringsExact() throws IOException {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("varopt_sketch_string_exact_cpp.sk"));
final VarOptItemsSketch<String> sk = VarOptItemsSketch.heapify(Memory.wrap(bytes), new ArrayOfStringsSerDe());
assertEquals(sk.getK(), 1024);
assertEquals(sk.getN(), 200);
assertEquals(sk.getNumSamples(), 200);
final SampleSubsetSummary ss = sk.estimateSubsetSum(item -> true);
double weight = 0;
for (int i = 1; i <= 200; ++i) weight += 1000.0 / i;
assertEquals(ss.getTotalSketchWeight(), weight, EPS);
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCppSketchLongsSampling() throws IOException {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("varopt_sketch_long_sampling_cpp.sk"));
final VarOptItemsSketch<Long> sk = VarOptItemsSketch.heapify(Memory.wrap(bytes), new ArrayOfLongsSerDe());
assertEquals(sk.getK(), 1024);
assertEquals(sk.getN(), 2003);
assertEquals(sk.getNumSamples(), 1024);
SampleSubsetSummary ss = sk.estimateSubsetSum(item -> true);
assertEquals(ss.getTotalSketchWeight(), 332000.0, EPS);
ss = sk.estimateSubsetSum(item -> item < 0);
assertEquals(ss.getEstimate(), 330000.0); // heavy item, weight is exact
ss = sk.estimateSubsetSum(item -> item >= 0);
assertEquals(ss.getEstimate(), 2000.0, EPS);
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCppUnionDoubleSampling() throws IOException {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("varopt_union_double_sampling_cpp.sk"));
final VarOptItemsUnion<Double> u = VarOptItemsUnion.heapify(Memory.wrap(bytes), new ArrayOfDoublesSerDe());
// must reduce k in the process
final VarOptItemsSketch<Double> sk = u.getResult();
assertTrue(sk.getK() < 128);
assertEquals(sk.getN(), 97);
// light items, ignoring the heavy one
SampleSubsetSummary ss = sk.estimateSubsetSum(item -> item >= 0);
assertEquals(ss.getEstimate(), 96.0, EPS);
assertEquals(ss.getTotalSketchWeight(), 96.0 + 1024.0, EPS);
}
}
| 2,400 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/sampling/VarOptItemsSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.sampling;
import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE;
import static org.apache.datasketches.sampling.PreambleUtil.PREAMBLE_LONGS_BYTE;
import static org.apache.datasketches.sampling.PreambleUtil.SER_VER_BYTE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesStateException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
public class VarOptItemsSketchTest {
static final double EPS = 1e-10;
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidK() {
VarOptItemsSketch.<Integer>newInstance(0);
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
final VarOptItemsSketch<Long> sketch = getUnweightedLongsVIS(16, 16);
final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe());
final WritableMemory mem = WritableMemory.writableWrap(bytes);
mem.putByte(SER_VER_BYTE, (byte) 0); // corrupt the serialization version
VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadFamily() {
final VarOptItemsSketch<Long> sketch = getUnweightedLongsVIS(32, 16);
final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe());
final WritableMemory mem = WritableMemory.writableWrap(bytes);
mem.putByte(FAMILY_BYTE, (byte) 0); // corrupt the family ID
VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
}
@Test
public void checkBadPreLongs() {
final VarOptItemsSketch<Long> sketch = getUnweightedLongsVIS(32, 33);
final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe());
final WritableMemory mem = WritableMemory.writableWrap(bytes);
// corrupt the preLongs count to 0
mem.putByte(PREAMBLE_LONGS_BYTE, (byte) (Family.VAROPT.getMinPreLongs() - 1));
try {
VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
} catch (final SketchesArgumentException e) {
// expected
}
mem.putByte(PREAMBLE_LONGS_BYTE, (byte) 2); // corrupt the preLongs count to 2
try {
VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
} catch (final SketchesArgumentException e) {
// expected
}
// corrupt the preLongs count to be too large
mem.putByte(PREAMBLE_LONGS_BYTE, (byte) (Family.VAROPT.getMaxPreLongs() + 1));
try {
VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
} catch (final SketchesArgumentException e) {
// expected
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadMemory() {
byte[] bytes = new byte[4];
Memory mem = Memory.wrap(bytes);
try {
PreambleUtil.getAndCheckPreLongs(mem);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
bytes = new byte[8];
bytes[0] = 2; // only 1 preLong worth of items in bytearray
mem = Memory.wrap(bytes);
PreambleUtil.getAndCheckPreLongs(mem);
}
@Test
public void checkMalformedPreamble() {
final int k = 50;
final VarOptItemsSketch<Long> sketch = getUnweightedLongsVIS(k, k);
final byte[] sketchBytes = sketch.toByteArray(new ArrayOfLongsSerDe());
final Memory srcMem = Memory.wrap(sketchBytes);
// we'll use the same initial sketch a few times, so grab a copy of it
final byte[] copyBytes = new byte[sketchBytes.length];
final WritableMemory mem = WritableMemory.writableWrap(copyBytes);
// copy the bytes
srcMem.copyTo(0, mem, 0, sketchBytes.length);
assertEquals(PreambleUtil.extractPreLongs(mem), PreambleUtil.VO_PRELONGS_WARMUP);
// no items in R but max preLongs
try {
PreambleUtil.insertPreLongs(mem, Family.VAROPT.getMaxPreLongs());
VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
} catch (final SketchesArgumentException e) {
assertTrue(e.getMessage().startsWith("Possible Corruption: "
+ Family.VAROPT.getMaxPreLongs() + " preLongs but"));
}
// refresh the copy
srcMem.copyTo(0, mem, 0, sketchBytes.length);
assertEquals(PreambleUtil.extractPreLongs(mem), PreambleUtil.VO_PRELONGS_WARMUP);
// negative H region count
try {
PreambleUtil.insertHRegionItemCount(mem, -1);
VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
} catch (final SketchesArgumentException e) {
assertTrue(e.getMessage().equals("Possible Corruption: H region count cannot be negative: -1"));
}
// refresh the copy
srcMem.copyTo(0, mem, 0, sketchBytes.length);
assertEquals(PreambleUtil.extractHRegionItemCount(mem), k);
// negative R region count
try {
PreambleUtil.insertRRegionItemCount(mem, -128);
VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
} catch (final SketchesArgumentException e) {
assertTrue(e.getMessage().equals("Possible Corruption: R region count cannot be negative: -128"));
}
// refresh the copy
srcMem.copyTo(0, mem, 0, sketchBytes.length);
assertEquals(PreambleUtil.extractRRegionItemCount(mem), 0);
// invalid k < 1
try {
PreambleUtil.insertK(mem, 0);
VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
} catch (final SketchesArgumentException e) {
assertTrue(e.getMessage().equals("Possible Corruption: k must be at least 1: 0"));
}
// refresh the copy
srcMem.copyTo(0, mem, 0, sketchBytes.length);
assertEquals(PreambleUtil.extractK(mem), k);
// invalid n < 0
try {
PreambleUtil.insertN(mem, -1024);
VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
} catch (final SketchesArgumentException e) {
assertTrue(e.getMessage().equals("Possible Corruption: n cannot be negative: -1024"));
}
}
@Test
public void checkEmptySketch() {
final VarOptItemsSketch<String> vis = VarOptItemsSketch.newInstance(5);
assertEquals(vis.getN(), 0);
assertEquals(vis.getNumSamples(), 0);
assertNull(vis.getSamplesAsArrays());
assertNull(vis.getSamplesAsArrays(Long.class));
final byte[] sketchBytes = vis.toByteArray(new ArrayOfStringsSerDe());
final Memory mem = Memory.wrap(sketchBytes);
// only minPreLongs bytes and should deserialize to empty
assertEquals(sketchBytes.length, Family.VAROPT.getMinPreLongs() << 3);
final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
final VarOptItemsSketch<String> loadedVis = VarOptItemsSketch.heapify(mem, serDe);
assertEquals(loadedVis.getNumSamples(), 0);
println("Empty sketch:");
println(" Preamble:");
VarOptItemsSketch.toString(sketchBytes);
println(VarOptItemsSketch.toString(mem));
println(" Sketch:");
println(vis.toString());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkNonEmptyDegenerateSketch() {
// make an empty serialized sketch, then copy the items into a
// PreambleUtil.VO_WARMUP_PRELONGS-sized byte array
// so there'll be no items, then clear the empty flag so it will try to load
// the rest.
final VarOptItemsSketch<String> vis = VarOptItemsSketch.newInstance(12, ResizeFactor.X2);
final byte[] sketchBytes = vis.toByteArray(new ArrayOfStringsSerDe());
final byte[] dstByteArr = new byte[PreambleUtil.VO_PRELONGS_WARMUP << 3];
final WritableMemory mem = WritableMemory.writableWrap(dstByteArr);
mem.putByteArray(0, sketchBytes, 0, sketchBytes.length);
// ensure non-empty but with H and R region sizes set to 0
PreambleUtil.insertFlags(mem, 0); // set not-empty
PreambleUtil.insertHRegionItemCount(mem, 0);
PreambleUtil.insertRRegionItemCount(mem, 0);
VarOptItemsSketch.heapify(mem, new ArrayOfStringsSerDe());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidWeight() {
final VarOptItemsSketch<String> vis = VarOptItemsSketch.newInstance(5);
try {
vis.update(null, 1.0); // should work fine
} catch (final SketchesArgumentException e) {
fail();
}
vis.update("invalidWeight", -1.0); // should fail
}
@Test
public void checkCorruptSerializedWeight() {
final VarOptItemsSketch<String> vis = VarOptItemsSketch.newInstance(24);
for (int i = 1; i < 10; ++i) {
vis.update(Integer.toString(i), i);
}
final byte[] sketchBytes = vis.toByteArray(new ArrayOfStringsSerDe(), String.class);
final WritableMemory mem = WritableMemory.writableWrap(sketchBytes);
// weights will be stored in the first double after the preamble
final int numPreLongs = PreambleUtil.extractPreLongs(mem);
final int weightOffset = numPreLongs << 3;
mem.putDouble(weightOffset, -1.25); // inject a negative weight
try {
VarOptItemsSketch.heapify(mem, new ArrayOfStringsSerDe());
fail();
} catch (final SketchesArgumentException e) {
assertTrue(e.getMessage().equals("Possible Corruption: Non-positive weight in "
+ "heapify(): -1.25"));
}
}
@Test
public void checkCumulativeWeight() {
final int k = 256;
final int n = 10 * k;
final VarOptItemsSketch<Long> sketch = VarOptItemsSketch.newInstance(k);
double inputSum = 0.0;
for (long i = 0; i < n; ++i) {
// generate weights above and below 1.0 using w ~ exp(5*N(0,1)) which covers about
// 10 orders of magnitude
final double w = Math.exp(5 * SamplingUtil.rand().nextGaussian());
inputSum += w;
sketch.update(i, w);
}
final VarOptItemsSamples<Long> samples = sketch.getSketchSamples();
double outputSum = 0;
for (VarOptItemsSamples<Long>.WeightedSample ws : samples) {
outputSum += ws.getWeight();
}
final double wtRatio = outputSum / inputSum;
assertTrue(Math.abs(wtRatio - 1.0) < EPS);
}
@Test
public void checkUnderFullSketchSerialization() {
final VarOptItemsSketch<Long> sketch = VarOptItemsSketch.newInstance(2048);
for (long i = 0; i < 10; ++i) {
sketch.update(i, 1.0);
}
assertEquals(sketch.getNumSamples(), 10);
final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe());
final Memory mem = Memory.wrap(bytes);
// ensure correct number of preLongs
assertEquals(PreambleUtil.extractPreLongs(mem), PreambleUtil.VO_PRELONGS_WARMUP);
final VarOptItemsSketch<Long> rebuilt
= VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
checkIfEqual(rebuilt, sketch);
}
@Test
public void checkEndOfWarmupSketchSerialization() {
final int k = 2048;
final VarOptItemsSketch<Long> sketch = getUnweightedLongsVIS(k, k);
final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe());
final Memory mem = Memory.wrap(bytes);
// ensure still only 2 preLongs
assertEquals(PreambleUtil.extractPreLongs(mem), PreambleUtil.VO_PRELONGS_WARMUP);
final VarOptItemsSketch<Long> rebuilt
= VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
checkIfEqual(rebuilt, sketch);
}
@Test
public void checkFullSketchSerialization() {
final VarOptItemsSketch<Long> sketch = VarOptItemsSketch.newInstance(32);
for (long i = 0; i < 32; ++i) {
sketch.update(i, 1.0);
}
sketch.update(100L, 100.0);
sketch.update(101L, 101.0);
assertEquals(sketch.getNumSamples(), 32);
// first 2 entries should be heavy and in heap order (smallest at root)
final VarOptItemsSamples<Long> samples = sketch.getSketchSamples();
final Long[] data = samples.items();
final double[] weights = samples.weights();
assertEquals(weights[0], 100.0);
assertEquals(weights[1], 101.0);
assertEquals((long) data[0], 100L);
assertEquals((long) data[1], 101L);
final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe());
final Memory mem = Memory.wrap(bytes);
// ensure 3 preLongs
assertEquals(PreambleUtil.extractPreLongs(mem), Family.VAROPT.getMaxPreLongs());
final VarOptItemsSketch<Long> rebuilt
= VarOptItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
checkIfEqual(rebuilt, sketch);
}
@Test
public void checkPseudoLightUpdate() {
final int k = 1024;
final VarOptItemsSketch<Long> sketch = getUnweightedLongsVIS(k, k + 1);
sketch.update(0L, 1.0); // k+2-nd update
// checking weights(0), assuming all k items are unweighted (and consequently in R)
// Expected: (k + 2) / |R| = (k+2) / k
final VarOptItemsSamples<Long> samples = sketch.getSketchSamples();
final double wtDiff = samples.weights(0) - ((1.0 * (k + 2)) / k);
assertTrue(Math.abs(wtDiff) < EPS);
}
@Test
public void checkPseudoHeavyUpdates() {
final int k = 1024;
final double wtScale = 10.0 * k;
final VarOptItemsSketch<Long> sketch = VarOptItemsSketch.newInstance(k);
for (long i = 0; i <= k; ++i) {
sketch.update(i, 1.0);
}
// Next k-1 updates should be updatePseudoHeavyGeneral()
// Last one should call updatePseudoHeavyREq1(), since we'll have added k-1 heavy
// items, leaving only 1 item left in R
for (long i = 1; i <= k; ++i) {
sketch.update(-i, k + (i * wtScale));
}
final VarOptItemsSamples<Long> samples = sketch.getSketchSamples();
final double[] weights = samples.weights();
// Don't know which R item is left, but should be only one at the end of the array
// Expected: k+1 + (min "heavy" item) / |R| = ((k+1) + (k+wtScale)) / 1 = wtScale + 2k + 1
double wtDiff = weights[k - 1] - (1.0 * (wtScale + (2 * k) + 1));
assertTrue(Math.abs(wtDiff) < EPS);
// Expected: 2nd lightest "heavy" item: k + 2*wtScale
wtDiff = weights[0] - (1.0 * (k + (2 * wtScale)));
assertTrue(Math.abs(wtDiff) < EPS);
}
@Test(expectedExceptions = SketchesStateException.class)
public void checkDecreaseKWithUnderfullSketch() {
final VarOptItemsSketch<Integer> sketch = VarOptItemsSketch.newInstanceAsGadget(5);
assertEquals(sketch.getK(), 5);
// shrink empty sketch
sketch.decreaseKBy1();
assertEquals(sketch.getK(), 4);
// insert 3 values
sketch.update(1, 1.0);
sketch.update(2, 2.0);
sketch.update(3, 3.0);
// shrink to k=3, should do nothing
assertEquals(sketch.getTotalWtR(), 0.0);
sketch.decreaseKBy1();
assertEquals(sketch.getTotalWtR(), 0.0);
// one more time, to k=2, which exist warmup phase
sketch.decreaseKBy1();
assertEquals(sketch.getHRegionCount(), 1);
assertEquals(sketch.getRRegionCount(), 1);
assertEquals(sketch.getTotalWtR(), 3.0);
// decrease twice more to trigger an exception
sketch.decreaseKBy1();
sketch.decreaseKBy1();
}
@Test
public void checkDecreaseKWithFullSketch() {
final int[] itemList = {10, 1, 9, 2, 8, 3, 7, 4, 6, 5};
final int startK = 7;
final int tgtK = 5;
// Create sketch with k = startK and another with k = tgtK. We'll then decrease k until
// they're equal and ensure the results "match"
final VarOptItemsSketch<Integer> sketch = VarOptItemsSketch.newInstanceAsGadget(startK);
final VarOptItemsSketch<Integer> tgtSketch = VarOptItemsSketch.newInstanceAsGadget(tgtK);
double totalWeight = 0.0;
for (int val : itemList) {
sketch.update(val, val);
tgtSketch.update(val, val);
totalWeight += val;
}
// larger sketch has heavy items, smaller does not
assertEquals(sketch.getHRegionCount(), 4);
assertEquals(sketch.getRRegionCount(), 3);
assertEquals(tgtSketch.getHRegionCount(), 0);
assertEquals(tgtSketch.getRRegionCount(), 5);
while (sketch.getK() > tgtK) {
sketch.decreaseKBy1();
}
assertEquals(sketch.getK(), tgtSketch.getK());
assertEquals(sketch.getHRegionCount(), 0);
assertTrue(Math.abs(sketch.getTau() - tgtSketch.getTau()) < EPS);
// decrease again from reservoir-only mode
sketch.decreaseKBy1();
assertEquals(sketch.getK(), tgtK - 1);
assertEquals(sketch.getK(), sketch.getRRegionCount());
assertEquals(sketch.getTotalWtR(), totalWeight);
}
@Test
public void checkReset() {
final int k = 25;
final VarOptItemsSketch<String> sketch = VarOptItemsSketch.newInstanceAsGadget(k);
sketch.update("a", 1.0);
sketch.update("b", 2.0);
sketch.update("c", 3.0);
sketch.update("d", 4.0);
assertEquals(sketch.getN(), 4);
assertEquals(sketch.getHRegionCount(), 4);
assertEquals(sketch.getRRegionCount(), 0);
assertEquals(sketch.getMark(0), false);
sketch.reset();
assertEquals(sketch.getN(), 0);
assertEquals(sketch.getHRegionCount(), 0);
assertEquals(sketch.getRRegionCount(), 0);
try {
sketch.getMark(0);
fail();
} catch (final IndexOutOfBoundsException e) {
// expected
}
// strip marks and try again
sketch.stripMarks();
for (int i = 0; i < (2 * k); ++i) {
sketch.update("a", 100.0 + i);
}
assertEquals(sketch.getN(), 2 * k);
assertEquals(sketch.getHRegionCount(), 0);
assertEquals(sketch.getRRegionCount(), k);
sketch.reset();
assertEquals(sketch.getN(), 0);
assertEquals(sketch.getHRegionCount(), 0);
assertEquals(sketch.getRRegionCount(), 0);
}
@Test
public void checkEstimateSubsetSum() {
final int k = 10;
final VarOptItemsSketch<Long> sketch = VarOptItemsSketch.newInstance(k);
// empty sketch -- all zeros
SampleSubsetSummary ss = sketch.estimateSubsetSum(item -> true);
assertEquals(ss.getEstimate(), 0.0);
assertEquals(ss.getTotalSketchWeight(), 0.0);
// add items, keeping in exact mode
double totalWeight = 0.0;
for (long i = 1; i <= (k - 1); ++i) {
sketch.update(i, 1.0 * i);
totalWeight += 1.0 * i;
}
ss = sketch.estimateSubsetSum(item -> true);
assertEquals(ss.getEstimate(), totalWeight);
assertEquals(ss.getLowerBound(), totalWeight);
assertEquals(ss.getUpperBound(), totalWeight);
assertEquals(ss.getTotalSketchWeight(), totalWeight);
// add a few more items, pushing to sampling mode
for (long i = k; i <= (k + 1); ++i) {
sketch.update(i, 1.0 * i);
totalWeight += 1.0 * i;
}
// predicate always true so estimate == upper bound
ss = sketch.estimateSubsetSum(item -> true);
assertEquals(ss.getEstimate(), totalWeight);
assertEquals(ss.getUpperBound(), totalWeight);
assertTrue(ss.getLowerBound() < totalWeight);
assertEquals(ss.getTotalSketchWeight(), totalWeight);
// predicate always false so estimate == lower bound == 0.0
ss = sketch.estimateSubsetSum(item -> false);
assertEquals(ss.getEstimate(), 0.0);
assertEquals(ss.getLowerBound(), 0.0);
assertTrue(ss.getUpperBound() > 0.0);
assertEquals(ss.getTotalSketchWeight(), totalWeight);
// finally, a non-degenerate predicate
// insert negative items with identical weights, filter for negative weights only
for (long i = 1; i <= (k + 1); ++i) {
sketch.update(-i, 1.0 * i);
totalWeight += 1.0 * i;
}
ss = sketch.estimateSubsetSum(item -> item < 0);
assertTrue(ss.getEstimate() >= ss.getLowerBound());
assertTrue(ss.getEstimate() <= ss.getUpperBound());
// allow pretty generous bounds when testing
assertTrue(ss.getLowerBound() < (totalWeight / 1.4));
assertTrue(ss.getUpperBound() > (totalWeight / 2.6));
assertEquals(ss.getTotalSketchWeight(), totalWeight);
// for good measure, test a different type
final VarOptItemsSketch<Boolean> boolSketch = VarOptItemsSketch.newInstance(k);
totalWeight = 0.0;
for (int i = 1; i <= (k - 1); ++i) {
boolSketch.update((i % 2) == 0, 1.0 * i);
totalWeight += i;
}
ss = boolSketch.estimateSubsetSum(item -> !item);
assertTrue(ss.getEstimate() == ss.getLowerBound());
assertTrue(ss.getEstimate() == ss.getUpperBound());
assertTrue(ss.getEstimate() < totalWeight); // exact mode, so know it must be strictly less
}
/* Returns a sketch of size k that has been presented with n items. Use n = k+1 to obtain a
sketch that has just reached the sampling phase, so that the next update() is handled by
one of the non-warmup routes.
*/
static VarOptItemsSketch<Long> getUnweightedLongsVIS(final int k, final int n) {
final VarOptItemsSketch<Long> sketch = VarOptItemsSketch.newInstance(k);
for (long i = 0; i < n; ++i) {
sketch.update(i, 1.0);
}
return sketch;
}
private static <T> void checkIfEqual(final VarOptItemsSketch<T> s1,
final VarOptItemsSketch<T> s2) {
assertEquals(s1.getK(), s2.getK(), "Sketches have different values of k");
assertEquals(s1.getNumSamples(), s2.getNumSamples(), "Sketches have different sample counts");
final int len = s1.getNumSamples();
final VarOptItemsSamples<T> r1 = s1.getSketchSamples();
final VarOptItemsSamples<T> r2 = s2.getSketchSamples();
// next 2 lines also trigger copying results
assertEquals(len, r1.getNumSamples());
assertEquals(r1.getNumSamples(), r2.getNumSamples());
for (int i = 0; i < len; ++i) {
assertEquals(r1.items(i), r2.items(i), "Data values differ at sample " + i);
assertEquals(r1.weights(i), r2.weights(i), "Weights differ at sample " + i);
}
}
/**
* Wrapper around System.out.println() allowing a simple way to disable logging in tests
* @param msg The message to print
*/
private static void println(final String msg) {
//System.out.println(msg);
}
}
| 2,401 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/sampling/VarOptItemsSamplesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.sampling;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.testng.annotations.Test;
/**
* @author Jon Malkin
*/
public class VarOptItemsSamplesTest {
@Test
public void compareIteratorToArrays() {
final int k = 64;
final int n = 1024;
final VarOptItemsSketch<Long> sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, n);
// and a few heavy items
sketch.update(n * 10L, n * 10.0);
sketch.update(n * 11L, n * 11.0);
sketch.update(n * 12L, n * 12.0);
final VarOptItemsSamples<Long> samples = sketch.getSketchSamples();
final Long[] items = samples.items();
final double[] weights = samples.weights();
int i = 0;
for (VarOptItemsSamples<Long>.WeightedSample ws : samples) {
assertEquals(ws.getWeight(), weights[i]);
assertEquals(ws.getItem(), items[i]);
++i;
}
}
@Test(expectedExceptions = ConcurrentModificationException.class)
public void checkConcurrentModification() {
final int k = 128;
final VarOptItemsSketch<Long> sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, k);
final VarOptItemsSamples<Long> samples = sketch.getSketchSamples();
for (VarOptItemsSamples<Long>.WeightedSample ws : samples) {
if (ws.getItem() > (k / 2)) { // guaranteed to exist somewhere in the sketch
sketch.update(-1L, 1.0);
}
}
fail();
}
@Test(expectedExceptions = ConcurrentModificationException.class)
public void checkWeightCorrectingConcurrentModification() {
final int k = 128;
// sketch needs to be in sampling mode
final VarOptItemsSketch<Long> sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, 2 * k);
final Iterator<VarOptItemsSamples<Long>.WeightedSample> iter;
iter = sketch.getSketchSamples().getWeightCorrRIter();
int i = 0;
while (iter.hasNext()) {
iter.next();
if (++i > (k / 2)) {
sketch.update(-1L, 1.0);
}
}
fail();
}
@Test(expectedExceptions = NoSuchElementException.class)
public void checkReadingPastEndOfIterator() {
final int k = 128;
final VarOptItemsSketch<Long> sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, k);
final Iterator<VarOptItemsSamples<Long>.WeightedSample> iter;
iter = sketch.getSketchSamples().iterator();
while (iter.hasNext()) {
iter.next();
}
iter.next(); // no more elements
fail();
}
@Test(expectedExceptions = NoSuchElementException.class)
public void checkWeightCorrectionReadingPastEndOfIterator() {
final int k = 128;
final VarOptItemsSketch<Long> sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, k);
final Iterator<VarOptItemsSamples<Long>.WeightedSample> iter;
iter = sketch.getSketchSamples().getWeightCorrRIter();
while (iter.hasNext()) {
iter.next();
}
iter.next(); // no more elements
fail();
}
@Test
public void checkPolymorphicBaseClass() {
// use setClass()
final VarOptItemsSketch<Number> sketch = VarOptItemsSketch.newInstance(12);
sketch.update(1, 0.5);
sketch.update(2L, 1.7);
sketch.update(3.0f, 2.0);
sketch.update(4.0, 3.1);
try {
final VarOptItemsSamples<Number> samples = sketch.getSketchSamples();
// will try to create array based on type of first item in the array and fail
samples.items();
fail();
} catch (final ArrayStoreException e) {
// expected
}
final VarOptItemsSamples<Number> samples = sketch.getSketchSamples();
samples.setClass(Number.class);
assertEquals(samples.items(0), 1);
assertEquals(samples.items(1), 2L);
assertEquals(samples.items(2), 3.0f);
assertEquals(samples.items(3), 4.0);
}
@Test
public void checkEmptySketch() {
// verify what happens when n_ == 0
final VarOptItemsSketch<String> sketch = VarOptItemsSketch.newInstance(32);
assertEquals(sketch.getNumSamples(), 0);
final VarOptItemsSamples<String> samples = sketch.getSketchSamples();
assertEquals(samples.getNumSamples(), 0);
assertNull(samples.items());
assertNull(samples.items(0));
assertNull(samples.weights());
assertTrue(Double.isNaN(samples.weights(0)));
}
@Test
public void checkUnderFullSketchIterator() {
// needed to fully cover iterator's next() and hasNext() conditions
final int k = 128;
final VarOptItemsSketch<Long> sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, k / 2);
final VarOptItemsSamples<Long> samples = sketch.getSketchSamples();
for (VarOptItemsSamples<Long>.WeightedSample ws : samples) {
assertTrue((ws.getItem() >= 0) && (ws.getItem() < (k / 2)));
}
}
}
| 2,402 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/sampling/ReservoirLongsSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.sampling;
import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE;
import static org.apache.datasketches.sampling.PreambleUtil.PREAMBLE_LONGS_BYTE;
import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SIZE_INT;
import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SIZE_SHORT;
import static org.apache.datasketches.sampling.PreambleUtil.SER_VER_BYTE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesException;
import org.apache.datasketches.common.SketchesStateException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
public class ReservoirLongsSketchTest {
private static final double EPS = 1e-8;
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidK() {
ReservoirLongsSketch.newInstance(0);
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadPreLongs() {
final WritableMemory mem = getBasicSerializedRLS();
mem.putByte(PREAMBLE_LONGS_BYTE, (byte) 0); // corrupt the preLongs count
ReservoirLongsSketch.heapify(mem);
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
final WritableMemory mem = getBasicSerializedRLS();
mem.putByte(SER_VER_BYTE, (byte) 0); // corrupt the serialization version
ReservoirLongsSketch.heapify(mem);
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadFamily() {
final WritableMemory mem = getBasicSerializedRLS();
mem.putByte(FAMILY_BYTE, (byte) 0); // corrupt the family ID
ReservoirLongsSketch.heapify(mem);
fail();
}
@Test
public void checkEmptySketch() {
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(5);
assertTrue(rls.getSamples() == null);
final byte[] sketchBytes = rls.toByteArray();
final Memory mem = Memory.wrap(sketchBytes);
// only minPreLongs bytes and should deserialize to empty
assertEquals(sketchBytes.length, Family.RESERVOIR.getMinPreLongs() << 3);
final ReservoirLongsSketch loadedRls = ReservoirLongsSketch.heapify(mem);
assertEquals(loadedRls.getNumSamples(), 0);
println("Empty sketch:");
println(rls.toString());
ReservoirLongsSketch.toString(sketchBytes);
ReservoirLongsSketch.toString(mem);
}
@Test
public void checkUnderFullReservoir() {
final int k = 128;
final int n = 64;
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k);
for (int i = 0; i < n; ++i) {
rls.update(i);
}
assertEquals(rls.getNumSamples(), n);
final long[] data = rls.getSamples();
assertEquals(rls.getNumSamples(), rls.getN());
assertNotNull(data);
assertEquals(data.length, n);
// items in submit order until reservoir at capacity so check
for (int i = 0; i < n; ++i) {
assertEquals(data[i], i);
}
validateSerializeAndDeserialize(rls);
}
@Test
public void checkFullReservoir() {
final int k = 1000;
final int n = 2000;
// specify smaller ResizeFactor to ensure multiple resizes
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k, ResizeFactor.X2);
for (int i = 0; i < n; ++i) {
rls.update(i);
}
assertEquals(rls.getNumSamples(), rls.getK());
validateSerializeAndDeserialize(rls);
println("Full reservoir:");
println(rls.toString());
}
@Test
public void checkDownsampledCopy() {
final int k = 256;
final int tgtK = 64;
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k);
// check status at 3 points:
// 1. n < encTgtK
// 2. encTgtK < n < k
// 3. n > k
int i;
for (i = 0; i < (tgtK - 1); ++i) {
rls.update(i);
}
ReservoirLongsSketch dsCopy = rls.downsampledCopy(tgtK);
assertEquals(dsCopy.getK(), tgtK);
// should be identical other than value of k, which isn't checked here
validateReservoirEquality(rls, dsCopy);
// check condition 2 next
for (; i < (k - 1); ++i) {
rls.update(i);
}
assertEquals(rls.getN(), k - 1);
dsCopy = rls.downsampledCopy(tgtK);
assertEquals(dsCopy.getN(), rls.getN());
assertEquals(dsCopy.getNumSamples(), tgtK);
// and now condition 3
for (; i < (2 * k); ++i) {
rls.update(i);
}
assertEquals(rls.getN(), 2 * k);
dsCopy = rls.downsampledCopy(tgtK);
assertEquals(dsCopy.getN(), rls.getN());
assertEquals(dsCopy.getNumSamples(), tgtK);
}
@Test
public void checkBadConstructorArgs() {
final long[] data = new long[128];
for (int i = 0; i < 128; ++i) {
data[i] = i;
}
final ResizeFactor rf = ResizeFactor.X8;
// no items
try {
ReservoirLongsSketch.getInstance(null, 128, rf, 128);
fail();
} catch (final SketchesException e) {
assertTrue(e.getMessage().contains("null reservoir"));
}
// size too small
try {
ReservoirLongsSketch.getInstance(data, 128, rf, 1);
fail();
} catch (final SketchesException e) {
assertTrue(e.getMessage().contains("size less than 2"));
}
// configured reservoir size smaller than items length
try {
ReservoirLongsSketch.getInstance(data, 128, rf, 64);
fail();
} catch (final SketchesException e) {
assertTrue(e.getMessage().contains("max size less than array length"));
}
// too many items seen vs items length, full sketch
try {
ReservoirLongsSketch.getInstance(data, 512, rf, 256);
fail();
} catch (final SketchesException e) {
assertTrue(e.getMessage().contains("too few samples"));
}
// too many items seen vs items length, under-full sketch
try {
ReservoirLongsSketch.getInstance(data, 256, rf, 256);
fail();
} catch (final SketchesException e) {
assertTrue(e.getMessage().contains("too few samples"));
}
}
@Test
public void checkSketchCapacity() {
final long[] data = new long[64];
final long itemsSeen = (1L << 48) - 2;
final ReservoirLongsSketch rls = ReservoirLongsSketch.getInstance(data, itemsSeen,
ResizeFactor.X8, data.length);
// this should work, the next should fail
rls.update(0);
try {
rls.update(0);
fail();
} catch (final SketchesStateException e) {
assertTrue(e.getMessage().contains("Sketch has exceeded capacity for total items seen"));
}
rls.reset();
assertEquals(rls.getN(), 0);
rls.update(1L);
assertEquals(rls.getN(), 1L);
}
@Test
public void checkSampleWeight() {
final int k = 32;
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k);
for (int i = 0; i < (k / 2); ++i) {
rls.update(i);
}
assertEquals(rls.getImplicitSampleWeight(), 1.0); // should be exact value here
// will have 3k/2 total samples when done
for (int i = 0; i < k; ++i) {
rls.update(i);
}
assertTrue(Math.abs(rls.getImplicitSampleWeight() - 1.5) < EPS);
}
/*
@Test
public void checkReadOnlyHeapify() {
Memory sketchMem = getBasicSerializedRLS();
// Load from read-only and writable memory to ensure they deserialize identically
ReservoirLongsSketch rls = ReservoirLongsSketch.heapify(sketchMem.asReadOnlyMemory());
ReservoirLongsSketch fromWritable = ReservoirLongsSketch.heapify(sketchMem);
validateReservoirEquality(rls, fromWritable);
// Same with an empty sketch
final byte[] sketchBytes = ReservoirLongsSketch.newInstance(32).toByteArray();
sketchMem = new NativeMemory(sketchBytes);
rls = ReservoirLongsSketch.heapify(sketchMem.asReadOnlyMemory());
fromWritable = ReservoirLongsSketch.heapify(sketchMem);
validateReservoirEquality(rls, fromWritable);
}
*/
@Test
public void checkVersionConversion() {
// version change from 1 to 2 only impact first preamble long, so empty sketch is sufficient
final int k = 32768;
final short encK = ReservoirSize.computeSize(k);
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k);
final byte[] sketchBytesOrig = rls.toByteArray();
// get a new byte[], manually revert to v1, then reconstruct
final byte[] sketchBytes = rls.toByteArray();
final WritableMemory sketchMem = WritableMemory.writableWrap(sketchBytes);
sketchMem.putByte(SER_VER_BYTE, (byte) 1);
sketchMem.putInt(RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes
sketchMem.putShort(RESERVOIR_SIZE_SHORT, encK);
final ReservoirLongsSketch rebuilt = ReservoirLongsSketch.heapify(sketchMem);
final byte[] rebuiltBytes = rebuilt.toByteArray();
assertEquals(sketchBytesOrig.length, rebuiltBytes.length);
for (int i = 0; i < sketchBytesOrig.length; ++i) {
assertEquals(sketchBytesOrig[i], rebuiltBytes[i]);
}
}
@Test
public void checkSetAndGetValue() {
final int k = 20;
final int tgtIdx = 5;
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k);
for (int i = 0; i < k; ++i) {
rls.update(i);
}
assertEquals(rls.getValueAtPosition(tgtIdx), tgtIdx);
rls.insertValueAtPosition(-1, tgtIdx);
assertEquals(rls.getValueAtPosition(tgtIdx), -1);
}
@Test
public void checkBadSetAndGetValue() {
final int k = 20;
final int tgtIdx = 5;
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k);
try {
rls.getValueAtPosition(0);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
for (int i = 0; i < k; ++i) {
rls.update(i);
}
assertEquals(rls.getValueAtPosition(tgtIdx), tgtIdx);
try {
rls.insertValueAtPosition(-1, -1);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
try {
rls.insertValueAtPosition(-1, k + 1);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
try {
rls.getValueAtPosition(-1);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
try {
rls.getValueAtPosition(k + 1);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
}
@Test
public void checkForceIncrement() {
final int k = 100;
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k);
for (int i = 0; i < (2 * k); ++i) {
rls.update(i);
}
assertEquals(rls.getN(), 2 * k);
rls.forceIncrementItemsSeen(k);
assertEquals(rls.getN(), 3 * k);
try {
rls.forceIncrementItemsSeen((1L << 48) - 1);
fail();
} catch (final SketchesStateException e) {
// expected
}
}
@Test
public void cluster_checkEstimateSubsetSum() {
int cluster = 3;
int failCount = 0;
for (int i = 0; i < cluster; i++) {
try {
checkEstimateSubsetSum(); //Test to run cluster on
//System.out.println("Fail Count: " + failCount); //useful for debugging thresholds
break;
} catch (AssertionError ae) {
if (++failCount >= cluster) {
StringWriter sw = new StringWriter();
ae.printStackTrace(new PrintWriter(sw));
String str = sw.toString();
fail("Failed a cluster of " + cluster + "\n" + str);
}
}
}
}
public void checkEstimateSubsetSum() {
final int k = 10;
final ReservoirLongsSketch sketch = ReservoirLongsSketch.newInstance(k);
// empty sketch -- all zeros
SampleSubsetSummary ss = sketch.estimateSubsetSum(item -> true);
assertEquals(ss.getEstimate(), 0.0);
assertEquals(ss.getTotalSketchWeight(), 0.0);
// add items, keeping in exact mode
double itemCount = 0.0;
for (long i = 1; i <= (k - 1); ++i) {
sketch.update(i);
itemCount += 1.0;
}
ss = sketch.estimateSubsetSum(item -> true);
assertEquals(ss.getEstimate(), itemCount);
assertEquals(ss.getLowerBound(), itemCount);
assertEquals(ss.getUpperBound(), itemCount);
assertEquals(ss.getTotalSketchWeight(), itemCount);
// add a few more items, pushing to sampling mode
for (long i = k; i <= (k + 1); ++i) {
sketch.update(i);
itemCount += 1.0;
}
// predicate always true so estimate == upper bound
ss = sketch.estimateSubsetSum(item -> true);
assertEquals(ss.getEstimate(), itemCount);
assertEquals(ss.getUpperBound(), itemCount);
assertTrue(ss.getLowerBound() < itemCount);
assertEquals(ss.getTotalSketchWeight(), itemCount);
// predicate always false so estimate == lower bound == 0.0
ss = sketch.estimateSubsetSum(item -> false);
assertEquals(ss.getEstimate(), 0.0);
assertEquals(ss.getLowerBound(), 0.0);
assertTrue(ss.getUpperBound() > 0.0);
assertEquals(ss.getTotalSketchWeight(), itemCount);
// finally, a non-degenerate predicate
// insert negative items with identical weights, filter for negative weights only
for (long i = 1; i <= (k + 1); ++i) {
sketch.update(-i);
itemCount += 1.0;
}
ss = sketch.estimateSubsetSum(item -> item < 0);
assertTrue(ss.getEstimate() >= ss.getLowerBound());
assertTrue(ss.getEstimate() <= ss.getUpperBound());
// allow pretty generous bounds when testing
assertTrue(ss.getLowerBound() < (itemCount / 1.4));
assertTrue(ss.getUpperBound() > (itemCount / 2.6));
assertEquals(ss.getTotalSketchWeight(), itemCount);
}
private static WritableMemory getBasicSerializedRLS() {
final int k = 10;
final int n = 20;
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k);
assertEquals(rls.getNumSamples(), 0);
for (int i = 0; i < n; ++i) {
rls.update(i);
}
assertEquals(rls.getNumSamples(), Math.min(n, k));
assertEquals(rls.getN(), n);
assertEquals(rls.getK(), k);
final byte[] sketchBytes = rls.toByteArray();
return WritableMemory.writableWrap(sketchBytes);
}
private static void validateSerializeAndDeserialize(final ReservoirLongsSketch rls) {
final byte[] sketchBytes = rls.toByteArray();
assertEquals(sketchBytes.length,
(Family.RESERVOIR.getMaxPreLongs() + rls.getNumSamples()) << 3);
// ensure full reservoir rebuilds correctly
final Memory mem = Memory.wrap(sketchBytes);
final ReservoirLongsSketch loadedRls = ReservoirLongsSketch.heapify(mem);
validateReservoirEquality(rls, loadedRls);
}
static void validateReservoirEquality(final ReservoirLongsSketch rls1,
final ReservoirLongsSketch rls2) {
assertEquals(rls1.getNumSamples(), rls2.getNumSamples());
if (rls1.getNumSamples() == 0) {
return;
}
final long[] samples1 = rls1.getSamples();
final long[] samples2 = rls2.getSamples();
assertNotNull(samples1);
assertNotNull(samples2);
assertEquals(samples1.length, samples2.length);
for (int i = 0; i < samples1.length; ++i) {
assertEquals(samples1[i], samples2[i]);
}
}
/**
* Wrapper around System.out.println() allowing a simple way to disable logging in tests
*
* @param msg The message to print
*/
private static void println(final String msg) {
//System.out.println(msg);
}
}
| 2,403 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/req/ReqSketchOtherTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.req;
import static org.apache.datasketches.quantilescommon.InequalitySearch.GE;
import static org.apache.datasketches.quantilescommon.InequalitySearch.GT;
import static org.apache.datasketches.quantilescommon.InequalitySearch.LE;
import static org.apache.datasketches.quantilescommon.InequalitySearch.LT;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.quantilescommon.FloatsSortedView;
import org.apache.datasketches.quantilescommon.InequalitySearch;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
@SuppressWarnings("unused")
public class ReqSketchOtherTest {
final ReqSketchTest reqSketchTest = new ReqSketchTest();
static InequalitySearch critLT = LT;
static InequalitySearch critLE = LE;
static InequalitySearch critGT = GT;
static InequalitySearch critGE = GE;
/**
*
*/
@Test
public void checkConstructors() {
final ReqSketch sk = ReqSketch.builder().build();
assertEquals(sk.getK(), 12);
}
@Test
public void checkCopyConstructors() {
final boolean ltEq = true;
final ReqSketch sk = reqSketchTest.loadSketch( 6, 1, 50, true, true, 0);
final long n = sk.getN();
final float min = sk.getMinItem();
final float max = sk.getMaxItem();
final ReqSketch sk2 = new ReqSketch(sk);
assertEquals(sk2.getMinItem(), min);
assertEquals(sk2.getMaxItem(), max);
}
@Test
public void checkNonFinitePMF_CDF() {
final ReqSketch sk = ReqSketch.builder().build();
sk.update(1);
try { //splitpoint values must be finite
sk.getCDF(new float[] { Float.NaN });
fail();
}
catch (final SketchesArgumentException e) {}
}
@Test
public void checkQuantilesExceedLimits() {
final boolean ltEq = true;
final ReqSketch sk = reqSketchTest.loadSketch( 6, 1, 200, true, true, 0);
try { sk.getQuantile(2.0f); fail(); } catch (final SketchesArgumentException e) {}
try { sk.getQuantile(-2.0f); fail(); } catch (final SketchesArgumentException e) {}
}
@Test
public void checkEstimationMode() {
final boolean up = true;
final boolean hra = true;
final boolean ltEq = true;
final ReqSketch sk = reqSketchTest.loadSketch( 20, 1, 119, up, hra, 0);
assertEquals(sk.isEstimationMode(), false);
final double lb = sk.getRankLowerBound(1.0, 1);
final double ub = sk.getRankUpperBound(1.0, 1);
assertEquals(lb, 1.0);
assertEquals(ub, 1.0);
int maxNomSize = sk.getMaxNomSize();
assertEquals(maxNomSize, 120);
sk.update(120);
assertEquals(sk.isEstimationMode(), true);
// lb = sk.getRankLowerBound(0, 1);
// ub = sk.getRankUpperBound(1.0, 1);
// assertEquals(lb, 0.0);
// assertEquals(ub, 2.0);
maxNomSize = sk.getMaxNomSize();
assertEquals(maxNomSize, 240);
final float v = sk.getQuantile(1.0);
assertEquals(v, 120.0f);
final FloatsSortedView aux = sk.getSortedView();
assertNotNull(aux);
assertTrue(BaseReqSketch.getRSE(sk.getK(), .5, false, 120) > 0);
assertTrue(sk.getSerializedSizeBytes() > 0);
}
@Test
public void checkNaNUpdate() {
final InequalitySearch criterion = LE;
final ReqSketch sk = ReqSketch.builder().build();
sk.update(Float.NaN);
assertTrue(sk.isEmpty());
}
@Test
public void checkNonFiniteGetRank() {
final ReqSketch sk = ReqSketch.builder().build();
sk.update(1);
try { sk.getRank(Float.POSITIVE_INFINITY); fail(); } catch (final AssertionError e) {}
}
@Test
public void moreMergeTests() {
final ReqSketch sk1 = ReqSketch.builder().build();
final ReqSketch sk2 = ReqSketch.builder().build();
for (int i = 5; i < 10; i++) {sk1.update(i); }
sk1.merge(sk2); //does nothing
for (int i = 1; i <= 15; i++) {sk2.update(i); }
sk1.merge(sk2);
assertEquals(sk1.getN(), 20);
for (int i = 16; i <= 300; i++) { sk2.update(i); }
sk1.merge(sk2);
}
@Test
public void simpleTest() {
ReqSketch sk;
final ReqSketchBuilder bldr = ReqSketch.builder();
bldr.setK(50).setHighRankAccuracy(false);
bldr.setReqDebug(null);
sk = bldr.build();
final float[] vArr = { 5, 5, 5, 6, 6, 6, 7, 8, 8, 8 };
for (int i = 0; i < vArr.length; i++) { sk.update(vArr[i]); }
final double[] rArrLT = {0.0, 0.0, 0.0, 0.3, 0.3, 0.3, 0.6, 0.7, 0.7, 0.7};
for (int i = 0; i < vArr.length; i++) {
assertEquals(sk.getRank(vArr[i], EXCLUSIVE), rArrLT[i]);
//System.out.println("v:" + vArr[i] + " r:" + sk.getRank(vArr[i]));
}
final double[] rArrLE = {0.3, 0.3, 0.3, 0.6, 0.6, 0.6, 0.7, 1.0, 1.0, 1.0};
for (int i = 0; i < vArr.length; i++) {
assertEquals(sk.getRank(vArr[i], INCLUSIVE), rArrLE[i]);
//System.out.println("v:" + vArr[i] + " r:" + sk.getRank(vArr[i]));
}
}
@Test
public void checkGetRankUBLB() {
checkGetRank(true, false);
checkGetRank(false, true);
}
@Test
public void checkEmpty() {
final ReqSketchBuilder bldr = new ReqSketchBuilder();
final ReqSketch sk = bldr.build();
try { sk.getRank(1f); fail(); } catch (IllegalArgumentException e) {}
try { sk.getRanks(new float[] {1f}); fail(); } catch (IllegalArgumentException e) {}
try { sk.getQuantile(0.5); fail(); } catch (IllegalArgumentException e) {}
try { sk.getQuantiles(new double[] {0.5}); fail(); } catch (IllegalArgumentException e) {}
try { sk.getPMF(new float[] {1f}); fail(); } catch (IllegalArgumentException e) {}
try { sk.getCDF(new float[] {1f}); fail(); } catch (IllegalArgumentException e) {}
assertTrue(BaseReqSketch.getRSE(50, 0.5, true, 0) > 0);
assertTrue(sk.getRankUpperBound(0.5, 1) > 0);
}
private void checkGetRank(final boolean hra, final boolean ltEq) {
final int k = 12;
final boolean up = true;
final int min = 1;
final int max = 1000;
final int skDebug = 0;
final ReqSketch sk = reqSketchTest.loadSketch(k, min, max, up, hra, skDebug);
double rLB = sk.getRankLowerBound(0.5, 1);
assertTrue(rLB > 0);
if (hra) { rLB = sk.getRankLowerBound(995.0/1000, 1); }
else { rLB = sk.getRankLowerBound(5.0/1000, 1); }
assertTrue(rLB > 0);
double rUB = sk.getRankUpperBound(0.5, 1);
assertTrue(rUB > 0);
if (hra) { rUB = sk.getRankUpperBound(995.0/1000, 1); }
else { rUB = sk.getRankUpperBound(5.0/1000, 1); }
assertTrue(rUB > 0);
final double[] ranks = sk.getRanks(new float[] {5f, 100f});
}
private static void myAssertEquals(final double v1, final double v2) {
if (Double.isNaN(v1) && Double.isNaN(v2)) { assert true; }
else if (v1 == v2) { assert true; }
else { assert false; }
}
private static void myAssertEquals(final float v1, final float v2) {
if (Float.isNaN(v1) && Float.isNaN(v2)) { assert true; }
else if (v1 == v2) { assert true; }
else { assert false; }
}
}
| 2,404 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/req/ReqSketchSortedViewTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.req;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.quantilescommon.FloatsSortedView;
import org.apache.datasketches.quantilescommon.FloatsSortedViewIterator;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class ReqSketchSortedViewTest {
private final int k = 32;
private final boolean hra = false;
private final int numV = 3;
private final int dup = 2;
private final int n = numV * dup;
@Test
public void emptySketch() {
ReqSketch sketch = ReqSketch.builder().build();
FloatsSortedViewIterator itr = sketch.getSortedView().iterator();
Assert.assertFalse(itr.next());
}
@Test
public void twoValueSketch() {
ReqSketch sketch = ReqSketch.builder().build();
sketch.update(1f);
sketch.update(2f);
FloatsSortedViewIterator itr = sketch.getSortedView().iterator();
assertTrue(itr.next());
assertEquals(itr.getQuantile(), 1f);
assertEquals(itr.getWeight(), 1);
assertEquals(itr.getCumulativeWeight(EXCLUSIVE), 0);
assertEquals(itr.getCumulativeWeight(INCLUSIVE), 1);
assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0);
assertEquals(itr.getNormalizedRank(INCLUSIVE), 0.5);
assertTrue(itr.next());
assertEquals(itr.getQuantile(), 2f);
assertEquals(itr.getWeight(), 1);
assertEquals(itr.getCumulativeWeight(EXCLUSIVE), 1);
assertEquals(itr.getCumulativeWeight(INCLUSIVE), 2);
assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0.5);
assertEquals(itr.getNormalizedRank(INCLUSIVE), 1.0);
}
//@Test //visual only
public void checkIterator() {
println("");
println("CHECK ReqSketchSortedViewIterator");
println(" k: " + k + ", hra: " + hra);
println(" numV: " + numV + ", dup: " + dup + ", Total n = " + n);
ReqSketch sketch = buildDataLoadSketch();
checkIterator(sketch);
}
private ReqSketch buildDataLoadSketch() {
float[] fArr = new float[n];
int h = 0;
for (int i = 0; i < numV; i++) {
float flt = (i + 1) * 10;
for (int j = 1; j <= dup; j++) { fArr[h++] = flt; }
}
ReqSketchBuilder bldr = ReqSketch.builder();
ReqSketch sketch = bldr.build();
for (int i = 0; i < n; i++) { sketch.update(fArr[i]); }
return sketch;
}
private static void checkIterator(final ReqSketch sketch) {
println("\nNot Deduped:");
FloatsSortedView sv = sketch.getSortedView();
FloatsSortedViewIterator itr = sv.iterator();
printIterator(itr);
}
private static void printIterator(final FloatsSortedViewIterator itr) {
println("");
String[] header = {"Value", "Wt", "CumWtNotInc", "NormRankNotInc", "CumWtInc", "NormRankInc"};
String hfmt = "%8s%6s%16s%16s%16s%16s\n";
String fmt = "%8.1f%6d%16d%16.3f%16d%16.3f\n";
printf(hfmt, (Object[]) header);
while (itr.next()) {
float v = itr.getQuantile();
long wt = itr.getWeight();
long cumWtNotInc = itr.getCumulativeWeight(EXCLUSIVE);
double nRankNotInc = itr.getNormalizedRank(EXCLUSIVE);
long cumWtInc = itr.getCumulativeWeight(INCLUSIVE);
double nRankInc = itr.getNormalizedRank(INCLUSIVE);
printf(fmt, v, wt, cumWtNotInc, nRankNotInc, cumWtInc, nRankInc);
}
}
private final static boolean enablePrinting = false;
/**
* @param format the format
* @param args the args
*/
private static final void printf(final String format, final Object ...args) {
if (enablePrinting) { System.out.printf(format, args); }
}
/**
* @param o the Object to println
*/
private static final void println(final Object o) {
if (enablePrinting) { System.out.println(o.toString()); }
}
}
| 2,405 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/req/ReqDebugImplTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.req;
import java.util.List;
/**
* The implementation of the ReqDebug interface. The current levels are
* implemented:
* <ul><li><b>Level 0: </b>The random generator in the compactor will be given a fixed
* seed which will make the sketch deterministic.</li>
* <li><b>Level 1: </b>Print summaries, but not the data retained by the sketch. This is useful
* when the sketch is large.</li>
* <li><b>Level 2: </b>Print summaries and all data retained by the sketch.</li>
* </ul>
*
* @author Lee Rhodes
*/
public class ReqDebugImplTest implements ReqDebug {
private static final String LS = System.getProperty("line.separator");
private static final String TAB = "\t";
private ReqSketch sk;
final int debugLevel;
final String fmt;
/**
* Constructor
* @param debugLevel sets the debug level of detail
* @param fmt string format to use when printing values
*/
public ReqDebugImplTest(final int debugLevel, final String fmt) {
this.debugLevel = debugLevel;
this.fmt = fmt;
}
@Override
public void emitStart(final ReqSketch sk) {
if (debugLevel == 0) { return; }
this.sk = sk; //SpotBugs EI_EXPOSE_REP2 suppressed by FindBugsExcludeFilter
println("START");
}
@Override
public void emitStartCompress() {
if (debugLevel == 0) { return; }
final int retItems = sk.getNumRetained();
final int maxNomSize = sk.getMaxNomSize();
final long totalN = sk.getN();
final StringBuilder sb = new StringBuilder();
sb.append("COMPRESS: ");
sb.append("skRetItems: ").append(retItems).append(" >= ");
sb.append("MaxNomSize: ").append(maxNomSize);
sb.append(" N: ").append(totalN);
println(sb.toString());
emitAllHorizList();
}
@Override
public void emitCompressDone() {
if (debugLevel == 0) { return; }
final int retItems = sk.getNumRetained();
final int maxNomSize = sk.getMaxNomSize();
emitAllHorizList();
println("COMPRESS: DONE: SketchSize: " + retItems + TAB
+ " MaxNomSize: " + maxNomSize + LS + LS);
}
@Override
public void emitAllHorizList() {
if (debugLevel == 0) { return; }
final List<ReqCompactor> compactors = sk.getCompactors();
for (int h = 0; h < sk.getCompactors().size(); h++) {
final ReqCompactor c = compactors.get(h);
println(c.toListPrefix());
if (debugLevel > 1) {
print(c.getBuffer().toHorizList(fmt, 20) + LS);
} else {
print(LS);
}
}
}
@Override
public void emitMustAddCompactor() {
if (debugLevel == 0) { return; }
final int curLevels = sk.getNumLevels();
final List<ReqCompactor> compactors = sk.getCompactors();
final ReqCompactor topC = compactors.get(curLevels - 1);
final int lgWt = topC.getLgWeight();
final int retCompItems = topC.getBuffer().getCount();
final int nomCap = topC.getNomCapacity();
final StringBuilder sb = new StringBuilder();
sb.append(" ");
sb.append("Must Add Compactor: len(c[").append(lgWt).append("]): ");
sb.append(retCompItems).append(" >= c[").append(lgWt).append("].nomCapacity(): ")
.append(nomCap);
println(sb.toString());
}
//compactor signals
@Override
public void emitCompactingStart(final byte lgWeight) {
if (debugLevel == 0) { return; }
final List<ReqCompactor> compactors = sk.getCompactors();
final ReqCompactor comp = compactors.get(lgWeight);
final int nomCap = comp.getNomCapacity();
final int secSize = comp.getSectionSize();
final int numSec = comp.getNumSections();
final long state = comp.getState();
final int bufCap = comp.getBuffer().getCapacity();
final StringBuilder sb = new StringBuilder();
sb.append(LS + " ");
sb.append("COMPACTING[").append(lgWeight).append("] ");
sb.append("NomCapacity: ").append(nomCap);
sb.append(TAB + " SectionSize: ").append(secSize);
sb.append(TAB + " NumSections: ").append(numSec);
sb.append(TAB + " State(bin): ").append(Long.toBinaryString(state));
sb.append(TAB + " BufCapacity: ").append(bufCap);
println(sb.toString());
}
@Override
public void emitNewCompactor(final byte lgWeight) {
if (debugLevel == 0) { return; }
final List<ReqCompactor> compactors = sk.getCompactors();
final ReqCompactor comp = compactors.get(lgWeight);
println(" New Compactor: lgWeight: " + comp.getLgWeight()
+ TAB + "sectionSize: " + comp.getSectionSize()
+ TAB + "numSections: " + comp.getNumSections());
}
@Override
public void emitAdjSecSizeNumSec(final byte lgWeight) {
if (debugLevel == 0) { return; }
final List<ReqCompactor> compactors = sk.getCompactors();
final ReqCompactor comp = compactors.get(lgWeight);
final int secSize = comp.getSectionSize();
final int numSec = comp.getNumSections();
final StringBuilder sb = new StringBuilder();
sb.append(" ");
sb.append("Adjust: SectionSize: ").append(secSize);
sb.append(" NumSections: ").append(numSec);
println(sb.toString());
}
@Override
public void emitCompactionDetail(final int compactionStart, final int compactionEnd,
final int secsToCompact, final int promoteLen, final boolean coin) {
if (debugLevel == 0) { return; }
final StringBuilder sb = new StringBuilder();
sb.append(" ");
sb.append("SecsToCompact: ").append(secsToCompact);
sb.append(TAB + " CompactStart: ").append(compactionStart);
sb.append(TAB + " CompactEnd: ").append(compactionEnd).append(LS);
final int delete = compactionEnd - compactionStart;
final String oddOrEven = coin ? "Odds" : "Evens";
sb.append(" ");
sb.append("Promote: ").append(promoteLen);
sb.append(TAB + " Delete: ").append(delete);
sb.append(TAB + " Choose: ").append(oddOrEven);
println(sb.toString());
}
@Override
public void emitCompactionDone(final byte lgWeight) {
if (debugLevel == 0) { return; }
final List<ReqCompactor> compactors = sk.getCompactors();
final ReqCompactor comp = compactors.get(lgWeight);
final long state = comp.getState();
println(" COMPACTING DONE: NumCompactions: " + state + LS);
}
static final void printf(final String format, final Object ...args) {
System.out.printf(format, args);
}
static final void print(final Object o) { System.out.print(o.toString()); }
static final void println(final Object o) { System.out.println(o.toString()); }
}
| 2,406 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/req/ReqSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.req;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE;
import static org.apache.datasketches.quantilescommon.QuantilesUtil.evenlySpacedDoubles;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.FloatsSortedView;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator;
import org.apache.datasketches.quantilescommon.QuantilesUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
@SuppressWarnings("unused")
public class ReqSketchTest {
private static final String LS = System.getProperty("line.separator");
//To control debug printing:
private final static int skDebug = 0; // sketch debug printing: 0 = none, 1 = summary, 2 = extensive detail
private final static int iDebug = 0; // debug printing for individual tests below, same scale as above
@Test
public void bigTest() { //ALL IN EXACT MODE
// k, min, max, up, hra, crit, skDebug
bigTestImpl(20, 1, 100, true, true, INCLUSIVE, skDebug);
bigTestImpl(20, 1, 100, false, false, INCLUSIVE, skDebug);
bigTestImpl(20, 1, 100, false, true, EXCLUSIVE, skDebug);
bigTestImpl(20, 1, 100, true, false, INCLUSIVE, skDebug);
}
public void bigTestImpl(final int k, final int min, final int max, final boolean up, final boolean hra,
final QuantileSearchCriteria crit, final int skDebug) {
if (iDebug > 0) {
println(LS + "*************************");
println("k=" + k + " min=" + min + " max=" + max
+ " up=" + up + " hra=" + hra + " criterion=" + crit + LS);
}
final ReqSketch sk = loadSketch(k, min, max, up, hra, skDebug);
final FloatsSortedView sv = sk.getSortedView();
checkToString(sk, iDebug);
checkSortedView(sk, iDebug);
checkGetRank(sk, min, max, iDebug);
checkGetRanks(sk, max, iDebug);
checkGetQuantiles(sk, iDebug);
checkGetCDF(sk, iDebug);
checkGetPMF(sk, iDebug);
checkIterator(sk, iDebug);
checkMerge(sk, iDebug);
printBoundary(skDebug);
sk.reset();
}
//Common loadSketch
public ReqSketch loadSketch(final int k, final int min, final int max, final boolean up,
final boolean hra, final int skDebug) {
final ReqSketchBuilder bldr = ReqSketch.builder();
bldr.setReqDebug(new ReqDebugImplTest(skDebug, "%5.0f"));
bldr.setK(k);
bldr.setHighRankAccuracy(hra);
final ReqSketch sk = bldr.build();
if (up) {
for (int i = min; i <= max; i++) {
sk.update(i);
}
} else { //down
for (int i = max + 1; i-- > min; ) {
sk.update(i);
}
}
return sk;
}
private static void printBoundary(final int iDebug) {
if (iDebug > 0) {
println("===========================================================");
}
}
private static void checkToString(final ReqSketch sk, final int iDebug) {
final boolean summary = iDebug == 1;
final boolean allData = iDebug == 2;
final String brief = sk.toString();
final String all = sk.viewCompactorDetail("%4.0f", true);
if (summary) {
println(brief);
println(sk.viewCompactorDetail("%4.0f", false));
}
if (allData) {
println(brief);
println(all);
}
}
private static void checkGetRank(final ReqSketch sk, final int min, final int max, final int iDebug) {
if (iDebug > 0) { println("GetRank Test: INCLUSIVE"); }
final float[] spArr = QuantilesUtil.evenlySpacedFloats(0, max, 11);
final double[] trueRanks = evenlySpacedDoubles(0, 1.0, 11);
final String dfmt = "%10.2f%10.6f" + LS;
final String sfmt = "%10s%10s" + LS;
if (iDebug > 0) { printf(sfmt, "Value", "Rank"); }
float va = 0;
double ranka = 0;
for (int i = 0; i < spArr.length; i++) {
final float v = spArr[i];
final double trueRank = trueRanks[i];
final double rank = sk.getRank(v);
if (iDebug > 0) { printf(dfmt, v, rank); }
assertEquals(rank, trueRank, .01);
}
if (iDebug > 0) { println(""); }
}
private static void checkGetRanks(final ReqSketch sk, final int max, final int iDebug) {
if (iDebug > 0) { println("GetRanks Test:"); }
final float[] sp = QuantilesUtil.evenlySpacedFloats(0, max, 11);
final String dfmt = "%10.2f%10.6f" + LS;
final String sfmt = "%10s%10s" + LS;
if (iDebug > 0) { printf(sfmt, "Value", "Rank"); }
final double[] nRanks = sk.getRanks(sp);
for (int i = 0; i < nRanks.length; i++) {
if (iDebug > 0) { printf(dfmt, sp[i], nRanks[i]); }
}
if (iDebug > 0) { println(""); }
}
private static void checkSortedView(final ReqSketch sk, final int iDebug) {
final ReqSketchSortedView sv = new ReqSketchSortedView(sk);
final ReqSketchSortedViewIterator itr = sv.iterator();
final int retainedCount = sk.getNumRetained();
final long totalN = sk.getN();
int count = 0;
long cumWt = 0;
while (itr.next()) {
cumWt = itr.getCumulativeWeight(INCLUSIVE);
count++;
}
assertEquals(cumWt, totalN);
assertEquals(count, retainedCount);
}
private static void checkGetQuantiles(final ReqSketch sk, final int iDebug) {
if (iDebug > 0) { println("GetQuantiles() Test"); }
final double[] rArr = {0, .1F, .2F, .3F, .4F, .5F, .6F, .7F, .8F, .9F, 1.0F};
final float[] qOut = sk.getQuantiles(rArr);
if (iDebug > 0) {
for (int i = 0; i < qOut.length; i++) {
final String r = String.format("%6.3f", rArr[i]);
println("nRank: " + r + ", q: " + qOut[i]);
}
}
if (iDebug > 0) { println(""); }
}
private static void checkGetCDF(final ReqSketch sk, final int iDebug) {
if (iDebug > 0) { println("GetCDF() Test"); }
final float[] spArr = { 20, 40, 60, 80 };
final double[] cdf = sk.getCDF(spArr);
if (iDebug > 0) {
for (int i = 0; i < cdf.length; i++) {
final float sp = i == spArr.length ? sk.getMaxItem() : spArr[i];
println("SP: " +sp + ", Den: " + cdf[i]);
}
}
if (iDebug > 0) { println(""); }
}
private static void checkGetPMF(final ReqSketch sk, final int iDebug) {
if (iDebug > 0) { println("GetPMF() Test"); }
final float[] spArr = { 20, 40, 60, 80 };
final double[] pmf = sk.getPMF(spArr);
if (iDebug > 0) {
for (int i = 0; i < pmf.length; i++) {
final float sp = i == spArr.length ? sk.getMaxItem() : spArr[i];
println("SP: " +sp + ", Mass: " + pmf[i]);
}
}
if (iDebug > 0) { println(""); }
}
private static void checkIterator(final ReqSketch sk, final int iDebug) {
if (iDebug > 0) { println("Sketch iterator() Test"); }
final QuantilesFloatsSketchIterator itr = sk.iterator();
while (itr.next()) {
final float v = itr.getQuantile();
final long wt = itr.getWeight();
if (iDebug > 0) { println(" v=" + v + " wt=" +wt); }
}
if (iDebug > 0) { println(""); }
}
private static void checkMerge(final ReqSketch sk, final int iDebug) {
final boolean allData = iDebug > 1;
final boolean summary = iDebug > 0;
if (summary) {
println("Merge Test");
println("Before Merge:");
outputCompactorDetail(sk, "%5.0f", allData, "Host Sketch:");
}
final ReqSketch sk2 = new ReqSketch(sk); //copy ctr
if (summary) {
outputCompactorDetail(sk2, "%5.0f", allData, "Incoming Sketch:");
println("Merge Process:");
}
sk.merge(sk2);
assertEquals(sk.getN(), 200);
}
//specific tests
@Test
public void getQuantiles() {
final ReqSketch sketch = ReqSketch.builder().setK(12).build();
sketch.update(1);
sketch.update(2);
sketch.update(3);
sketch.update(4);
float[] quantiles1 = sketch.getQuantiles(new double[] {0.0, 0.5, 1.0}, EXCLUSIVE);
float[] quantiles2 = sketch.getPartitionBoundaries(2, EXCLUSIVE).boundaries;
assertEquals(quantiles1, quantiles2);
quantiles1 = sketch.getQuantiles(new double[] {0.0, 0.5, 1.0}, INCLUSIVE);
quantiles2 = sketch.getPartitionBoundaries(2, INCLUSIVE).boundaries;
assertEquals(quantiles1, quantiles2);
}
@Test
public void merge() {
final ReqSketch s1 = ReqSketch.builder().setK(12).build();
for (int i = 0; i < 40; i++) {
s1.update(i);
}
final ReqSketch s2 = ReqSketch.builder().setK(12).build();
for (int i = 0; i < 40; i++) {
s2.update(i);
}
final ReqSketch s3 = ReqSketch.builder().setK(12).build();
for (int i = 0; i < 40; i++) {
s3.update(i);
}
final ReqSketch s = ReqSketch.builder().setK(12).build();
s.merge(s1);
s.merge(s2);
s.merge(s3);
}
@Test
public void checkValidateSplits() {
final float[] arr = {1,2,3,4,5};
ReqSketch.validateSplits(arr);
try {
final float[] arr1 = {1,2,4,3,5};
ReqSketch.validateSplits(arr1);
fail();
}
catch (final SketchesArgumentException e) { }
}
@Test
public void checkSerDe() {
final int k = 12;
final int exact = 2 * 3 * k - 1;
checkSerDeImpl(12, false, 0);
checkSerDeImpl(12, true, 0);
checkSerDeImpl(12, false, 4);
checkSerDeImpl(12, true, 4);
checkSerDeImpl(12, false, exact);
checkSerDeImpl(12, true, exact);
checkSerDeImpl(12, false, 2 * exact); //more than one compactor
checkSerDeImpl(12, true, 2 * exact);
}
private static void checkSerDeImpl(final int k, final boolean hra, final int count) {
final ReqSketch sk1 = ReqSketch.builder().setK(k).setHighRankAccuracy(hra).build();
for (int i = 1; i <= count; i++) {
sk1.update(i);
}
final byte[] sk1Arr = sk1.toByteArray();
final Memory mem = Memory.wrap(sk1Arr);
final ReqSketch sk2 = ReqSketch.heapify(mem);
assertEquals(sk2.getNumRetained(), sk1.getNumRetained());
assertEquals(sk1.isEmpty(), sk2.isEmpty());
if (sk2.isEmpty()) {
try { sk2.getMinItem(); fail(); } catch (IllegalArgumentException e) {}
try { sk2.getMaxItem(); fail(); } catch (IllegalArgumentException e) {}
} else {
assertEquals(sk2.getMinItem(), sk1.getMinItem());
assertEquals(sk2.getMaxItem(), sk1.getMaxItem());
}
assertEquals(sk2.getN(), sk1.getN());
assertEquals(sk2.getHighRankAccuracyMode(),sk1.getHighRankAccuracyMode());
assertEquals(sk2.getK(), sk1.getK());
assertEquals(sk2.getMaxNomSize(), sk1.getMaxNomSize());
assertEquals(sk2.getNumLevels(), sk1.getNumLevels());
assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
}
@Test
public void checkK() {
try {
final ReqSketch sk1 = ReqSketch.builder().setK(1).build();
fail();
} catch (final SketchesArgumentException e) {}
}
@Test
public void tenValues() {
final ReqSketch sketch = ReqSketch.builder().build();
for (int i = 1; i <= 10; i++) { sketch.update(i); }
assertFalse(sketch.isEmpty());
assertEquals(sketch.getN(), 10);
assertEquals(sketch.getNumRetained(), 10);
for (int i = 1; i <= 10; i++) {
assertEquals(sketch.getRank(i), (i) / 10.0);
assertEquals(sketch.getRank(i, EXCLUSIVE), (i - 1) / 10.0);
assertEquals(sketch.getRank(i, INCLUSIVE), (i) / 10.0);
}
// inclusive = false
assertEquals(sketch.getQuantile(0, EXCLUSIVE), 1);
assertEquals(sketch.getQuantile(0.1, EXCLUSIVE), 2);
assertEquals(sketch.getQuantile(0.2, EXCLUSIVE), 3);
assertEquals(sketch.getQuantile(0.3, EXCLUSIVE), 4);
assertEquals(sketch.getQuantile(0.4, EXCLUSIVE), 5);
assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 6);
assertEquals(sketch.getQuantile(0.6, EXCLUSIVE), 7);
assertEquals(sketch.getQuantile(0.7, EXCLUSIVE), 8);
assertEquals(sketch.getQuantile(0.8, EXCLUSIVE), 9);
assertEquals(sketch.getQuantile(0.9, EXCLUSIVE), 10);
assertEquals(sketch.getQuantile(1, EXCLUSIVE), 10.0);
// inclusive = true
assertEquals(sketch.getQuantile(0, INCLUSIVE), 1);
assertEquals(sketch.getQuantile(0.1, INCLUSIVE), 1);
assertEquals(sketch.getQuantile(0.2, INCLUSIVE), 2);
assertEquals(sketch.getQuantile(0.3, INCLUSIVE), 3);
assertEquals(sketch.getQuantile(0.4, INCLUSIVE), 4);
assertEquals(sketch.getQuantile(0.5, INCLUSIVE), 5);
assertEquals(sketch.getQuantile(0.6, INCLUSIVE), 6);
assertEquals(sketch.getQuantile(0.7, INCLUSIVE), 7);
assertEquals(sketch.getQuantile(0.8, INCLUSIVE), 8);
assertEquals(sketch.getQuantile(0.9, INCLUSIVE), 9);
assertEquals(sketch.getQuantile(1, INCLUSIVE), 10);
// getQuantile() and getQuantiles() equivalence
{
// inclusive = false (default)
final float[] quantiles =
sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1});
for (int i = 0; i <= 10; i++) {
assertEquals(sketch.getQuantile(i / 10.0), quantiles[i]);
}
}
{
// inclusive = true
final float[] quantiles =
sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1}, INCLUSIVE);
for (int i = 0; i <= 10; i++) {
assertEquals(sketch.getQuantile(i / 10.0, INCLUSIVE), quantiles[i]);
}
}
}
private static void outputCompactorDetail(final ReqSketch sk, final String fmt, final boolean allData,
final String text) {
println(text);
println(sk.viewCompactorDetail(fmt, allData));
}
private static final void printf(final String format, final Object ...args) {
System.out.printf(format, args);
}
private static final void print(final Object o) {
System.out.print(o.toString());
}
private static final void println(final Object o) {
System.out.println(o.toString());
}
}
| 2,407 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/req/ReqSketchCrossLanguageTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.req;
import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES;
import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES;
import static org.apache.datasketches.common.TestUtil.cppPath;
import static org.apache.datasketches.common.TestUtil.javaPath;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator;
import org.testng.annotations.Test;
/**
* Serialize binary sketches to be tested by C++ code.
* Test deserialization of binary sketches serialized by C++ code.
*/
public class ReqSketchCrossLanguageTest {
@Test(groups = {GENERATE_JAVA_FILES})
public void generateBinariesForCompatibilityTesting() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000};
for (int n: nArr) {
final ReqSketch sk = ReqSketch.builder().build();
for (int i = 1; i <= n; i++) sk.update(i);
Files.newOutputStream(javaPath.resolve("req_float_n" + n + "_java.sk")).write(sk.toByteArray());
}
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCpp() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("req_float_n" + n + "_cpp.sk"));
final ReqSketch sk = ReqSketch.heapify(Memory.wrap(bytes));
assertTrue(n == 0 ? sk.isEmpty() : !sk.isEmpty());
assertTrue(n > 10 ? sk.isEstimationMode() : !sk.isEstimationMode());
assertEquals(sk.getN(), n);
if (n > 0) {
assertEquals(sk.getMinItem(), 1);
assertEquals(sk.getMaxItem(), n);
QuantilesFloatsSketchIterator it = sk.iterator();
long weight = 0;
while(it.next()) {
assertTrue(it.getQuantile() >= sk.getMinItem());
assertTrue(it.getQuantile() <= sk.getMaxItem());
weight += it.getWeight();
}
assertEquals(weight, n);
}
}
}
}
| 2,408 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/req/ReqFloatBufferTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.req;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class ReqFloatBufferTest {
@Test
public void checkTrimCount() {
checkTrimCountImpl(true);
checkTrimCountImpl(false);
}
private static void checkTrimCountImpl(final boolean spaceAtBottom) {
final FloatBuffer buf = new FloatBuffer(16, 4, spaceAtBottom);
for (int i = 0; i < 8; i++) { buf.append(i+1); }
assertEquals(buf.getCount(), 8);
buf.trimCount(4);
assertEquals(buf.getCount(), 4);
}
@Test
public void checkGetEvensOrOdds() {
checkGetEvensOrOddsImpl(false, false);
checkGetEvensOrOddsImpl(false, true);
checkGetEvensOrOddsImpl(true, false);
checkGetEvensOrOddsImpl(true, true);
}
private static void checkGetEvensOrOddsImpl(final boolean odds, final boolean spaceAtBottom) {
final int cap = 16;
final FloatBuffer buf = new FloatBuffer(cap, 0, spaceAtBottom);
for (int i = 0; i < cap/2; i++) {
buf.append(i);
}
final FloatBuffer out = buf.getEvensOrOdds(0, cap/2, odds);
//println("odds: " + odds + ", spaceAtBottom: " + spaceAtBottom);
for (int i = 0; i < out.getCount(); i++) {
final int v = (int)out.getItem(i);
if (odds) { assertTrue((v & 1) == 1); }
else { assertTrue((v & 1) == 0); }
//print(v + " ");
}
//println("");
}
@Test
public void checkAppendAndSpaceTop() {
checkAppendAndSpaceImpl(true);
checkAppendAndSpaceImpl(false);
}
private static void checkAppendAndSpaceImpl(final boolean spaceAtBottom) {
final FloatBuffer buf = new FloatBuffer(2, 2, spaceAtBottom);
assertEquals(buf.getCount(), 0);
assertEquals(buf.getCapacity(), 2);
assertEquals(buf.getSpace(), 2);
buf.append(1);
assertEquals(buf.getCount(), 1);
assertEquals(buf.getCapacity(), 2);
assertEquals(buf.getSpace(), 1);
buf.append(2);
assertEquals(buf.getCount(), 2);
assertEquals(buf.getCapacity(), 2);
assertEquals(buf.getSpace(), 0);
buf.append(3);
assertEquals(buf.getCount(), 3);
assertEquals(buf.getCapacity(), 5);
assertEquals(buf.getSpace(), 2);
}
@Test
public void checkEnsureCapacity() {
checkEnsureCapacityImpl(true);
checkEnsureCapacityImpl(false);
}
private static void checkEnsureCapacityImpl(final boolean spaceAtBottom) {
final FloatBuffer buf = new FloatBuffer(4, 2, spaceAtBottom);
buf.append(2);
buf.append(1);
buf.append(3);
buf.ensureCapacity(8);
buf.sort();
assertEquals(buf.getItem(0), 1.0f);
assertEquals(buf.getItem(1), 2.0f);
assertEquals(buf.getItem(2), 3.0f);
}
@Test
public void checkCountLessThan() {
checkCountLessThanImpl(true);
checkCountLessThanImpl(false);
}
private static void checkCountLessThanImpl(final boolean spaceAtBottom) {
final float[] sortedArr = {1,2,3,4,5,6,7};
final FloatBuffer buf = FloatBuffer.wrap(sortedArr, true, spaceAtBottom);
final FloatBuffer buf2 = new FloatBuffer(7,0, spaceAtBottom);
buf2.mergeSortIn(buf);
assertEquals(buf2.getCountWithCriterion(4, EXCLUSIVE), 3);
buf2.mergeSortIn(buf);
assertEquals(buf2.getCountWithCriterion(4, EXCLUSIVE), 6);
assertEquals(buf2.getCount(), 14);
buf2.trimCount(12);
assertEquals(buf2.getCount(), 12);
}
@Test
public void checkCountWcriteria() {
final int delta = 0;
final int cap = 16;
final boolean spaceAtBottom = true;
for (int len = 5; len < 10; len++) {
iterateValues(createSortedFloatBuffer(cap, delta, spaceAtBottom, len), len);
iterateValues(createSortedFloatBuffer(cap, delta, !spaceAtBottom, len), len);
}
}
private static void iterateValues(final FloatBuffer buf, final int len) {
for (float v = 0.5f; v <= len + 0.5f; v += 0.5f) {
checkCountWithCriteria(buf, v);
}
}
//@Test
public void checkCount() {
final FloatBuffer buf = createSortedFloatBuffer(120, 0, true, 100);
println("LT: " + buf.getCountWithCriterion(100, EXCLUSIVE));
println("LE: " + buf.getCountWithCriterion(100, INCLUSIVE));
}
private static void checkCountWithCriteria(final FloatBuffer buf, final float v) {
int count;
final int len = buf.getCount();
final int iv = (int) v;
count = buf.getCountWithCriterion(v, EXCLUSIVE);
assertEquals(count, v > len ? len : v <= 1 ? 0 : iv == v? iv - 1 : iv);
count = buf.getCountWithCriterion(v, INCLUSIVE);
assertEquals(count, v >= len ? len : v < 1 ? 0 : iv);
}
/**
* Creates a FloatBuffer with data
* @param cap size of the buffer
* @param delta incremental growth size
* @param sab space-at-bottom T/F
* @param len number of values to load, starting at 1.0f.
* @return FloatBuffer
*/
private static FloatBuffer createSortedFloatBuffer(final int cap, final int delta,
final boolean sab, final int len) {
final FloatBuffer buf = new FloatBuffer(cap, delta, sab);
for (int i = 0; i < len; i++) { buf.append(i + 1); }
return buf;
}
@Test
public void checkMergeSortIn() {
checkMergeSortInImpl(true);
checkMergeSortInImpl(false);
}
private static void checkMergeSortInImpl(final boolean spaceAtBottom) {
final float[] arr1 = {1,2,5,6}; //both must be sorted
final float[] arr2 = {3,4,7,8};
final FloatBuffer buf1 = new FloatBuffer(12, 0, spaceAtBottom);
final FloatBuffer buf2 = new FloatBuffer(12, 0, spaceAtBottom);
for (int i = 0; i < arr1.length; i++) { buf1.append(arr1[i]); }
for (int i = 0; i < arr2.length; i++) { buf2.append(arr2[i]); }
assertEquals(buf1.getSpace(), 8);
assertEquals(buf2.getSpace(), 8);
assertEquals(buf1.getCount(), 4);
assertEquals(buf2.getCount(), 4);
buf1.sort();
buf2.sort();
buf1.mergeSortIn(buf2);
assertEquals(buf1.getSpace(), 4);
final int len = buf1.getCount();
assertEquals(len, 8);
for (int i = 0; i < len; i++) {
final int item = (int)buf1.getItem(i);
assertEquals(item, i+1);
//print(item + " ");
}
//println("");
}
@Test
private static void checkMergeSortInNotSorted() {
final float[] arr1 = {6,5,2,1};
final float[] arr2 = {8,7,4,3};
final FloatBuffer buf1 = new FloatBuffer(4, 0, false);
final FloatBuffer buf2 = new FloatBuffer(4, 0, false);
for (int i = 0; i < 4; i++) {
buf1.append(arr1[i]);
buf2.append(arr2[i]);
}
try { buf1.mergeSortIn(buf2); fail(); }
catch (final SketchesArgumentException e) { }
}
@Test
public void checkGetCountLtOrEqOddRange() {
final FloatBuffer buf = new FloatBuffer(8, 0, false);
assertTrue(buf.isEmpty());
buf.append(3); buf.append(2); buf.append(1);
buf.trimCount(4);
assertEquals(buf.getCount(), 3);
final int cnt = buf.getCountWithCriterion(3.0f, INCLUSIVE);
assertEquals(cnt, 3);
assertEquals(buf.getItemFromIndex(2), 3.0f);
try { buf.getEvensOrOdds(0, 3, false); fail(); } catch (final SketchesArgumentException e) {}
}
@Test
public void checkTrimCapacityToCount() {
final FloatBuffer buf = new FloatBuffer(100, 100, true);
for (int i = 0; i <= 100; i++) { buf.append(i); }
assertEquals(buf.getCapacity(), 201);
assertEquals(buf.getCount(), 101);
buf.trimCapacity();
assertEquals(buf.getItemFromIndex(0), 100f);
assertEquals(buf.getCapacity(), 101);
assertEquals(buf.getCount(), 101);
}
@Test
public void checkSerDe() {
checkSerDeImpl(true);
checkSerDeImpl(false);
}
private static void checkSerDeImpl(final boolean hra) {
final FloatBuffer buf = new FloatBuffer(100, 100, hra);
for (int i = 0; i <= 100; i++) { buf.append(i); }
final int capacity = buf.getCapacity();
final int count = buf.getCount();
final int delta = buf.getDelta();
final boolean sorted = buf.isSorted();
final boolean sab = buf.isSpaceAtBottom();
assertEquals(buf.getItemFromIndex(100), 100.0f);
assertEquals(buf.getItemFromIndex(hra ? 199 : 1), 1.0f);
assertEquals(buf.isSpaceAtBottom(), hra);
//uses the serialization method
final WritableMemory wmem = WritableMemory.writableWrap(buf.floatsToBytes());
final float[] farr2 = new float[101];
wmem.getFloatArray(0, farr2, 0, 101);
//uses the deserialization method
final FloatBuffer buf2 = FloatBuffer.reconstruct(farr2, count, capacity, delta, sorted, sab);
assertEquals(buf2.getCapacity(), capacity);
assertEquals(buf2.getCount(), count);
assertEquals(buf2.getDelta(), delta);
assertEquals(buf2.isSorted(), sorted);
assertEquals(buf2.getItemFromIndex(100), 100.0f);
assertEquals(buf2.getItemFromIndex(hra ? 199 : 1), 1.0f);
assertEquals(buf2.isSpaceAtBottom(), sab);
}
static void print(final Object o) { System.out.print(o.toString()); }
static void println(final Object o) { System.out.println(o.toString()); }
}
| 2,409 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/req/ReqSketchBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.req;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class ReqSketchBuilderTest {
@Test
public void checkBldr() {
final ReqSketchBuilder bldr = new ReqSketchBuilder();
final ReqDebugImplTest rdi = new ReqDebugImplTest(2, "%4.0f");
bldr.setK(50).setHighRankAccuracy(true).setReqDebug(rdi);
assertEquals(bldr.getK(), 50);
assertEquals(bldr.getHighRankAccuracy(), true);
assertTrue(bldr.getReqDebug() != null);
println(bldr.toString());
bldr.setReqDebug(null);
println(bldr.toString());
}
/**
* @param o object to be printed
*/
static void println(final Object o) {
//System.out.println(o.toString());
}
}
| 2,410 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/req/ReqCompactorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.req;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.memory.Buffer;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.req.ReqSerDe.Compactor;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class ReqCompactorTest {
final ReqSketchTest reqSketchTest = new ReqSketchTest();
@Test
public void checkNearestEven() {
assertEquals(ReqCompactor.nearestEven(-0.9f), 0);
}
@Test
public void checkGetters() {
final boolean up = true;
final boolean hra = true;
final ReqSketch sk = reqSketchTest.loadSketch( 20, 1, 120, up, hra, 0);
final ReqCompactor c = sk.getCompactors().get(0);
c.getCoin();
final long state = c.getState();
assertEquals(state, 1L);
assertEquals(c.getNumSections(), 3);
assertEquals(c.getSectionSize(), 20);
}
@Test
public void checkSerDe() {
checkSerDeImpl(12, false);
checkSerDeImpl(12, true);
}
private static void checkSerDeImpl(final int k, final boolean hra) {
final ReqCompactor c1 = new ReqCompactor((byte)0, hra, k, null);
final int nomCap = 2 * 3 * k;
final int cap = 2 * nomCap;
final int delta = nomCap;
final FloatBuffer buf = c1.getBuffer();
for (int i = 1; i <= nomCap; i++) {
buf.append(i); //compactor doesn't have a direct update() method
}
final float minV = 1;
final float maxV = nomCap;
final float sectionSizeFlt = c1.getSectionSizeFlt();
final int sectionSize = c1.getSectionSize();
final int numSections = c1.getNumSections();
final long state = c1.getState();
final int lgWeight = c1.getLgWeight();
final boolean c1hra = c1.isHighRankAccuracy();
final boolean sorted = buf.isSorted();
final byte[] c1ser = c1.toByteArray();
//now deserialize
final Buffer buff = Memory.wrap(c1ser).asBuffer();
final Compactor compactor = ReqSerDe.extractCompactor(buff, sorted, c1hra);
final ReqCompactor c2 = compactor.reqCompactor;
assertEquals(compactor.minItem, minV);
assertEquals(compactor.maxItem, maxV);
assertEquals(compactor.count, nomCap);
assertEquals(c2.getSectionSizeFlt(), sectionSizeFlt);
assertEquals(c2.getSectionSize(), sectionSize);
assertEquals(c2.getNumSections(), numSections);
assertEquals(c2.getState(), state);
assertEquals(c2.getLgWeight(), lgWeight);
assertEquals(c2.isHighRankAccuracy(), c1hra);
final FloatBuffer buf2 = c2.getBuffer();
assertEquals(buf2.getCapacity(), cap);
assertEquals(buf2.getDelta(), delta);
assertTrue(buf.isEqualTo(buf2));
}
}
| 2,411 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/common/FamilyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.common;
import static org.apache.datasketches.common.Family.idToFamily;
import static org.apache.datasketches.common.Family.stringToFamily;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class FamilyTest {
@Test
public void checkFamilyEnum() {
final Family[] families = Family.values();
final int numFam = families.length;
for (int i = 0; i < numFam; i++) {
final Family f = families[i];
final int fid = f.getID();
f.checkFamilyID(fid);
final Family f2 = idToFamily(fid);
assertTrue(f.equals(f2));
assertEquals(f.getFamilyName(), f2.getFamilyName());
final int id2 = f2.getID();
assertEquals(fid, id2);
}
checkStringToFamily("Alpha");
checkStringToFamily("QuickSelect");
checkStringToFamily("Union");
checkStringToFamily("Intersection");
checkStringToFamily("AnotB");
checkStringToFamily("HLL");
checkStringToFamily("Quantiles");
}
private static void checkStringToFamily(final String inStr) {
final String fName = stringToFamily(inStr).toString();
assertEquals(fName, inStr.toUpperCase());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadFamilyName() {
stringToFamily("Test");
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadFamilyID() {
final Family famAlpha = Family.ALPHA;
final Family famQS = Family.QUICKSELECT;
famAlpha.checkFamilyID(famQS.getID());
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,412 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/common/Shuffle.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.common;
import java.util.Random;
/**
* @author Lee Rhodes
*/
public final class Shuffle {
private static final Random rand = new Random();
/**
* Shuffle the given input float array
* @param array input array
*/
public static void shuffle(final float[] array) {
final int arrLen = array.length;
for (int i = 0; i < arrLen; i++) {
final int r = rand.nextInt(i + 1);
swap(array, i, r);
}
}
private static void swap(final float[] array, final int i1, final int i2) {
final float value = array[i1];
array[i1] = array[i2];
array[i2] = value;
}
/**
* Shuffle the given input double array
* @param array input array
*/
public static void shuffle(final double[] array) {
final int arrLen = array.length;
for (int i = 0; i < arrLen; i++) {
final int r = rand.nextInt(i + 1);
swap(array, i, r);
}
}
private static void swap(final double[] array, final int i1, final int i2) {
final double value = array[i1];
array[i1] = array[i2];
array[i2] = value;
}
/**
* Shuffle the given input long array
* @param array input array
*/
public static void shuffle(final long[] array) {
final int arrLen = array.length;
for (int i = 0; i < arrLen; i++) {
final int r = rand.nextInt(i + 1);
swap(array, i, r);
}
}
private static void swap(final long[] array, final int i1, final int i2) {
final long value = array[i1];
array[i1] = array[i2];
array[i2] = value;
}
/**
* Shuffle the given input int array
* @param array input array
*/
public static void shuffle(final int[] array) {
final int arrLen = array.length;
for (int i = 0; i < arrLen; i++) {
final int r = rand.nextInt(i + 1);
swap(array, i, r);
}
}
private static void swap(final int[] array, final int i1, final int i2) {
final int value = array[i1];
array[i1] = array[i2];
array[i2] = value;
}
}
| 2,413 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/common/UtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.common;
import static java.lang.Math.pow;
import static org.apache.datasketches.common.Util.bytesToInt;
import static org.apache.datasketches.common.Util.bytesToLong;
import static org.apache.datasketches.common.Util.bytesToString;
import static org.apache.datasketches.common.Util.ceilingIntPowerOf2;
import static org.apache.datasketches.common.Util.ceilingLongPowerOf2;
import static org.apache.datasketches.common.Util.ceilingPowerBaseOfDouble;
import static org.apache.datasketches.common.Util.characterPad;
import static org.apache.datasketches.common.Util.checkBounds;
import static org.apache.datasketches.common.Util.checkIfIntPowerOf2;
import static org.apache.datasketches.common.Util.checkIfLongPowerOf2;
import static org.apache.datasketches.common.Util.checkIfMultipleOf8AndGT0;
import static org.apache.datasketches.common.Util.checkProbability;
import static org.apache.datasketches.common.Util.convertToLongArray;
import static org.apache.datasketches.common.Util.exactLog2OfInt;
import static org.apache.datasketches.common.Util.exactLog2OfLong;
import static org.apache.datasketches.common.Util.floorPowerBaseOfDouble;
import static org.apache.datasketches.common.Util.floorPowerOf2;
import static org.apache.datasketches.common.Util.intToBytes;
import static org.apache.datasketches.common.Util.invPow2;
import static org.apache.datasketches.common.Util.isEven;
import static org.apache.datasketches.common.Util.isIntPowerOf2;
import static org.apache.datasketches.common.Util.isLessThanUnsigned;
import static org.apache.datasketches.common.Util.isLongPowerOf2;
import static org.apache.datasketches.common.Util.isMultipleOf8AndGT0;
import static org.apache.datasketches.common.Util.isOdd;
import static org.apache.datasketches.common.Util.longToBytes;
import static org.apache.datasketches.common.Util.milliSecToString;
import static org.apache.datasketches.common.Util.nanoSecToString;
import static org.apache.datasketches.common.Util.numberOfLeadingOnes;
import static org.apache.datasketches.common.Util.numberOfTrailingOnes;
import static org.apache.datasketches.common.Util.powerSeriesNextDouble;
import static org.apache.datasketches.common.Util.pwr2SeriesNext;
import static org.apache.datasketches.common.Util.pwr2SeriesPrev;
import static org.apache.datasketches.common.Util.zeroPad;
import static org.apache.datasketches.common.TestUtil.cppPath;
import static org.apache.datasketches.common.TestUtil.javaPath;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class UtilTest {
private static final String LS = System.getProperty("line.separator");
@Test
public void numTrailingOnes() {
long mask = 1L;
for (int i = 0; i <= 64; i++) {
final long v = ~mask & -1L;
mask <<= 1;
final int numT1s = numberOfTrailingOnes(v);
final int numL1s = numberOfLeadingOnes(v);
assertEquals(Long.numberOfTrailingZeros(~v), numT1s);
assertEquals(Long.numberOfLeadingZeros(~v), numL1s);
//println(zeroPad(Long.toBinaryString(v),64) + ", " + numL1s + ", " + numT1s);
continue;
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBoundsTest() {
checkBounds(999L, 2L, 1000L);
}
@Test
public void checkIsIntPowerOf2() {
Assert.assertEquals(isIntPowerOf2(0), false);
Assert.assertEquals(isIntPowerOf2(1), true);
Assert.assertEquals(isIntPowerOf2(2), true);
Assert.assertEquals(isIntPowerOf2(4), true);
Assert.assertEquals(isIntPowerOf2(8), true);
Assert.assertEquals(isIntPowerOf2(1 << 30), true);
Assert.assertEquals(isIntPowerOf2(3), false);
Assert.assertEquals(isIntPowerOf2(5), false);
Assert.assertEquals(isIntPowerOf2( -1), false);
}
@Test
public void checkIsLongPowerOf2() {
Assert.assertEquals(isLongPowerOf2(0), false);
Assert.assertEquals(isLongPowerOf2(1), true);
Assert.assertEquals(isLongPowerOf2(2), true);
Assert.assertEquals(isLongPowerOf2(4), true);
Assert.assertEquals(isLongPowerOf2(8), true);
Assert.assertEquals(isLongPowerOf2(1L << 62), true);
Assert.assertEquals(isLongPowerOf2(3), false);
Assert.assertEquals(isLongPowerOf2(5), false);
Assert.assertEquals(isLongPowerOf2( -1), false);
}
@Test
public void checkCheckIfIntPowerOf2() {
checkIfIntPowerOf2(8, "Test 8");
try {
checkIfIntPowerOf2(7, "Test 7");
Assert.fail("Expected SketchesArgumentException");
}
catch (final SketchesArgumentException e) {
//pass
}
}
@Test
public void checkCheckIfLongPowerOf2() {
checkIfLongPowerOf2(8L, "Test 8");
try {
checkIfLongPowerOf2(7L, "Test 7");
Assert.fail("Expected SketchesArgumentException");
}
catch (final SketchesArgumentException e) {
//pass
}
}
@Test
public void checkCeilingIntPowerOf2() {
Assert.assertEquals(ceilingIntPowerOf2(Integer.MAX_VALUE), 1 << 30);
Assert.assertEquals(ceilingIntPowerOf2(1 << 30), 1 << 30);
Assert.assertEquals(ceilingIntPowerOf2(64), 64);
Assert.assertEquals(ceilingIntPowerOf2(65), 128);
Assert.assertEquals(ceilingIntPowerOf2(0), 1);
Assert.assertEquals(ceilingIntPowerOf2( -1), 1);
}
@Test
public void checkCeilingLongPowerOf2() {
Assert.assertEquals(ceilingLongPowerOf2(Long.MAX_VALUE), 1L << 62);
Assert.assertEquals(ceilingLongPowerOf2(1L << 62), 1L << 62);
Assert.assertEquals(ceilingLongPowerOf2(64), 64);
Assert.assertEquals(ceilingLongPowerOf2(65), 128);
Assert.assertEquals(ceilingLongPowerOf2(0), 1L);
Assert.assertEquals(ceilingLongPowerOf2( -1L), 1L);
}
@Test
public void checkCeilingPowerOf2double() {
Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, Integer.MAX_VALUE), pow(2.0, 31));
Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, 1 << 30), pow(2.0, 30));
Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, 64.0), 64.0);
Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, 65.0), 128.0);
Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, 0.0), 1.0);
Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, -1.0), 1.0);
}
@Test
public void checkFloorPowerOf2Int() {
Assert.assertEquals(floorPowerOf2( -1), 1);
Assert.assertEquals(floorPowerOf2(0), 1);
Assert.assertEquals(floorPowerOf2(1), 1);
Assert.assertEquals(floorPowerOf2(2), 2);
Assert.assertEquals(floorPowerOf2(3), 2);
Assert.assertEquals(floorPowerOf2(4), 4);
Assert.assertEquals(floorPowerOf2((1 << 30) - 1), 1 << 29);
Assert.assertEquals(floorPowerOf2(1 << 30), 1 << 30);
Assert.assertEquals(floorPowerOf2((1 << 30) + 1), 1 << 30);
}
@Test
public void checkFloorPowerOf2Long() {
Assert.assertEquals(floorPowerOf2( -1L), 1L);
Assert.assertEquals(floorPowerOf2(0L), 1L);
Assert.assertEquals(floorPowerOf2(1L), 1L);
Assert.assertEquals(floorPowerOf2(2L), 2L);
Assert.assertEquals(floorPowerOf2(3L), 2L);
Assert.assertEquals(floorPowerOf2(4L), 4L);
Assert.assertEquals(floorPowerOf2((1L << 63) - 1L), 1L << 62);
Assert.assertEquals(floorPowerOf2(1L << 62), 1L << 62);
Assert.assertEquals(floorPowerOf2((1L << 62) + 1L), 1L << 62);
}
@Test
public void checkFloorPowerOf2double() {
Assert.assertEquals(floorPowerBaseOfDouble(2.0, -1.0), 1.0);
Assert.assertEquals(floorPowerBaseOfDouble(2.0, 0.0), 1.0);
Assert.assertEquals(floorPowerBaseOfDouble(2.0, 1.0), 1.0);
Assert.assertEquals(floorPowerBaseOfDouble(2.0, 2.0), 2.0);
Assert.assertEquals(floorPowerBaseOfDouble(2.0, 3.0), 2.0);
Assert.assertEquals(floorPowerBaseOfDouble(2.0, 4.0), 4.0);
Assert.assertEquals(floorPowerBaseOfDouble(2.0, (1 << 30) - 1.0), 1 << 29);
Assert.assertEquals(floorPowerBaseOfDouble(2.0, 1 << 30), 1 << 30);
Assert.assertEquals(floorPowerBaseOfDouble(2.0, (1 << 30) + 1.0), 1L << 30);
}
@Test
public void checkCheckIfMultipleOf8AndGT0() {
checkIfMultipleOf8AndGT0(8, "test 8");
try { checkIfMultipleOf8AndGT0( 7, "test 7"); fail(); } catch (final SketchesArgumentException e) { }
try { checkIfMultipleOf8AndGT0(-8, "test -8"); fail(); } catch (final SketchesArgumentException e) { }
try { checkIfMultipleOf8AndGT0(-1, "test -1"); fail(); } catch (final SketchesArgumentException e) { }
}
@Test
public void checkIsMultipleOf8AndGT0() {
Assert.assertTrue(isMultipleOf8AndGT0(8));
Assert.assertFalse(isMultipleOf8AndGT0(7));
Assert.assertFalse(isMultipleOf8AndGT0(-8));
Assert.assertFalse(isMultipleOf8AndGT0(-1));
}
@Test
public void checkInvPow2() {
Assert.assertEquals(invPow2(1), 0.5);
Assert.assertEquals(invPow2(0), 1.0);
try { invPow2(-1); failIAE(); } catch (final AssertionError e) {}
try {invPow2(1024); failIAE(); } catch (final AssertionError e) {}
try {invPow2(Integer.MIN_VALUE); failIAE(); } catch (final AssertionError e) {}
}
private static void failIAE() { throw new IllegalArgumentException("Test should have failed!"); }
@Test
public void checkIsLessThanUnsigned() {
final long n1 = 1;
final long n2 = 3;
final long n3 = -3;
final long n4 = -1;
Assert.assertTrue(isLessThanUnsigned(n1, n2));
Assert.assertTrue(isLessThanUnsigned(n2, n3));
Assert.assertTrue(isLessThanUnsigned(n3, n4));
Assert.assertFalse(isLessThanUnsigned(n2, n1));
Assert.assertFalse(isLessThanUnsigned(n3, n2));
Assert.assertFalse(isLessThanUnsigned(n4, n3));
}
@Test
public void checkZeroPad() {
final long v = 123456789;
final String vHex = Long.toHexString(v);
final String out = zeroPad(vHex, 16);
println("Pad 16, prepend 0: " + out);
}
@Test
public void checkCharacterPad() {
final String s = "Pad 30, postpend z:";
final String out = characterPad(s, 30, 'z', true);
println(out);
}
@Test
public void checkProbabilityFn1() {
checkProbability(.5, "Good");
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkProbabilityFn2() {
checkProbability(-.5, "Too Low");
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkProbabilityFn3() {
checkProbability(1.5, "Too High");
}
@Test
public void checkEvenOdd() {
assertTrue(isEven(0));
assertFalse(isOdd(0));
assertTrue(isOdd(-1));
assertFalse(isEven(-1));
}
@Test
public void checkBytesToInt() {
final byte[] arr = new byte[] {4, 3, 2, 1};
final int result = 4 + (3 << 8) + (2 << 16) + (1 << 24);
Assert.assertEquals(bytesToInt(arr), result);
final byte[] arr2 = intToBytes(result, new byte[4]);
Assert.assertEquals(arr, arr2);
}
@Test
public void checkBytesToLong() {
final byte[] arr = new byte[] {8, 7, 6, 5, 4, 3, 2, 1};
final long result = 8L + (7L << 8) + (6L << 16) + (5L << 24)
+ (4L << 32) + (3L << 40) + (2L << 48) + (1L << 56);
Assert.assertEquals(bytesToLong(arr), result);
}
@Test
public void checkBytesToString() {
final long lng = 0XF8F7F6F504030201L;
//println(Long.toHexString(lng));
byte[] bytes = new byte[8];
bytes = longToBytes(lng, bytes);
final String sep = ".";
final String unsignLE = bytesToString(bytes, false, true, sep);
final String signedLE = bytesToString(bytes, true, true, sep);
final String unsignBE = bytesToString(bytes, false, false, sep);
final String signedBE = bytesToString(bytes, true, false, sep);
Assert.assertEquals(unsignLE, "1.2.3.4.245.246.247.248");
Assert.assertEquals(signedLE, "1.2.3.4.-11.-10.-9.-8");
Assert.assertEquals(unsignBE, "248.247.246.245.4.3.2.1");
Assert.assertEquals(signedBE, "-8.-9.-10.-11.4.3.2.1");
}
@Test
public void checkNsecToString() {
final long nS = 1000000000L + 1000000L + 1000L + 1L;
final String result = nanoSecToString(nS);
final String expected = "1.001_001_001";
Assert.assertEquals(result, expected);
}
@Test
public void checkMsecToString() {
final long nS = 60L * 60L * 1000L + 60L * 1000L + 1000L + 1L;
final String result = milliSecToString(nS);
final String expected = "1:01:01.001";
Assert.assertEquals(result, expected);
}
@Test
public void checkPwr2LawNext() {
int next = (int)pwr2SeriesNext(2, 1);
Assert.assertEquals(next, 2);
next = (int)pwr2SeriesNext(2, 2);
Assert.assertEquals(next, 3);
next = (int)pwr2SeriesNext(2, 3);
Assert.assertEquals(next, 4);
next = (int)pwr2SeriesNext(2, 0);
Assert.assertEquals(next, 1);
}
@Test
public void checkPwr2LawNextDouble() {
double next = powerSeriesNextDouble(2, 1.0, true, 2.0);
Assert.assertEquals(next, 2.0, 0.0);
next = powerSeriesNextDouble(2, 2.0, true, 2.0);
Assert.assertEquals(next, 3.0, 0.0);
next = powerSeriesNextDouble(2, 3, true, 2.0);
Assert.assertEquals(next, 4.0, 0.0);
next = powerSeriesNextDouble(2, 1, false, 2.0);
Assert.assertEquals(next, Math.sqrt(2), 0.0);
next = powerSeriesNextDouble(2, 0.5, true, 2.0);
Assert.assertEquals(next, 2.0, 0.0);
next = powerSeriesNextDouble(2, 0.5, false, 2.0);
Assert.assertEquals(next, Math.sqrt(2), 0.0);
next = powerSeriesNextDouble(2, next, false, 2.0);
Assert.assertEquals(next, 2.0, 0.0);
}
@Test
public void checkPwr2SeriesExamples() {
final int maxP = 32;
final int minP = 1;
final int ppo = 4;
for (int p = minP; p <= maxP; p = (int)pwr2SeriesNext(ppo, p)) {
print(p + " ");
}
println("");
for (int p = maxP; p >= minP; p = pwr2SeriesPrev(ppo, p)) {
print(p + " ");
}
println("");
}
@Test
public void checkExactLog2OfLong() {
Assert.assertEquals(exactLog2OfLong(2), 1);
Assert.assertEquals(exactLog2OfLong(1), 0);
Assert.assertEquals(exactLog2OfLong(1L << 62), 62);
try {
exactLog2OfLong(0);
fail();
} catch (final SketchesArgumentException e) { }
}
@Test
public void checkExactLog2OfInt() {
Assert.assertEquals(exactLog2OfInt(2), 1);
Assert.assertEquals(exactLog2OfInt(1), 0);
Assert.assertEquals(exactLog2OfInt(1 << 30), 30);
try {
exactLog2OfInt(0);
fail();
} catch (final SketchesArgumentException e) { }
}
@Test
public void checkExactLog2OfLongWithArg() {
Assert.assertEquals(exactLog2OfLong(2, "2"), 1);
Assert.assertEquals(exactLog2OfLong(1, "1"), 0);
Assert.assertEquals(exactLog2OfLong(1L << 62,"1L<<62"), 62);
try {
exactLog2OfLong(0,"0");
fail();
} catch (final SketchesArgumentException e) { }
}
@Test
public void checkExactLog2OfIntWithArg() {
Assert.assertEquals(exactLog2OfInt(2,"2"), 1);
Assert.assertEquals(exactLog2OfInt(1,"1"), 0);
Assert.assertEquals(exactLog2OfInt(1 << 30,"1<<30"), 30);
try {
exactLog2OfInt(0,"0");
fail();
} catch (final SketchesArgumentException e) { }
}
@Test
static void checkConvertToLongArray() {
byte[] arr = {1,2,3,4,5,6,7,8,9,10,11,12};
long[] out = convertToLongArray(arr, false);
String s = org.apache.datasketches.common.Util.zeroPad(Long.toHexString(out[0]), 16);
assertEquals(s, "0807060504030201");
s = org.apache.datasketches.common.Util.zeroPad(Long.toHexString(out[1]), 16);
assertEquals(s, "000000000c0b0a09");
out = convertToLongArray(arr, true);
s = org.apache.datasketches.common.Util.zeroPad(Long.toHexString(out[0]), 16);
assertEquals(s, "0102030405060708");
s = org.apache.datasketches.common.Util.zeroPad(Long.toHexString(out[1]), 16);
assertEquals(s, "00000000090a0b0c");
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
@Test
public void checkDirCreation() {
assertNotNull(javaPath);
assertNotNull(cppPath);
}
private static boolean enablePrinting = false;
static void println(final Object o) {
if (enablePrinting) {
if (o == null) { print(LS); }
else { print(o.toString() + LS); }
}
}
/**
* @param o value to print
*/
static void print(final Object o) {
if (enablePrinting && o != null) {
System.out.print(o.toString());
}
}
}
| 2,414 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/common/BoundsOnBinomialProportionsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.common;
import static org.apache.datasketches.common.BoundsOnBinomialProportions.approximateLowerBoundOnP;
import static org.apache.datasketches.common.BoundsOnBinomialProportions.approximateUpperBoundOnP;
import static org.apache.datasketches.common.BoundsOnBinomialProportions.erf;
import static org.apache.datasketches.common.BoundsOnBinomialProportions.estimateUnknownP;
import static org.apache.datasketches.common.BoundsOnBinomialProportions.normalCDF;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.testng.annotations.Test;
/**
* @author Kevin Lang
*/
public class BoundsOnBinomialProportionsTest {
@Test
public static void tinyLBTest() {
//these answers were computed using a different programming language and therefore might not
// match exactly.
final double[] answers = {0.0, 0.004592032688529923, 0.04725537386564205,
0.1396230607626959, 0.2735831034867167, 0.4692424353373485};
final double kappa = 2.0;
assertTrue( 0.0 == approximateLowerBoundOnP(0, 0, kappa) );
final long n = 5;
for (long k = 0; k <= n; k++) {
final double lb = approximateLowerBoundOnP(n, k, kappa);
final double est = estimateUnknownP(n, k);
assertTrue(lb <= est);
assertTrue(Math.abs(lb - answers[(int) k]) < 1e-14);
// System.out.printf ("LB\t%d\t%d\t%.1f\t%.16g%n", n, k, kappa, lb);
}
}
@Test
public static void tinyUBTest() {
//these answers were computed using a different programming language and therefore might not
// match exactly.
final double[] answers = {0.5307575646626514, 0.7264168965132833, 0.860376939237304,
0.952744626134358, 0.9954079673114701, 1.0};
final double kappa = 2.0;
assertTrue(1.0 == approximateUpperBoundOnP(0, 0, kappa));
final long n = 5;
for (long k = 0; k <= n; k++) {
final double ub = approximateUpperBoundOnP(n, k, kappa);
final double est = estimateUnknownP(n, k);
assertTrue(ub >= est);
assertTrue(Math.abs(ub - answers[(int) k]) < 1e-14);
// System.out.printf ("UB\t%d\t%d\t%.1f\t%.16g%n", n, k, kappa, ub);
}
}
// This is for Kevin's use only, and will not be one of the unit tests.
public static void lotsOfSpewage(final long maxN) {
for (long n = 0; n <= maxN; n++) {
for (long k = 0; k <= n; k++) {
for (double kappa = 0.5; kappa < 5.0; kappa += 0.5) {
final double lb = approximateLowerBoundOnP(n, k, kappa);
final double ub = approximateUpperBoundOnP(n, k, kappa);
final double est = estimateUnknownP(n, k);
assertTrue(lb <= est);
assertTrue(ub >= est);
final String slb = String.format("LB\t%d\t%d\t%.1f\t%.16g%n", n, k, kappa, lb);
final String sub = String.format("UB\t%d\t%d\t%.1f\t%.16g%n", n, k, kappa, ub);
println(slb);
println(sub);
}
}
}
}
// This is for Kevin's use only, and will not be one of the unit tests.
public static void printSomeNormalCDF() {
final double[] someX = {-10.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 10.0};
for (int i = 0; i < 11; i++) {
final String s = String.format("normalCDF(%.1f) = %.12f%n", someX[i], normalCDF(someX[i]));
println(s);
}
}
// This is for Kevin's use only, and will not be one of the unit tests.
// public static void main (String[] args) {
// tinyLBTest ();
// tinyUBTest ();
// assertTrue (args.length == 1);
// long maxN = Long.parseLong(args[0]);
// lotsOfSpewage (maxN);
// }
@Test
public static void checkNumStdDevZero() {
final double lb = BoundsOnBinomialProportions.approximateLowerBoundOnP( 1000, 100, 0.0);
final double ub = BoundsOnBinomialProportions.approximateUpperBoundOnP( 1000, 100, 0.0);
println("LB: " + lb);
println("UB: " + ub);
}
@Test
public static void checkInputs() {
try {
estimateUnknownP(-1, 50);
fail("Should have thrown SketchesArgumentException.");
}
catch (final SketchesArgumentException e) {
//expected
}
try {
estimateUnknownP(500, -50);
fail("Should have thrown SketchesArgumentException.");
}
catch (final SketchesArgumentException e) {
//expected
}
try {
estimateUnknownP(500, 5000);
fail("Should have thrown SketchesArgumentException.");
}
catch (final SketchesArgumentException e) {
//expected
}
assertEquals(estimateUnknownP(0, 0), 0.5, 0.0);
}
@Test
public static void checkErf() {
assertTrue(erf(-2.0) < 0.99);
assertTrue(erf(2.0) > 0.99);
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,415 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/common/ArrayOfXSerDeTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.common;
import static org.testng.Assert.assertEquals;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
public class ArrayOfXSerDeTest {
@Test
public void checkBooleanItems() {
int bytes;
byte[] byteArr;
int offset = 10;
WritableMemory wmem;
ArrayOfBooleansSerDe serDe = new ArrayOfBooleansSerDe();
Boolean[] items = {true,false,true,true,false,false};
bytes = serDe.sizeOf(items);
byteArr = serDe.serializeToByteArray(items);
assertEquals(byteArr.length, bytes);
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
Boolean[] deSer = serDe.deserializeFromMemory(wmem, offset, items.length);
assertEquals(deSer, items);
assertEquals(serDe.sizeOf(wmem, offset, items.length), bytes);
Boolean item = true;
bytes = serDe.sizeOf(item);
byteArr = serDe.serializeToByteArray(item);
assertEquals(byteArr.length, bytes);
assertEquals(serDe.toString(item), item.toString());
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
Boolean deItem = serDe.deserializeFromMemory(wmem, offset, 1)[0];
assertEquals(deItem, item);
assertEquals(serDe.sizeOf(wmem, offset, 1), bytes);
}
@Test
public void checkDoubleItems() {
int bytes;
byte[] byteArr;
int offset = 10;
WritableMemory wmem;
ArrayOfDoublesSerDe serDe = new ArrayOfDoublesSerDe();
Double[] items = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
bytes = serDe.sizeOf(items);
byteArr = serDe.serializeToByteArray(items);
assertEquals(byteArr.length, bytes);
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
Double[] deSer = serDe.deserializeFromMemory(wmem, offset, items.length);
assertEquals(deSer,items);
assertEquals(serDe.sizeOf(wmem, offset, items.length), bytes);
Double item = 13.0;
bytes = serDe.sizeOf(item);
byteArr = serDe.serializeToByteArray(item);
assertEquals(byteArr.length, bytes);
assertEquals(serDe.sizeOf(item), bytes);
assertEquals(serDe.toString(item), item.toString());
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
Double deItem = serDe.deserializeFromMemory(wmem, offset, 1)[0];
assertEquals(deItem, item);
assertEquals(serDe.sizeOf(wmem, offset, 1), bytes);
}
@Test
public void checkLongItems() {
int bytes;
byte[] byteArr;
int offset = 10;
WritableMemory wmem;
ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
Long[] items = {1L, 2L, 3L, 4L, 5L, 6L};
bytes = serDe.sizeOf(items);
byteArr = serDe.serializeToByteArray(items);
assertEquals(byteArr.length, bytes);
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
Long[] deSer = serDe.deserializeFromMemory(wmem, offset, items.length);
assertEquals(deSer,items);
assertEquals(serDe.sizeOf(wmem, offset, items.length), bytes);
Long item = 13L;
bytes = serDe.sizeOf(item);
byteArr = serDe.serializeToByteArray(item);
assertEquals(byteArr.length, bytes);
assertEquals(serDe.sizeOf(item), bytes);
assertEquals(serDe.toString(item), item.toString());
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
Long deItem = serDe.deserializeFromMemory(wmem, offset, 1)[0];
assertEquals(deItem, item);
assertEquals(serDe.sizeOf(wmem, offset, 1), bytes);
}
@Test
public void checkNumberItems() {
int bytes;
byte[] byteArr;
final int offset = 10;
WritableMemory wmem;
ArrayOfNumbersSerDe serDe = new ArrayOfNumbersSerDe();
Number item = (double)5;
bytes = serDe.sizeOf(item);
byteArr = serDe.serializeToByteArray(item);
assertEquals(byteArr.length, bytes);
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
Number deSer1 = serDe.deserializeFromMemory(wmem, offset, 1)[0];
assertEquals(deSer1,item);
assertEquals(serDe.sizeOf(wmem, offset, 1), bytes);
Number[] items = {(long)1, (int)2, (short)3, (byte)4, (double)5, (float)6};
bytes = serDe.sizeOf(items);
byteArr = serDe.serializeToByteArray(items);
assertEquals(byteArr.length, bytes);
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
Number[] deSer = serDe.deserializeFromMemory(wmem, offset, items.length);
assertEquals(deSer,items);
assertEquals(serDe.sizeOf(wmem, offset, items.length), bytes);
item = 13.0;
bytes = serDe.sizeOf(item);
byteArr = serDe.serializeToByteArray(new Number[] {item});
assertEquals(byteArr.length, bytes);
assertEquals(serDe.sizeOf(item), bytes);
assertEquals(serDe.toString(item), item.toString());
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
Number[] deItem = serDe.deserializeFromMemory(wmem, offset, 1);
assertEquals(deItem[0], item);
assertEquals(serDe.sizeOf(wmem, offset, 1), bytes);
}
@Test
public void checkUTF8Items() {
int bytes;
byte[] byteArr;
final int offset = 10;
WritableMemory wmem;
ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
String item = "abcdefghijklmnopqr";
bytes = serDe.sizeOf(item);
byteArr = serDe.serializeToByteArray(item);
assertEquals(byteArr.length, bytes);
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
String deSer1 = serDe.deserializeFromMemory(wmem, offset, 1)[0];
assertEquals(deSer1,item);
assertEquals(serDe.sizeOf(wmem, offset, 1), bytes);
String[] items = {"abc","def","ghi","jkl","mno","pqr"};
bytes = serDe.sizeOf(items);
byteArr = serDe.serializeToByteArray(items);
assertEquals(byteArr.length, bytes);
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
String[] deSer = serDe.deserializeFromMemory(wmem, offset, items.length);
assertEquals(deSer,items);
assertEquals(serDe.sizeOf(wmem, offset, items.length), bytes);
item = "13.0";
bytes = serDe.sizeOf(item);
byteArr = serDe.serializeToByteArray(new String[] {item});
assertEquals(byteArr.length, bytes);
assertEquals(serDe.sizeOf(item), bytes);
assertEquals(serDe.toString(item), item);
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
String[] deItem = serDe.deserializeFromMemory(wmem, offset, 1);
assertEquals(deItem[0], item);
assertEquals(serDe.sizeOf(wmem, offset, 1), bytes);
}
@Test
public void checkUTF16Items() {
int bytes;
byte[] byteArr;
final int offset = 10;
WritableMemory wmem;
ArrayOfUtf16StringsSerDe serDe = new ArrayOfUtf16StringsSerDe();
String item = "abcdefghijklmnopqr";
bytes = serDe.sizeOf(item);
byteArr = serDe.serializeToByteArray(item);
assertEquals(byteArr.length, bytes);
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
String deSer1 = serDe.deserializeFromMemory(wmem, offset, 1)[0];
assertEquals(deSer1,item);
assertEquals(serDe.sizeOf(wmem, offset, 1), bytes);
String[] items = {"abc","def","ghi","jkl","mno","pqr"};
bytes = serDe.sizeOf(items);
byteArr = serDe.serializeToByteArray(items);
assertEquals(byteArr.length, bytes);
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
String[] deSer = serDe.deserializeFromMemory(wmem, offset, items.length);
assertEquals(deSer,items);
assertEquals(serDe.sizeOf(wmem, offset, items.length), bytes); //
item = "13.0";
bytes = serDe.sizeOf(item);
byteArr = serDe.serializeToByteArray(new String[] {item});
assertEquals(byteArr.length, bytes);
assertEquals(serDe.sizeOf(item), bytes);
assertEquals(serDe.toString(item), item);
wmem = WritableMemory.allocate(offset + byteArr.length);
wmem.putByteArray(offset, byteArr, 0, byteArr.length);
String[] deItem = serDe.deserializeFromMemory(wmem, offset, 1);
assertEquals(deItem[0], item);
assertEquals(serDe.sizeOf(wmem, offset, 1), bytes);
}
}
| 2,416 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/common/ByteArrayUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.common;
import static org.apache.datasketches.common.ByteArrayUtil.getDoubleBE;
import static org.apache.datasketches.common.ByteArrayUtil.getDoubleLE;
import static org.apache.datasketches.common.ByteArrayUtil.getFloatBE;
import static org.apache.datasketches.common.ByteArrayUtil.getFloatLE;
import static org.apache.datasketches.common.ByteArrayUtil.getIntBE;
import static org.apache.datasketches.common.ByteArrayUtil.getIntLE;
import static org.apache.datasketches.common.ByteArrayUtil.getLongBE;
import static org.apache.datasketches.common.ByteArrayUtil.getLongLE;
import static org.apache.datasketches.common.ByteArrayUtil.getShortBE;
import static org.apache.datasketches.common.ByteArrayUtil.getShortLE;
import static org.apache.datasketches.common.ByteArrayUtil.putDoubleBE;
import static org.apache.datasketches.common.ByteArrayUtil.putDoubleLE;
import static org.apache.datasketches.common.ByteArrayUtil.putFloatBE;
import static org.apache.datasketches.common.ByteArrayUtil.putFloatLE;
import static org.apache.datasketches.common.ByteArrayUtil.putIntBE;
import static org.apache.datasketches.common.ByteArrayUtil.putIntLE;
import static org.apache.datasketches.common.ByteArrayUtil.putLongBE;
import static org.apache.datasketches.common.ByteArrayUtil.putLongLE;
import static org.apache.datasketches.common.ByteArrayUtil.putShortBE;
import static org.apache.datasketches.common.ByteArrayUtil.putShortLE;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class ByteArrayUtilTest {
@Test
public void checkCopyBytes() {
final byte[] src = { 1, 2, 3, 4 };
final byte[] tgt = new byte[8];
ByteArrayUtil.copyBytes(src, 1, tgt, 4, 3);
System.out.println("");
}
@Test
public void checkGetPutShortLE() {
final byte[] arr = { 79, -93, 124, 117 };
final short out1 = getShortLE(arr, 0);
final short out2 = getShortLE(arr, 2);
final byte[] arr2 = new byte[4];
putShortLE(arr2, 0, out1);
putShortLE(arr2, 2, out2);
assertEquals(arr2, arr);
}
@Test
public void checkGetPutShortBE() {
final byte[] arr = { 79, -93, 124, 117 };
final short out1 = getShortBE(arr, 0);
final short out2 = getShortBE(arr, 2);
final byte[] arr2 = new byte[4];
putShortBE(arr2, 0, out1);
putShortBE(arr2, 2, out2);
assertEquals(arr2, arr);
}
@Test
public void checkGetPutIntLE() {
final byte[] arr = { 79, -93, 124, 117, -73, -100, -114, 77 };
final int out1 = getIntLE(arr, 0);
final int out2 = getIntLE(arr, 4);
final byte[] arr2 = new byte[8];
putIntLE(arr2, 0, out1);
putIntLE(arr2, 4, out2);
assertEquals(arr2, arr);
}
@Test
public void checkGetPutIntBE() {
final byte[] arr = { 79, -93, 124, 117, -73, -100, -114, 77 };
final int out1 = getIntBE(arr, 0);
final int out2 = getIntBE(arr, 4);
final byte[] arr2 = new byte[8];
putIntBE(arr2, 0, out1);
putIntBE(arr2, 4, out2);
assertEquals(arr2, arr);
}
@Test
public void checkGetPutLongLE() {
final byte[] arr = { 79, -93, 124, 117, -73, -100, -114, 77, 5, -95, -15, 41, -89, -124, -26, -87 };
final long out1 = getLongLE(arr, 0);
final long out2 = getLongLE(arr, 8);
final byte[] arr2 = new byte[16];
putLongLE(arr2, 0, out1);
putLongLE(arr2, 8, out2);
assertEquals(arr2, arr);
}
@Test
public void checkGetPutLongBE() {
final byte[] arr = { 79, -93, 124, 117, -73, -100, -114, 77, 5, -95, -15, 41, -89, -124, -26, -87 };
final long out1 = getLongBE(arr, 0);
final long out2 = getLongBE(arr, 8);
final byte[] arr2 = new byte[16];
putLongBE(arr2, 0, out1);
putLongBE(arr2, 8, out2);
assertEquals(arr2, arr);
}
@Test
public void checkGetPutFloatLE() {
final byte[] arr = { -37, 15, 73, 64, 84, -8, 45, 64 }; //PI, E
final float out1 = getFloatLE(arr, 0);
final float out2 = getFloatLE(arr, 4);
final byte[] arr2 = new byte[8];
putFloatLE(arr2, 0, out1);
putFloatLE(arr2, 4, out2);
assertEquals(arr2, arr);
assertEquals(out1, (float)Math.PI);
assertEquals(out2, (float)Math.E);
}
@Test
public void checkGetPutFloatBE() {
final byte[] arr = { -37, 15, 73, 64, 84, -8, 45, 64 }; //PI, E
final float out1 = getFloatBE(arr, 0);
final float out2 = getFloatBE(arr, 4);
final byte[] arr2 = new byte[8];
putFloatBE(arr2, 0, out1);
putFloatBE(arr2, 4, out2);
assertEquals(arr2, arr);
}
@Test
public void checkGetPutDoubleLE() {
final byte[] arr = { 24, 45, 68, 84, -5, 33, 9, 64, 105, 87, 20, -117, 10, -65, 5, 64 }; //PI, E
final double out1 = getDoubleLE(arr, 0);
final double out2 = getDoubleLE(arr, 8);
final byte[] arr2 = new byte[16];
putDoubleLE(arr2, 0, out1);
putDoubleLE(arr2, 8, out2);
assertEquals(arr2, arr);
assertEquals(out1, Math.PI);
assertEquals(out2, Math.E);
}
@Test
public void checkGetPutDoubleBE() {
final byte[] arr = { 24, 45, 68, 84, -5, 33, 9, 64, 105, 87, 20, -117, 10, -65, 5, 64 }; //PI, E
final double out1 = getDoubleBE(arr, 0);
final double out2 = getDoubleBE(arr, 8);
final byte[] arr2 = new byte[16];
putDoubleBE(arr2, 0, out1);
putDoubleBE(arr2, 8, out2);
assertEquals(arr2, arr);
}
}
| 2,417 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/common/SketchesExceptionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.common;
import org.testng.annotations.Test;
public class SketchesExceptionTest {
@Test(expectedExceptions = SketchesException.class)
public void checkSketchesException() {
throw new SketchesException("This is a test.");
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkSketchesArgumentException() {
throw new SketchesArgumentException("This is a test.");
}
@Test(expectedExceptions = SketchesStateException.class)
public void checkSketchesStateException() {
throw new SketchesStateException("This is a test.");
}
@Test
public void checkSketchesExceptionWithThrowable() {
try {
throw new SketchesException("First Exception.");
} catch (final SketchesException se) {
try {
throw new SketchesException("Second Exception. ", se);
} catch (final SketchesException se2) {
//success
}
}
}
}
| 2,418 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/common/ShuffleTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.common;
import static org.testng.Assert.fail;
import org.testng.annotations.Test;
public class ShuffleTest {
@Test
public void checkFloat() {
float[] array = new float[10];
for (int i = 0; i < array.length; i++) { array[i] = i; }
Shuffle.shuffle(array);
int neCount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != i) { neCount++; }
}
//System.out.println(neCount);
if (neCount == 0) { fail(); }
}
@Test
public void checkDouble() {
double[] array = new double[10];
for (int i = 0; i < array.length; i++) { array[i] = i; }
Shuffle.shuffle(array);
int neCount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != i) { neCount++; }
}
//System.out.println(neCount);
if (neCount == 0) { fail(); }
}
@Test
public void checkLong() {
long[] array = new long[10];
for (int i = 0; i < array.length; i++) { array[i] = i; }
Shuffle.shuffle(array);
int neCount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != i) { neCount++; }
}
//System.out.println(neCount);
if (neCount == 0) { fail(); }
}
@Test
public void checkInt() {
int[] array = new int[10];
for (int i = 0; i < array.length; i++) { array[i] = i; }
Shuffle.shuffle(array);
int neCount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != i) { neCount++; }
}
//System.out.println(neCount);
if (neCount == 0) { fail(); }
}
}
| 2,419 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/common/BoundsOnRatiosInSampledSetsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.common;
import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.checkInputs;
import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.getEstimateOfA;
import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.getEstimateOfB;
import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.getEstimateOfBoverA;
import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.getLowerBoundForBoverA;
import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.getUpperBoundForBoverA;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
public class BoundsOnRatiosInSampledSetsTest {
@Test
public void checkNormalReturns() {
getLowerBoundForBoverA(500, 100, .1);
getLowerBoundForBoverA(500, 100, 0.75);
getLowerBoundForBoverA(500, 100, 1.0);
assertEquals(getLowerBoundForBoverA(0, 0, .1), 0.0, 0.0);
getUpperBoundForBoverA(500, 100, .1);
getUpperBoundForBoverA(500, 100, 0.75);
getUpperBoundForBoverA(500, 100, 1.0);
assertEquals(getUpperBoundForBoverA(0, 0, .1), 1.0, 0.0);
getEstimateOfBoverA(500,100);
getEstimateOfA(500, .1);
getEstimateOfB(100, .1);
assertEquals(getEstimateOfBoverA(0, 0), .5, 0.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInputA() {
checkInputs(-1, 0, .3);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInputB() {
checkInputs(500, -1, .3);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInputF() {
checkInputs(500, 100, -1);
}
}
| 2,420 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/common/TestUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.common;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* Utilities common to testing
*/
public final class TestUtil {
private static final String userDir = System.getProperty("user.dir");
/**
* TestNG group constants
*/
public static final String GENERATE_JAVA_FILES = "generate_java_files";
public static final String CHECK_CPP_FILES = "check_cpp_files";
public static final String CHECK_CPP_HISTORICAL_FILES = "check_cpp_historical_files";
/**
* The full target Path for Java serialized sketches to be tested by other languages.
*/
public static final Path javaPath = createPath("serialization_test_data/java_generated_files");
/**
* The full target Path for C++ serialized sketches to be tested by Java.
*/
public static final Path cppPath = createPath("serialization_test_data/cpp_generated_files");
private static Path createPath(final String projectLocalDir) {
try {
return Files.createDirectories(Paths.get(userDir, projectLocalDir));
} catch (IOException e) { throw new SketchesArgumentException(e.getCause().toString()); }
}
//Get Resources
private static final int BUF_SIZE = 1 << 13;
/**
* Gets the file defined by the given resource file's shortFileName.
* @param shortFileName the last name in the pathname's name sequence.
* @return the file defined by the given resource file's shortFileName.
*/
public static File getResourceFile(final String shortFileName) {
Objects.requireNonNull(shortFileName, "input parameter 'String shortFileName' cannot be null.");
final String slashName = (shortFileName.charAt(0) == '/') ? shortFileName : '/' + shortFileName;
final URL url = Util.class.getResource(slashName);
Objects.requireNonNull(url, "resource " + slashName + " returns null URL.");
File file;
file = createTempFile(slashName);
if (url.getProtocol().equals("jar")) { //definitely a jar
try (final InputStream input = Util.class.getResourceAsStream(slashName);
final OutputStream out = new FileOutputStream(file)) {
Objects.requireNonNull(input, "InputStream is null.");
int numRead = 0;
final byte[] buf = new byte[1024];
while ((numRead = input.read(buf)) != -1) { out.write(buf, 0, numRead); }
} catch (final IOException e ) { throw new RuntimeException(e); }
} else { //protocol says resource is not a jar, must be a file
file = new File(getResourcePath(url));
}
if (!file.setReadable(false, true)) {
throw new IllegalStateException("Failed to set owner only 'Readable' on file");
}
if (!file.setWritable(false, false)) {
throw new IllegalStateException("Failed to set everyone 'Not Writable' on file");
}
return file;
}
/**
* Returns a byte array of the contents of the file defined by the given resource file's shortFileName.
* @param shortFileName the last name in the pathname's name sequence.
* @return a byte array of the contents of the file defined by the given resource file's shortFileName.
* @throws IllegalArgumentException if resource cannot be read.
*/
public static byte[] getResourceBytes(final String shortFileName) {
Objects.requireNonNull(shortFileName, "input parameter 'String shortFileName' cannot be null.");
final String slashName = (shortFileName.charAt(0) == '/') ? shortFileName : '/' + shortFileName;
final URL url = Util.class.getResource(slashName);
Objects.requireNonNull(url, "resource " + slashName + " returns null URL.");
final byte[] out;
if (url.getProtocol().equals("jar")) { //definitely a jar
try (final InputStream input = Util.class.getResourceAsStream(slashName)) {
out = readAllBytesFromInputStream(input);
} catch (final IOException e) { throw new RuntimeException(e); }
} else { //protocol says resource is not a jar, must be a file
try {
out = Files.readAllBytes(Paths.get(getResourcePath(url)));
} catch (final IOException e) { throw new RuntimeException(e); }
}
return out;
}
/**
* Note: This is only needed in Java 8 as it is part of Java 9+.
* Read all bytes from the given <i>InputStream</i>.
* This is limited to streams that are no longer than the maximum allocatable byte array determined by the VM.
* This may be a little smaller than <i>Integer.MAX_VALUE</i>.
* @param in the Input Stream
* @return byte array
*/
public static byte[] readAllBytesFromInputStream(final InputStream in) {
return readBytesFromInputStream(Integer.MAX_VALUE, in);
}
/**
* Note: This is only needed in Java 8 as is part of Java 9+.
* Read <i>numBytesToRead</i> bytes from an input stream into a single byte array.
* This is limited to streams that are no longer than the maximum allocatable byte array determined by the VM.
* This may be a little smaller than <i>Integer.MAX_VALUE</i>.
* @param numBytesToRead number of bytes to read
* @param in the InputStream
* @return the filled byte array from the input stream
* @throws IllegalArgumentException if array size grows larger than what can be safely allocated by some VMs.
*/
public static byte[] readBytesFromInputStream(final int numBytesToRead, final InputStream in) {
if (numBytesToRead < 0) { throw new IllegalArgumentException("numBytesToRead must be positive or zero."); }
List<byte[]> buffers = null;
byte[] result = null;
int totalBytesRead = 0;
int remaining = numBytesToRead;
int chunkCnt;
do {
final byte[] partialBuffer = new byte[Math.min(remaining, BUF_SIZE)];
int numRead = 0;
try {
// reads input stream in chunks of partial buffers, stops at EOF or when remaining is zero.
while ((chunkCnt =
in.read(partialBuffer, numRead, Math.min(partialBuffer.length - numRead, remaining))) > 0) {
numRead += chunkCnt;
remaining -= chunkCnt;
}
} catch (final IOException e) { throw new RuntimeException(e); }
if (numRead > 0) {
if (Integer.MAX_VALUE - Long.BYTES - totalBytesRead < numRead) {
throw new IllegalArgumentException(
"Input stream is larger than what can be safely allocated as a byte[] in some VMs."); }
totalBytesRead += numRead;
if (result == null) {
result = partialBuffer;
} else {
if (buffers == null) {
buffers = new ArrayList<>();
buffers.add(result);
}
buffers.add(partialBuffer);
}
}
} while (chunkCnt >= 0 && remaining > 0);
final byte[] out;
if (buffers == null) {
if (result == null) {
out = new byte[0];
} else {
out = result.length == totalBytesRead ? result : Arrays.copyOf(result, totalBytesRead);
}
return out;
}
result = new byte[totalBytesRead];
int offset = 0;
remaining = totalBytesRead;
for (byte[] b : buffers) {
final int count = Math.min(b.length, remaining);
System.arraycopy(b, 0, result, offset, count);
offset += count;
remaining -= count;
}
return result;
}
private static String getResourcePath(final URL url) { //must not be null
try {
final URI uri = url.toURI();
//decodes any special characters
final String path = uri.isAbsolute() ? Paths.get(uri).toAbsolutePath().toString() : uri.getPath();
return path;
} catch (final URISyntaxException e) {
throw new IllegalArgumentException("Cannot find resource: " + url.toString() + Util.LS + e);
}
}
/**
* Create an empty temporary file.
* On a Mac these files are stored at the system variable $TMPDIR. They should be cleared on a reboot.
* @param shortFileName the name before prefixes and suffixes are added here and by the OS.
* The final extension will be the current extension. The prefix "temp_" is added here.
* @return a temp file,which will be eventually deleted by the OS
*/
private static File createTempFile(final String shortFileName) {
//remove any leading slash
final String resName = (shortFileName.charAt(0) == '/') ? shortFileName.substring(1) : shortFileName;
final String suffix;
final String name;
final int lastIdx = resName.length() - 1;
final int lastIdxOfDot = resName.lastIndexOf('.');
if (lastIdxOfDot == -1) {
suffix = ".tmp";
name = resName;
} else if (lastIdxOfDot == lastIdx) {
suffix = ".tmp";
name = resName.substring(0, lastIdxOfDot);
} else { //has a real suffix
suffix = resName.substring(lastIdxOfDot);
name = resName.substring(0, lastIdxOfDot);
}
final File file;
try {
file = File.createTempFile("temp_" + name, suffix);
if (!file.setReadable(false, true)) {
throw new IllegalStateException("Failed to set only owner 'Readable' on file");
}
if (!file.setWritable(false, true)) {
throw new IllegalStateException("Failed to set only owner 'Writable' on file");
}
} catch (final IOException e) { throw new RuntimeException(e); }
return file;
}
}
| 2,421 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSetsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.thetacommon;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.theta.UpdateSketch;
import org.apache.datasketches.theta.UpdateSketchBuilder;
import org.apache.datasketches.tuple.Sketch;
import org.apache.datasketches.tuple.UpdatableSketch;
import org.apache.datasketches.tuple.UpdatableSketchBuilder;
import org.apache.datasketches.tuple.adouble.DoubleSummary;
import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory;
import org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations;
import org.apache.datasketches.tuple.Intersection;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
/**
* @author Lee Rhodes
* @author David Cromberge
*/
public class BoundsOnRatiosInTupleSketchedSetsTest {
private final DoubleSummary.Mode umode = DoubleSummary.Mode.Sum;
private final DoubleSummarySetOperations dsso = new DoubleSummarySetOperations();
private final DoubleSummaryFactory factory = new DoubleSummaryFactory(umode);
private final UpdateSketchBuilder thetaBldr = UpdateSketch.builder();
private final UpdatableSketchBuilder<Double, DoubleSummary> tupleBldr = new UpdatableSketchBuilder<>(factory);
private final Double constSummary = 1.0;
@Test
public void checkNormalReturns1() { // tuple, tuple
final UpdatableSketch<Double, DoubleSummary> skA = tupleBldr.build(); //4K
final UpdatableSketch<Double, DoubleSummary> skC = tupleBldr.build();
final int uA = 10000;
final int uC = 100000;
for (int i = 0; i < uA; i++) { skA.update(i, constSummary); }
for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2), constSummary); }
final Intersection<DoubleSummary> inter = new Intersection<>(dsso);
inter.intersect(skA);
inter.intersect(skC);
final Sketch<DoubleSummary> skB = inter.getResult();
double est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skB);
double lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skB);
double ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skB);
assertTrue(ub > est);
assertTrue(est > lb);
assertEquals(est, 0.5, .03);
println("ub : " + ub);
println("est: " + est);
println("lb : " + lb);
skA.reset(); //skA is now empty
est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skB);
lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skB);
ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skB);
println("ub : " + ub);
println("est: " + est);
println("lb : " + lb);
skC.reset(); //Now both are empty
est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skC);
lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skC);
ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skC);
println("ub : " + ub);
println("est: " + est);
println("lb : " + lb);
}
@Test
public void checkNormalReturns2() { // tuple, theta
final UpdatableSketch<Double, DoubleSummary> skA = tupleBldr.build(); //4K
final UpdateSketch skC = thetaBldr.build();
final int uA = 10000;
final int uC = 100000;
for (int i = 0; i < uA; i++) { skA.update(i, constSummary); }
for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2)); }
final Intersection<DoubleSummary> inter = new Intersection<>(dsso);
inter.intersect(skA);
inter.intersect(skC, factory.newSummary());
final Sketch<DoubleSummary> skB = inter.getResult();
double est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skB);
double lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skB);
double ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skB);
assertTrue(ub > est);
assertTrue(est > lb);
assertEquals(est, 0.5, .03);
println("ub : " + ub);
println("est: " + est);
println("lb : " + lb);
skA.reset(); //skA is now empty
est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skB);
lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skB);
ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skB);
println("ub : " + ub);
println("est: " + est);
println("lb : " + lb);
skC.reset(); //Now both are empty
est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skC);
lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skC);
ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skC);
println("ub : " + ub);
println("est: " + est);
println("lb : " + lb);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkAbnormalReturns1() { // tuple, tuple
final UpdatableSketch<Double, DoubleSummary> skA = tupleBldr.build(); //4K
final UpdatableSketch<Double, DoubleSummary> skC = tupleBldr.build();
final int uA = 100000;
final int uC = 10000;
for (int i = 0; i < uA; i++) { skA.update(i, constSummary); }
for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2), constSummary); }
BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skC);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkAbnormalReturns2() { // tuple, theta
final UpdatableSketch<Double, DoubleSummary> skA = tupleBldr.build(); //4K
final UpdateSketch skC = thetaBldr.build();
final int uA = 100000;
final int uC = 10000;
for (int i = 0; i < uA; i++) { skA.update(i, constSummary); }
for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2)); }
BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skC);
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,422 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/thetacommon/QuickSelectTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.thetacommon;
import static java.lang.String.format;
import static org.apache.datasketches.thetacommon.QuickSelect.select;
import static org.apache.datasketches.thetacommon.QuickSelect.selectExcludingZeros;
import static org.apache.datasketches.thetacommon.QuickSelect.selectIncludingZeros;
import java.util.Random;
import org.apache.datasketches.common.SketchesArgumentException;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class QuickSelectTest {
private static final String LS = System.getProperty("line.separator");
private static final Random random = new Random(); // pseudo-random number generator
//long[] arrays
@Test
public void checkQuickSelect0Based() {
final int len = 64;
final long[] arr = new long[len];
for (int i = 0; i < len; i++ ) {
arr[i] = i;
}
for (int pivot = 0; pivot < 64; pivot++ ) {
final long trueVal = pivot;
for (int i = 0; i < 1000; i++ ) {
shuffle(arr);
final long retVal = select(arr, 0, len - 1, pivot);
Assert.assertEquals(retVal, trueVal);
}
}
}
@Test
public void checkQuickSelect1BasedExcludingZeros() {
final int len = 64;
final int nonZeros = (7 * len) / 8;
final long[] arr = new long[len];
for (int i = 0; i < nonZeros; i++ ) {
arr[i] = i + 1;
}
final int pivot = len / 2;
final long trueVal = arr[pivot - 1];
shuffle(arr);
final long retVal = selectExcludingZeros(arr, nonZeros, pivot);
Assert.assertEquals(retVal, trueVal);
}
@Test
public void checkQuickSelect1BasedExcludingZeros2() {
final int len = 64;
final int nonZeros = 16;
final long[] arr = new long[len];
for (int i = 0; i < nonZeros; i++ ) {
arr[i] = i + 1;
}
shuffle(arr);
final int pivot = len / 2;
final long retVal = selectExcludingZeros(arr, nonZeros, pivot);
Assert.assertEquals(retVal, 0);
}
@Test
public void checkQuickSelect1BasedIncludingZeros() {
final int len = 64;
final int zeros = len / 8;
final long[] arr = new long[len];
for (int i = zeros; i < len; i++ ) {
arr[i] = i + 1;
}
final int pivot = len / 2;
final long trueVal = arr[pivot - 1];
shuffle(arr);
final long retVal = selectIncludingZeros(arr, pivot);
Assert.assertEquals(retVal, trueVal);
}
//double[] arrays
@Test
public void checkQuickSelectDbl0Based() {
final int len = 64;
final double[] arr = new double[len];
for (int i = 0; i < len; i++ ) {
arr[i] = i;
}
for (int pivot = 0; pivot < 64; pivot++ ) {
final double trueVal = pivot;
for (int i = 0; i < 1000; i++ ) {
shuffle(arr);
final double retVal = select(arr, 0, len - 1, pivot);
Assert.assertEquals(retVal, trueVal, 0.0);
}
}
}
@Test
public void checkQuickSelectDbl1BasedExcludingZeros() {
final int len = 64;
final int nonZeros = (7 * len) / 8;
final double[] arr = new double[len];
for (int i = 0; i < nonZeros; i++ ) {
arr[i] = i + 1;
}
final int pivot = len / 2;
final double trueVal = arr[pivot - 1];
shuffle(arr);
final double retVal = selectExcludingZeros(arr, nonZeros, pivot);
Assert.assertEquals(retVal, trueVal, 0.0);
}
@Test
public void checkQuickSelectDbl1BasedExcludingZeros2() {
final int len = 64;
final int nonZeros = 16;
final double[] arr = new double[len];
for (int i = 0; i < nonZeros; i++ ) {
arr[i] = i + 1;
}
shuffle(arr);
final int pivot = len / 2;
final double retVal = selectExcludingZeros(arr, nonZeros, pivot);
Assert.assertEquals(retVal, 0, 0.0);
}
@Test
public void checkQuickSelectDbl1BasedIncludingZeros() {
final int len = 64;
final int zeros = len / 8;
final double[] arr = new double[len];
for (int i = zeros; i < len; i++ ) {
arr[i] = i + 1;
}
final int pivot = len / 2;
final double trueVal = arr[pivot - 1];
shuffle(arr);
final double retVal = selectIncludingZeros(arr, pivot);
Assert.assertEquals(retVal, trueVal, 0.0);
}
/**
* Rearrange the elements of an array in random order.
* @param a long array
*/
public static void shuffle(final long[] a) {
final int N = a.length;
for (int i = 0; i < N; i++ ) {
final int r = i + uniform(N - i); // between i and N-1
final long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an array in random order.
* @param a double array
*/
public static void shuffle(final double[] a) {
final int N = a.length;
for (int i = 0; i < N; i++ ) {
final int r = i + uniform(N - i); // between i and N-1
final double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Returns an integer uniformly between 0 (inclusive) and n (exclusive) where {@code n > 0}
*
* @param n the upper exclusive bound
* @return random integer
*/
public static int uniform(final int n) {
if (n <= 0) {
throw new SketchesArgumentException("n must be positive");
}
return random.nextInt(n);
}
private static String printArr(final long[] arr) {
final StringBuilder sb = new StringBuilder();
final int len = arr.length;
sb.append(" Base0").append(" Base1").append(" Value").append(LS);
for (int i = 0; i < len; i++ ) {
sb
.append(format("%6d", i)).append(format("%6d", i + 1)).append(format("%6d", arr[i]))
.append(LS);
}
return sb.toString();
}
private static String printArr(final double[] arr) {
final StringBuilder sb = new StringBuilder();
final int len = arr.length;
sb.append(" Base0").append(" Base1").append(" Value").append(LS);
for (int i = 0; i < len; i++ ) {
sb
.append(format("%6d", i)).append(format("%6d", i + 1)).append(format("%9.3f", arr[i]))
.append(LS);
}
return sb.toString();
}
//For console testing
static void test1() {
final int len = 16;
final int nonZeros = (3 * len) / 4;
final int zeros = len - nonZeros;
final long[] arr = new long[len];
for (int i = 0; i < nonZeros; i++ ) {
arr[i] = i + 1;
}
println("Generated Numbers:");
println(printArr(arr));
shuffle(arr);
println("Randomized Ordering:");
println(printArr(arr));
final int pivot = len / 2;
println("select(...):");
println("ArrSize : " + len);
println("NonZeros: " + nonZeros);
println("Zeros : " + zeros);
println("Choose pivot at 1/2 array size, pivot: " + pivot);
final long ret = select(arr, 0, len - 1, pivot);
println("Return value of 0-based pivot including zeros:");
println("select(arr, 0, " + (len - 1) + ", " + pivot + ") => " + ret);
println("0-based index of pivot = pivot = " + (pivot));
println("Result Array:" + LS);
println(printArr(arr));
}
//For console testing
static void test2() {
final int len = 16;
final int nonZeros = (3 * len) / 4;
final int zeros = len - nonZeros;
final long[] arr = new long[len];
for (int i = 0; i < nonZeros; i++ ) {
arr[i] = i + 1;
}
println("Generated Numbers:");
println(printArr(arr));
shuffle(arr);
println("Randomized Ordering:");
println(printArr(arr));
final int pivot = len / 2; //= 8
println("selectDiscountingZeros(...):");
println("ArrSize : " + len);
println("NonZeros: " + nonZeros);
println("Zeros : " + zeros);
println("Choose pivot at 1/2 array size, pivot= " + pivot);
final long ret = selectExcludingZeros(arr, nonZeros, pivot);
println("Return value of 1-based pivot discounting zeros:");
println("selectDiscountingZeros(arr, " + nonZeros + ", " + pivot + ") => " + ret);
println("0-based index of pivot= pivot+zeros-1 = " + ((pivot + zeros) - 1));
println("Result Array:" + LS);
println(printArr(arr));
}
//For console testing
static void test3() {
final int len = 16;
final int nonZeros = (3 * len) / 4;
final int zeros = len - nonZeros;
final long[] arr = new long[len];
for (int i = 0; i < nonZeros; i++ ) {
arr[i] = i + 1;
}
println("Generated Numbers:");
println(printArr(arr));
shuffle(arr);
println("Randomized Ordering:");
println(printArr(arr));
final int pivot = len / 2; //= 8
println("selectIncludingZeros(...):");
println("ArrSize : " + len);
println("NonZeros: " + nonZeros);
println("Zeros : " + zeros);
println("Choose pivot at 1/2 array size, pivot= " + pivot);
final long ret = selectIncludingZeros(arr, pivot);
println("Return value of 1-based pivot including zeros:");
println("selectIncludingZeros(arr, " + pivot + ") => " + ret);
println("0-based index of pivot= pivot-1 = " + (pivot - 1));
println("Result Array:" + LS);
println(printArr(arr));
}
static void testDbl1() {
final int len = 16;
final int nonZeros = (3 * len) / 4;
final int zeros = len - nonZeros;
final double[] arr = new double[len];
for (int i = 0; i < nonZeros; i++ ) {
arr[i] = i + 1;
}
println("Generated Numbers:");
println(printArr(arr));
shuffle(arr);
println("Randomized Ordering:");
println(printArr(arr));
final int pivot = len / 2;
println("select(...):");
println("ArrSize : " + len);
println("NonZeros: " + nonZeros);
println("Zeros : " + zeros);
println("Choose pivot at 1/2 array size, pivot: " + pivot);
final double ret = select(arr, 0, len - 1, pivot);
println("Return value of 0-based pivot including zeros:");
println("select(arr, 0, " + (len - 1) + ", " + pivot + ") => " + ret);
println("0-based index of pivot = pivot = " + (pivot));
println("Result Array:" + LS);
println(printArr(arr));
}
//For console testing
static void testDbl2() {
final int len = 16;
final int nonZeros = (3 * len) / 4;
final int zeros = len - nonZeros;
final double[] arr = new double[len];
for (int i = 0; i < nonZeros; i++ ) {
arr[i] = i + 1;
}
println("Generated Numbers:");
println(printArr(arr));
shuffle(arr);
println("Randomized Ordering:");
println(printArr(arr));
final int pivot = len / 2; //= 8
println("selectDiscountingZeros(...):");
println("ArrSize : " + len);
println("NonZeros: " + nonZeros);
println("Zeros : " + zeros);
println("Choose pivot at 1/2 array size, pivot= " + pivot);
final double ret = selectExcludingZeros(arr, nonZeros, pivot);
println("Return value of 1-based pivot discounting zeros:");
println("selectDiscountingZeros(arr, " + nonZeros + ", " + pivot + ") => " + ret);
println("0-based index of pivot= pivot+zeros-1 = " + ((pivot + zeros) - 1));
println("Result Array:" + LS);
println(printArr(arr));
}
//For console testing
static void testDbl3() {
final int len = 16;
final int nonZeros = (3 * len) / 4;
final int zeros = len - nonZeros;
final double[] arr = new double[len];
for (int i = 0; i < nonZeros; i++ ) {
arr[i] = i + 1;
}
println("Generated Numbers:");
println(printArr(arr));
shuffle(arr);
println("Randomized Ordering:");
println(printArr(arr));
final int pivot = len / 2; //= 8
println("selectIncludingZeros(...):");
println("ArrSize : " + len);
println("NonZeros: " + nonZeros);
println("Zeros : " + zeros);
println("Choose pivot at 1/2 array size, pivot= " + pivot);
final double ret = selectIncludingZeros(arr, pivot);
println("Return value of 1-based pivot including zeros:");
println("selectIncludingZeros(arr, " + pivot + ") => " + ret);
println("0-based index of pivot= pivot-1 = " + (pivot - 1));
println("Result Array:" + LS);
println(printArr(arr));
}
// public static void main(String[] args) {
// println(LS+"==LONGS 1=========="+LS);
// test1();
// println(LS+"==LONGS 2=========="+LS);
// test2();
// println(LS+"==LONGS 3=========="+LS);
// test3();
// println(LS+"==DOUBLES 1========"+LS);
// testDbl1();
// println(LS+"==DOUBLES 2========"+LS);
// testDbl2();
// println(LS+"==DOUBLES 3========"+LS);
// testDbl3();
//
//
// QuickSelectTest qst = new QuickSelectTest();
// qst.checkQuickSelect0Based();
// qst.checkQuickSelect1BasedExcludingZeros();
// qst.checkQuickSelect1BasedExcludingZeros2();
// qst.checkQuickSelect1BasedIncludingZeros();
// qst.checkQuickSelectDbl0Based();
// qst.checkQuickSelectDbl1BasedExcludingZeros();
// qst.checkQuickSelectDbl1BasedExcludingZeros2();
// qst.checkQuickSelectDbl1BasedIncludingZeros();
//
// }
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
/**
* @param d value to print
*/
static void println(final double d) {
//System.out.println(d); //disable here
}
}
| 2,423 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/thetacommon/ThetaUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.thetacommon;
import org.apache.datasketches.quantilescommon.QuantilesUtil;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class ThetaUtilTest {
@Test
public void checkStartingSubMultiple() {
Assert.assertEquals(ThetaUtil.startingSubMultiple(8, 3, 4), 5);
Assert.assertEquals(ThetaUtil.startingSubMultiple(7, 3, 4), 4);
Assert.assertEquals(ThetaUtil.startingSubMultiple(6, 3, 4), 6);
}
@Test(expectedExceptions = NullPointerException.class)
public void checkValidateValuesNullException() {
QuantilesUtil.checkDoublesSplitPointsOrder(null);
}
}
| 2,424 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSetsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.thetacommon;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.theta.CompactSketch;
import org.apache.datasketches.theta.Intersection;
import org.apache.datasketches.theta.Sketches;
import org.apache.datasketches.theta.UpdateSketch;
import org.testng.annotations.Test;
public class BoundsOnRatiosInThetaSketchedSetsTest {
@Test
public void checkNormalReturns() {
final UpdateSketch skA = Sketches.updateSketchBuilder().build(); //4K
final UpdateSketch skC = Sketches.updateSketchBuilder().build();
final int uA = 10000;
final int uC = 100000;
for (int i = 0; i < uA; i++) { skA.update(i); }
for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2)); }
final Intersection inter = Sketches.setOperationBuilder().buildIntersection();
inter.intersect(skA);
inter.intersect(skC);
final CompactSketch skB = inter.getResult();
double est = BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(skA, skB);
double lb = BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(skA, skB);
double ub = BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(skA, skB);
assertTrue(ub > est);
assertTrue(est > lb);
assertEquals(est, 0.5, .03);
println("ub : " + ub);
println("est: " + est);
println("lb : " + lb);
skA.reset(); //skA is now empty
est = BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(skA, skB);
lb = BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(skA, skB);
ub = BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(skA, skB);
println("ub : " + ub);
println("est: " + est);
println("lb : " + lb);
skC.reset(); //Now both are empty
est = BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(skA, skC);
lb = BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(skA, skC);
ub = BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(skA, skC);
println("ub : " + ub);
println("est: " + est);
println("lb : " + lb);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkAbnormalReturns() {
final UpdateSketch skA = Sketches.updateSketchBuilder().build(); //4K
final UpdateSketch skC = Sketches.updateSketchBuilder().build();
final int uA = 100000;
final int uC = 10000;
for (int i = 0; i < uA; i++) { skA.update(i); }
for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2)); }
BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(skA, skC);
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,425 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/thetacommon/HashOperationsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.thetacommon;
import static org.apache.datasketches.hash.MurmurHash3.hash;
import static org.apache.datasketches.thetacommon.HashOperations.checkHashCorruption;
import static org.apache.datasketches.thetacommon.HashOperations.checkThetaCorruption;
import static org.apache.datasketches.thetacommon.HashOperations.continueCondition;
import static org.apache.datasketches.thetacommon.HashOperations.hashArrayInsert;
import static org.apache.datasketches.thetacommon.HashOperations.hashInsertOnly;
import static org.apache.datasketches.thetacommon.HashOperations.hashInsertOnlyMemory;
import static org.apache.datasketches.thetacommon.HashOperations.hashSearch;
import static org.apache.datasketches.thetacommon.HashOperations.hashSearchMemory;
import static org.apache.datasketches.thetacommon.HashOperations.hashSearchOrInsert;
import static org.apache.datasketches.thetacommon.HashOperations.hashSearchOrInsertMemory;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesStateException;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
public class HashOperationsTest {
//Not otherwise already covered
@Test(expectedExceptions = SketchesStateException.class)
public void testThetaCorruption1() {
checkThetaCorruption(0);
}
@Test(expectedExceptions = SketchesStateException.class)
public void testThetaCorruption2() {
checkThetaCorruption(-1);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void testHashCorruption() {
checkHashCorruption(-1);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHashSearch() {
hashSearch(new long[4], 2, 0);
}
@Test
public void checkHashArrayInsert() {
final long[] hTable = new long[16];
final long[] hashIn = new long[1];
for (int i = 0; i < 8; i++) {
hashIn[0] = i;
final long h = hash(hashIn, 0)[0] >>> 1;
hashInsertOnly(hTable, 4, h);
final int count = hashArrayInsert(hTable, hTable, 4, Long.MAX_VALUE);
assertEquals(count, 0);
}
}
@Test
public void testContinueCondtion() {
final long thetaLong = Long.MAX_VALUE / 2;
assertTrue(continueCondition(thetaLong, 0));
assertTrue(continueCondition(thetaLong, thetaLong));
assertTrue(continueCondition(thetaLong, thetaLong + 1));
assertFalse(continueCondition(thetaLong, thetaLong - 1));
}
@Test
public void testHashInsertOnlyNoStride() {
final long[] table = new long[32];
final int index = hashInsertOnly(table, 5, 1);
assertEquals(index, 1);
assertEquals(table[1], 1L);
}
@Test
public void testHashInsertOnlyWithStride() {
final long[] table = new long[32];
table[1] = 1;
final int index = hashInsertOnly(table, 5, 1);
assertEquals(index, 2);
assertEquals(table[2], 1L);
}
@Test
public void testHashInsertOnlyMemoryNoStride() {
final long[] table = new long[32];
final WritableMemory mem = WritableMemory.writableWrap(table);
final int index = hashInsertOnlyMemory(mem, 5, 1, 0);
assertEquals(index, 1);
assertEquals(table[1], 1L);
}
@Test
public void testHashInsertOnlyMemoryWithStride() {
final long[] table = new long[32];
table[1] = 1;
final WritableMemory mem = WritableMemory.writableWrap(table);
final int index = hashInsertOnlyMemory(mem, 5, 1, 0);
assertEquals(index, 2);
assertEquals(table[2], 1L);
}
@Test
public void checkFullHeapTableCatchesInfiniteLoop() {
final long[] table = new long[32];
for (int i = 1; i <= 32; ++i) {
hashInsertOnly(table, 5, i);
}
// table full; search returns not found, others throw exception
final int retVal = hashSearch(table, 5, 33);
assertEquals(retVal, -1);
try {
hashInsertOnly(table, 5, 33);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
try {
hashSearchOrInsert(table, 5, 33);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
}
@Test
public void checkFullDirectTableCatchesInfiniteLoop() {
final long[] table = new long[32];
final WritableMemory mem = WritableMemory.writableWrap(table);
for (int i = 1; i <= 32; ++i) {
hashInsertOnlyMemory(mem, 5, i, 0);
}
// table full; search returns not found, others throw exception
final int retVal = hashSearchMemory(mem, 5, 33, 0);
assertEquals(retVal, -1);
try {
hashInsertOnlyMemory(mem, 5, 33, 0);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
try {
hashSearchOrInsertMemory(mem, 5, 33, 0);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
}
@Test
public void checkFullFastDirectTableCatchesInfiniteLoop() {
final long[] table = new long[32];
final WritableMemory wmem = WritableMemory.writableWrap(table);
for (int i = 1; i <= 32; ++i) {
hashInsertOnlyMemory(wmem, 5, i, 0);
}
// table full; throws exception
try {
hashInsertOnlyMemory(wmem, 5, 33, 0);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
try {
hashSearchOrInsertMemory(wmem, 5, 33, 0);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,426 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/thetacommon/BinomialBoundsNTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.thetacommon;
import static org.apache.datasketches.thetacommon.BinomialBoundsN.checkArgs;
import static org.apache.datasketches.thetacommon.BinomialBoundsN.getLowerBound;
import static org.apache.datasketches.thetacommon.BinomialBoundsN.getUpperBound;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.testng.annotations.Test;
/**
* @author Kevin Lang
*/
public class BinomialBoundsNTest {
public static double[] runTestAux(final long max_numSamplesI, final int ci, final double min_p) {
long numSamplesI = 0;
double p, lb, ub;
double sum1 = 0.0;
double sum2 = 0.0;
double sum3 = 0.0;
double sum4 = 0.0;
long count = 0;
while (numSamplesI <= max_numSamplesI) { /* was <= */
p = 1.0;
while (p >= min_p) {
lb = BinomialBoundsN.getLowerBound(numSamplesI, p, ci, false);
ub = BinomialBoundsN.getUpperBound(numSamplesI, p, ci, false);
// if (numSamplesI == 300 && p > 0.365 && p < 0.367) { ub += 0.01; } // artificial discrepancy
// the logarithm helps discrepancies to not be swamped out of the total
sum1 += Math.log(lb + 1.0);
sum2 += Math.log(ub + 1.0);
count += 2;
if (p < 1.0) {
lb = BinomialBoundsN.getLowerBound(numSamplesI, 1.0 - p, ci, false);
ub = BinomialBoundsN.getUpperBound(numSamplesI, 1.0 - p, ci, false);
sum3 += Math.log(lb + 1.0);
sum4 += Math.log(ub + 1.0);
count += 2;
}
p *= 0.99;
}
numSamplesI = Math.max(numSamplesI + 1, (1001 * numSamplesI) / 1000);
}
println(String.format("{%.15e, %.15e, %.15e, %.15e, %d}", sum1, sum2, sum3, sum4, count));
final double[] arrOut = {sum1, sum2, sum3, sum4, count};
return arrOut;
}
private static final double TOL = 1E-15;
@Test
public static void checkBounds() {
int i = 0;
for (int ci = 1; ci <= 3; ci++, i++) {
final double[] arr = runTestAux(20, ci, 1e-3);
for (int j = 0; j < 5; j++) {
assertTrue(((arr[j] / std[i][j]) - 1.0) < TOL);
}
}
for (int ci = 1; ci <= 3; ci++, i++) {
final double[] arr = runTestAux(200, ci, 1e-5);
for (int j = 0; j < 5; j++) {
assertTrue(((arr[j] / std[i][j]) - 1.0) < TOL);
}
}
//comment last one out for a shorter test
// for (int ci = 1; ci <= 3; ci++, i++) {
// final double[] arr = runTestAux(2000, ci, 1e-7);
// for (int j = 0; j < 5; j++) {
// assertTrue(((arr[j] / std[i][j]) - 1.0) < TOL);
// }
//}
}
// With all 3 enabled the test should produce in groups of 3 */
private static final double[][] std = {
{7.083330682531043e+04, 8.530373642825481e+04, 3.273647725073409e+04, 3.734024243699785e+04, 57750},
{6.539415269641498e+04, 8.945522372568645e+04, 3.222302546497840e+04, 3.904738469737429e+04, 57750},
{6.006043493107306e+04, 9.318105731423477e+04, 3.186269956585285e+04, 4.096466221922520e+04, 57750},
{2.275584770163813e+06, 2.347586549014998e+06, 1.020399409477305e+06, 1.036729927598294e+06, 920982},
{2.243569126699713e+06, 2.374663344107342e+06, 1.017017233582122e+06, 1.042597845553438e+06, 920982},
{2.210056231903739e+06, 2.400441267999687e+06, 1.014081235946986e+06, 1.049480769755676e+06, 920982},
{4.688240115809608e+07, 4.718067204619278e+07, 2.148362024482338e+07, 2.153118905212302e+07, 12834414},
{4.674205938540214e+07, 4.731333757486791e+07, 2.146902141966406e+07, 2.154916650733873e+07, 12834414},
{4.659896614422579e+07, 4.744404182094614e+07, 2.145525391547799e+07, 2.156815612325058e+07, 12834414}
};
@Test
public static void checkCheckArgs() {
try {
checkArgs(-1L, 1.0, 1);
checkArgs(10L, 0.0, 1);
checkArgs(10L, 1.01, 1);
checkArgs(10L, 1.0, 3);
checkArgs(10L, 1.0, 0);
checkArgs(10L, 1.0, 4);
fail("Expected SketchesArgumentException");
} catch (final SketchesArgumentException e) {
//pass
}
}
@Test
public static void checkComputeApproxBino_LB_UB() {
final long n = 100;
final double theta = (2.0 - 1e-5) / 2.0;
double result = getLowerBound(n, theta, 1, false);
assertEquals(result, n, 0.0);
result = getUpperBound(n, theta, 1, false);
assertEquals(result, n + 1, 0.0);
result = getLowerBound(n, theta, 1, true);
assertEquals(result, 0.0, 0.0);
result = getUpperBound(n, theta, 1, true);
assertEquals(result, 0.0, 0.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public static void checkThetaLimits1() {
BinomialBoundsN.getUpperBound(100, 1.1, 1, false);
}
@Test
public static void boundsExample() {
println("BinomialBoundsN Example:");
final int k = 500;
final double theta = 0.001;
final int stdDev = 2;
final double ub = BinomialBoundsN.getUpperBound(k, theta, stdDev, false);
final double est = k / theta;
final double lb = BinomialBoundsN.getLowerBound(k, theta, stdDev, false);
println("K=" + k + ", Theta=" + theta + ", SD=" + stdDev);
println("UB: " + ub);
println("Est: " + est);
println("LB: " + lb);
println("");
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,427 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantilescommon/LinearRanksAndQuantiles.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantilescommon;
import static org.apache.datasketches.common.Util.le;
import static org.apache.datasketches.common.Util.lt;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE;
import static org.testng.Assert.fail;
import java.util.Comparator;
public class LinearRanksAndQuantiles {
/**
* Gets the quantile based on the given normalized rank.
* <ul><li><b>getQuantile(rank, INCLUSIVE) or q(r, GE)</b><br>
* := Given r, return the quantile, q, of the smallest rank that is strictly Greater than or Equal to r.</li>
* <li><br>getQuantile(rank, EXCLUSIVE) or q(r, GT)</b><br>
* := Given r, return the quantile, q, of the smallest rank that is strictly Greater Than r.</li>
* </ul>
*
* @param cumWeights the given natural cumulative weights. The last value must be N.
* @param quantiles the given quantile array
* @param givenNormR the given normalized rank, which must be in the range [0.0, 1.0], inclusive.
* @param inclusive determines the search criterion used.
* @return the quantile
*/
public static float getTrueFloatQuantile(
final long[] cumWeights,
final float[] quantiles,
final double givenNormR,
final QuantileSearchCriteria inclusive) {
final int len = cumWeights.length;
final long N = cumWeights[len - 1];
float result = Float.NaN;
for (int i = 0; i < len; i++) {
if (i == len - 1) { //at top or single element array
double topR = (double)cumWeights[i] / N;
float topQ = quantiles[i];
if (inclusive == INCLUSIVE) {
if (givenNormR <= topR) { result = topQ; break; }
fail("normRank > 1.0");
}
//EXCLUSIVE
if (givenNormR < topR ) { result = topQ; break; }
if (givenNormR > 1.0) { fail("normRank > 1.0"); }
result =topQ; // R == 1.0
break;
}
else { //always at least two valid entries
double loR = (double)cumWeights[i] / N;
double hiR = (double)cumWeights[i + 1] / N;
float loQ = quantiles[i];
float hiQ = quantiles[i + 1];
if (inclusive == INCLUSIVE) {
if (i == 0) { //at bottom, starting up
if (givenNormR <= loR) { result = loQ; break; }
}
if (loR < givenNormR && givenNormR <= hiR) { result = hiQ; break; }
continue;
}
//EXCLUSIVE
if (i == 0) { //at bottom, starting up
if (givenNormR < loR) { result = loQ; break; }
}
if (loR <= givenNormR && givenNormR < hiR) { result = hiQ; break; }
continue;
}
}
return result;
}
/**
* Gets the quantile based on the given normalized rank.
* <ul><li><b>getQuantile(rank, INCLUSIVE) or q(r, GE)</b><br>
* := Given r, return the quantile, q, of the smallest rank that is strictly Greater than or Equal to r.</li>
* <li><br>getQuantile(rank, EXCLUSIVE) or q(r, GT)</b><br>
* := Given r, return the quantile, q, of the smallest rank that is strictly Greater Than r.</li>
* </ul>
*
* @param cumWeights the given natural cumulative weights. The last value must be N.
* @param quantiles the given quantile array
* @param givenNormR the given normalized rank, which must be in the range [0.0, 1.0], inclusive.
* @param inclusive determines the search criterion used.
* @return the quantile
*/
public static double getTrueDoubleQuantile(
final long[] cumWeights,
final double[] quantiles,
final double givenNormR,
final QuantileSearchCriteria inclusive) {
final int len = cumWeights.length;
final long N = cumWeights[len - 1];
double result = Double.NaN;
for (int i = 0; i < len; i++) {
if (i == len - 1) { //at top or single element array
double topR = (double)cumWeights[i] / N;
double topQ = quantiles[i];
if (inclusive == INCLUSIVE) {
if (givenNormR <= topR) { result = topQ; break; }
fail("normRank > 1.0");
}
//EXCLUSIVE
if (givenNormR < topR ) { result = topQ; break; }
if (givenNormR > 1.0) { fail("normRank > 1.0"); }
result = topQ; // R == 1.0
break;
}
else { //always at least two valid entries
double loR = (double)cumWeights[i] / N;
double hiR = (double)cumWeights[i + 1] / N;
double loQ = quantiles[i];
double hiQ = quantiles[i + 1];
if (inclusive == INCLUSIVE) {
if (i == 0) { //at bottom, starting up
if (givenNormR <= loR) { result = loQ; break; }
}
if (loR < givenNormR && givenNormR <= hiR) { result = hiQ; break; }
continue;
}
//EXCLUSIVE) {
if (i == 0) { //at bottom, starting up
if (givenNormR < loR) { result = loQ; break; }
}
if (loR <= givenNormR && givenNormR < hiR) { result = hiQ; break; }
continue;
}
}
return result;
}
/**
* Gets the quantile based on the given normalized rank.
* <ul><li><b>getQuantile(rank, INCLUSIVE) or q(r, GE)</b><br>
* := Given r, return the quantile, q, of the smallest rank that is strictly Greater than or Equal to r.</li>
* <li><br>getQuantile(rank, EXCLUSIVE) or q(r, GT)</b><br>
* := Given r, return the quantile, q, of the smallest rank that is strictly Greater Than r.</li>
* </ul>
*
* @param cumWeights the given natural cumulative weights. The last value must be N.
* @param quantiles the given quantile array
* @param givenNormR the given normalized rank, which must be in the range [0.0, 1.0], inclusive.
* @param inclusive determines the search criterion used.
* @return the quantile
*/
public static <T> T getTrueItemQuantile(
final long[] cumWeights,
final T[] quantiles,
final double givenNormR,
final QuantileSearchCriteria inclusive) {
final int len = cumWeights.length;
final long N = cumWeights[len - 1];
T result = null;
for (int i = 0; i < len; i++) {
if (i == len - 1) { //at top or single element array
double topR = (double)cumWeights[i] / N;
T topQ = quantiles[i];
if (inclusive == INCLUSIVE) {
if (givenNormR <= topR) { result = topQ; break; }
fail("normRank > 1.0");
}
//EXCLUSIVE
if (givenNormR < topR ) { result = topQ; break; }
if (givenNormR > 1.0) { fail("normRank > 1.0"); }
result = topQ; // R == 1.0
break;
}
else { //always at least two valid entries
double loR = (double)cumWeights[i] / N;
double hiR = (double)cumWeights[i + 1] / N;
T loQ = quantiles[i];
T hiQ = quantiles[i + 1];
if (inclusive == INCLUSIVE) {
if (i == 0) { //at bottom, starting up
if (givenNormR <= loR) { result = loQ; break; }
}
if (loR < givenNormR && givenNormR <= hiR) { result = hiQ; break; }
continue;
}
//EXCLUSIVE) {
if (i == 0) { //at bottom, starting up
if (givenNormR < loR) { result = loQ; break; }
}
if (loR <= givenNormR && givenNormR < hiR) { result = hiQ; break; }
continue;
}
}
return result;
}
/**
* Gets the normalized rank based on the given value.
* <ul><li><b>getRank(quantile, INCLUSIVE) or r(q, LE)</b><br>
* := Given q, return the rank, r, of the largest quantile that is less than or equal to q.</li>
* <li><b>getRank(quantile, EXCLUSIVE) or r(q, LT)</b>
* := Given q, return the rank, r, of the largest quantile that is strictly Less Than q.</li>
* </ul>
*
* @param cumWeights the given cumulative weights
* @param quantiles the given quantile array
* @param givenQ the given quantile
* @param inclusive determines the search criterion used.
* @return the normalized rank
*/
public static double getTrueFloatRank(
final long[] cumWeights,
final float[] quantiles,
final float givenQ,
final QuantileSearchCriteria inclusive) {
final int len = quantiles.length;
final long N = cumWeights[len -1];
double result = Double.NaN;
for (int i = len; i-- > 0; ) {
if (i == 0) { //at bottom of single element array
double bottomR = (double)cumWeights[i] / N;
float bottomQ = quantiles[i];
if (inclusive == INCLUSIVE) {
if (givenQ < bottomQ) { result = 0; break; }
result = bottomR;
break;
}
//EXCLUSIVE
if (givenQ <= bottomQ) { result = 0; break; }
if (bottomQ < givenQ) { result = bottomR; break; }
}
else { //always at least two valid entries
double loR = (double)cumWeights[i - 1] / N;
//double hiR = (double)cumWeights[i] / N;
float loQ = quantiles[i - 1];
float hiQ = quantiles[i];
if (inclusive == INCLUSIVE) {
if (i == len - 1) { //at top, starting down
if (hiQ <= givenQ) { result = 1.0; break; }
}
if (loQ <= givenQ && givenQ < hiQ) { result = loR; break; }
continue;
}
//EXCLUSIVE
if (i == len - 1) { //at top, starting down
if (hiQ < givenQ) { result = 1.0; break; }
}
if (loQ < givenQ && givenQ <= hiQ) { result = loR; break; }
continue;
}
}
return result;
}
/**
* Gets the normalized rank based on the given value.
* <ul><li><b>getRank(quantile, INCLUSIVE) or r(q, LE)</b><br>
* := Given q, return the rank, r, of the largest quantile that is less than or equal to q.</li>
* <li><b>getRank(quantile, EXCLUSIVE) or r(q, LT)</b>
* := Given q, return the rank, r, of the largest quantile that is strictly Less Than q.</li>
* </ul>
*
* @param cumWeights the given cumulative weights
* @param quantiles the given quantile array
* @param givenQ the given quantile
* @param inclusive determines the search criterion used.
* @return the normalized rank
*/
public static double getTrueDoubleRank(
final long[] cumWeights,
final double[] quantiles,
final double givenQ,
final QuantileSearchCriteria inclusive) {
final int len = quantiles.length;
final long N = cumWeights[len -1];
double result = Double.NaN;
for (int i = len; i-- > 0; ) {
if (i == 0) { //at bottom of single element array
double bottomR = (double)cumWeights[i] / N;
double bottomQ = quantiles[i];
if (inclusive == INCLUSIVE) {
if (givenQ < bottomQ) { result = 0; break; }
result = bottomR;
break;
}
//EXCLUSIVE
if (givenQ <= bottomQ) { result = 0; break; }
if (bottomQ < givenQ) { result = bottomR; break; }
}
else { //always at least two valid entries
double loR = (double)cumWeights[i - 1] / N;
//double hiR = (double)cumWeights[i] / N;
double loQ = quantiles[i - 1];
double hiQ = quantiles[i];
if (inclusive == INCLUSIVE) {
if (i == len - 1) { //at top, starting down
if (hiQ <= givenQ) { result = 1.0; break; }
}
if (loQ <= givenQ && givenQ < hiQ) { result = loR; break; }
continue;
}
//EXCLUSIVE
if (i == len - 1) { //at top, starting down
if (hiQ < givenQ) { result = 1.0; break; }
}
if (loQ < givenQ && givenQ <= hiQ) { result = loR; break; }
continue;
}
}
return result;
}
/**
* Gets the normalized rank based on the given value.
* <ul><li><b>getRank(quantile, INCLUSIVE) or r(q, LE)</b><br>
* := Given q, return the rank, r, of the largest quantile that is less than or equal to q.</li>
* <li><b>getRank(quantile, EXCLUSIVE) or r(q, LT)</b>
* := Given q, return the rank, r, of the largest quantile that is strictly Less Than q.</li>
* </ul>
*
* @param cumWeights the given cumulative weights
* @param quantiles the given quantile array
* @param givenQ the given quantile
* @param inclusive determines the search criterion used.
* @return the normalized rank
*/
public static <T> double getTrueItemRank(
final long[] cumWeights,
final T[] quantiles,
final T givenQ,
final QuantileSearchCriteria inclusive,
final Comparator<? super T> comp) {
final int len = quantiles.length;
final long N = cumWeights[len -1];
double result = Double.NaN;
for (int i = len; i-- > 0; ) {
if (i == 0) { //at bottom of single element array
double bottomR = (double)cumWeights[i] / N;
T bottomQ = quantiles[i];
if (inclusive == INCLUSIVE) {
if (lt(givenQ, bottomQ, comp)) { result = 0; break; }
result = bottomR;
break;
}
//EXCLUSIVE
if (le(givenQ, bottomQ, comp)) { result = 0; break; }
if (lt(bottomQ, givenQ, comp)) { result = bottomR; break; }
}
else { //always at least two valid entries
double loR = (double)cumWeights[i - 1] / N;
//double hiR = (double)cumWeights[i] / N;
T loQ = quantiles[i - 1];
T hiQ = quantiles[i];
if (inclusive == INCLUSIVE) {
if (i == len - 1) { //at top, starting down
if (le(hiQ, givenQ, comp)) { result = 1.0; break; }
}
if (le(loQ, givenQ,comp) && lt(givenQ, hiQ, comp)) { result = loR; break; }
continue;
}
//EXCLUSIVE
if (i == len - 1) { //at top, starting down
if (lt(hiQ, givenQ, comp)) { result = 1.0; break; }
}
if (lt(loQ, givenQ, comp) && le(givenQ, hiQ, comp)) { result = loR; break; }
continue;
}
}
return result;
}
}
| 2,428 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantilescommon/GenericInequalitySearchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantilescommon;
import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.find;
import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality.EQ;
import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality.GE;
import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality.GT;
import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality.LE;
import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality.LT;
import static org.testng.Assert.assertEquals;
import java.util.Comparator;
import java.util.Random;
import org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class GenericInequalitySearchTest {
static Random rand = new Random(1);
private static final String LS = System.getProperty("line.separator");
private static int randDelta() { return rand.nextDouble() < 0.4 ? 0 : 1; }
private final Comparator<Float> comparator = Comparator.naturalOrder();
//CodeQL may complain about boxed values, but Java Generics require objects.
private static Float[] buildRandFloatArr(final int len) {
final Float[] arr = new Float[len];
float v = 1.0f;
for (int i = 0; i < len; i++) {
arr[i] = v;
v += randDelta();
}
return arr;
}
// @Test //visual testing only
// //@SuppressWarnings("unused")
// private static void viewBuildRandArr() {
// final int len = 10;
// for (int i = 0; i < 10; i++) {
// final Float[] tarr = buildRandFloatArr(len);
// for (int j = 0; j < len; j++) {
// printf("%4.1f,", tarr[j]);
// }
// println("");
// }
// }
@Test
public void checkBinSearchFltLimits() {
for (int len = 10; len <= 13; len++) {
final Float[] tarr = buildRandFloatArr(len);
final int low = 2;
final int high = len - 2;
println(listFltArray(tarr, low, high));
checkBinarySearchFloatLimits(tarr, low, high);
}
}
private static String listFltArray(final Float[] arr, final int low, final int high) {
final StringBuilder sb = new StringBuilder();
sb.append(LS);
sb.append("The values in parentheses are the low and high values of the sub-array to search");
sb.append(LS);
sb.append("arr: ");
for (int i = 0; i < arr.length; i++) {
if (i == low || i == high) { sb.append(String.format("(%.0f) ", arr[i])); }
else { sb.append(String.format("%.0f ", arr[i])); }
}
return sb.toString();
}
private void checkBinarySearchFloatLimits(final Float[] arr, final int low, final int high) {
final Float lowV = arr[low];
final Float highV = arr[high];
Float v;
int res;
v = lowV - 1f;
res = find(arr, low, high, v, LT, comparator);
println(desc(arr, low, high, v, res, LT, comparator));
assertEquals(res, -1);
v = lowV;
res = find(arr, low, high, v, LT, comparator);
println(desc(arr, low, high, v, res, LT, comparator));
assertEquals(res, -1);
v = highV + 1;
res = find(arr, low, high, v, LT, comparator);
println(desc(arr, low, high, v, res, LT, comparator));
assertEquals(res, high);
v = lowV -1;
res = find(arr, low, high, v, LE, comparator);
println(desc(arr, low, high, v, res, LE, comparator));
assertEquals(res, -1);
v = highV;
res = find(arr, low, high, v, LE, comparator);
println(desc(arr, low, high, v, res, LE, comparator));
assertEquals(res, high);
v = highV + 1;
res = find(arr, low, high, v, LE, comparator);
println(desc(arr, low, high, v, res, LE, comparator));
assertEquals(res, high);
v = lowV - 1;
res = find(arr, low, high, v, EQ, comparator);
println(desc(arr, low, high, v, res, EQ, comparator));
assertEquals(res, -1);
v = highV;
res = find(arr, low, high, v, EQ, comparator);
println(desc(arr, low, high, v, res, EQ, comparator));
assertEquals(arr[res], v);
v = highV + 1;
res = find(arr, low, high, v, EQ, comparator);
println(desc(arr, low, high, v, res, EQ, comparator));
assertEquals(res, -1);
v = lowV - 1;
res = find(arr, low, high, v, GT, comparator);
println(desc(arr, low, high, v, res, GT, comparator));
assertEquals(res, low);
v = highV;
res = find(arr, low, high, v, GT, comparator);
println(desc(arr, low, high, v, res, GT, comparator));
assertEquals(res, -1);
v = highV + 1;
res = find(arr, low, high, v, GT, comparator);
println(desc(arr, low, high, v, res, GT, comparator));
assertEquals(res, -1);
v = lowV - 1;
res = find(arr, low, high, v, GE, comparator);
println(desc(arr, low, high, v, res, GE, comparator));
assertEquals(res, low);
v = lowV;
res = find(arr, low, high, v, GE, comparator);
println(desc(arr, low, high, v, res, GE, comparator));
assertEquals(res, low);
v = highV + 1;
res = find(arr, low, high, v, GE, comparator);
println(desc(arr, low, high, v, res, GE, comparator));
assertEquals(res, -1);
}
@Test // visual only
public void exerciseFltBinSearch() {
checkFindFloat(LT);
checkFindFloat(LE);
checkFindFloat(GE);
checkFindFloat(GT);
}
private void checkFindFloat(final GenericInequalitySearch.Inequality inequality) {
final String ie = inequality.name();
println("Inequality: " + ie);
// 0 1 2 3 4 5 6 7 8 9
final Float[] arr = {5f,5f,5f,6f,6f,6f,7f,8f,8f,8f};
final int len = arr.length;
print("Index: ");
for (int i = 0; i < len; i++) { printf("%d, ", i); }
print(LS + "Value: ");
for (int i = 0; i < len; i++) { printf("%.1f, ", arr[i]); }
println("");
for (float v = 0.5f; v <= arr[len - 1] + 0.5f; v += .5f) {
final int low = 0;
final int high = len - 1;
final int idx = find(arr, low, high, v, inequality, comparator);
if (idx == -1) {
println(ie +": " + v + " Not resolved, return -1.");
}
else {
println(desc(arr, low, high, v, idx, inequality, comparator));
}
}
println("");
}
/**
* Optional call that describes the details of the results of the search.
* Used primarily for debugging.
* @param arr The underlying sorted array of generic values
* @param low the low index of the range
* @param high the high index of the range
* @param v the generic value to search for
* @param idx the resolved index from the search
* @param inequality one of LT, LE, EQ, GE, GT.
* @param comparator for the type T
* @param <T> The generic type of value to be used in the search process.
* @return the descriptive string.
*/
public static <T> String desc(final T[] arr, final int low, final int high, final T v, final int idx,
final Inequality inequality, final Comparator<T> comparator) {
switch (inequality) {
case LT: {
if (idx == -1) {
return "LT: " + v + " <= arr[" + low + "]=" + arr[low] + "; return -1";
}
if (idx == high) {
return "LT: " + v + " > arr[" + high + "]=" + arr[high]
+ "; return arr[" + high + "]=" + arr[high];
} //idx < high
return "LT: " + v
+ ": arr[" + idx + "]=" + arr[idx] + " < " + v
+ " <= arr[" + (idx + 1) + "]=" + arr[idx + 1]
+ "; return arr[" + idx + "]=" + arr[idx];
}
case LE: {
if (idx == -1) {
return "LE: " + v + " < arr[" + low + "]=" + arr[low] + "; return -1";
}
if (idx == high) {
return "LE: " + v + " >= arr[" + high + "]=" + arr[high]
+ "; return arr[" + high + "]=" + arr[high];
}
return "LE: " + v
+ ": arr[" + idx + "]=" + arr[idx] + " <= " + v
+ " < arr[" + (idx + 1) + "]=" + arr[idx + 1]
+ "; return arr[" + idx + "]=" + arr[idx];
}
case EQ: {
if (idx == -1) {
if (comparator.compare(v, arr[high]) > 0) {
return "EQ: " + v + " > arr[" + high + "]; return -1";
}
if (comparator.compare(v, arr[low]) < 0) {
return "EQ: " + v + " < arr[" + low + "]; return -1";
}
return "EQ: " + v + " Cannot be found within arr[" + low + "], arr[" + high + "]; return -1";
}
return "EQ: " + v + " == arr[" + idx + "]; return arr[" + idx + "]=" + arr[idx];
}
case GE: {
if (idx == -1) {
return "GE: " + v + " > arr[" + high + "]=" + arr[high] + "; return -1";
}
if (idx == low) {
return "GE: " + v + " <= arr[" + low + "]=" + arr[low]
+ "; return arr[" + low + "]=" + arr[low];
} //idx > low
return "GE: " + v
+ ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " < " + v + " <= arr[" + idx + "]=" + arr[idx]
+ "; return arr[" + idx + "]=" + arr[idx];
}
case GT: {
if (idx == -1) {
return "GT: " + v + " >= arr[" + high + "]=" + arr[high] + "; return -1";
}
if (idx == low) {
return "GT: " + v + " < arr[" + low + "]=" + arr[low]
+ "; return arr[" + low + "]=" + arr[low];
} //idx > low
return "GT: " + v
+ ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " <= " + v + " < arr[" + idx + "]=" + arr[idx]
+ "; return arr[" + idx + "]=" + arr[idx];
}
}
return "";
}
private final static boolean enablePrinting = false;
/**
* @param format the format
* @param args the args
*/
static final void printf(final String format, final Object ...args) {
if (enablePrinting) { System.out.printf(format, args); }
}
/**
* @param o the Object to println
*/
static final void println(final Object o) {
if (enablePrinting) { System.out.println(o.toString()); }
}
/**
* @param o the Object to print
*/
static final void print(final Object o) {
if (enablePrinting) { System.out.print(o.toString()); }
}
}
| 2,429 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantilescommon/CrossCheckQuantilesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantilescommon;
import static org.apache.datasketches.common.Util.intToFixedLengthString;
import static org.apache.datasketches.common.Util.LS;
import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueDoubleQuantile;
import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueDoubleRank;
import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueFloatQuantile;
import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueFloatRank;
import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueItemQuantile;
import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueItemRank;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE;
import static org.apache.datasketches.quantilescommon.ReflectUtilityTest.CLASSIC_DOUBLES_SV_CTOR;
import static org.apache.datasketches.quantilescommon.ReflectUtilityTest.KLL_DOUBLES_SV_CTOR;
import static org.apache.datasketches.quantilescommon.ReflectUtilityTest.KLL_FLOATS_SV_CTOR;
import static org.apache.datasketches.quantilescommon.ReflectUtilityTest.REQ_SV_CTOR;
import static org.testng.Assert.assertEquals;
import java.util.Comparator;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.kll.KllDoublesSketch;
import org.apache.datasketches.kll.KllDoublesSketchSortedView;
import org.apache.datasketches.kll.KllFloatsSketch;
import org.apache.datasketches.kll.KllFloatsSketchSortedView;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.kll.KllItemsSketchSortedViewString;
import org.apache.datasketches.quantiles.DoublesSketch;
import org.apache.datasketches.quantiles.DoublesSketchSortedView;
import org.apache.datasketches.quantiles.ItemsSketch;
import org.apache.datasketches.quantiles.ItemsSketchSortedViewString;
import org.apache.datasketches.quantiles.UpdateDoublesSketch;
import org.apache.datasketches.req.ReqSketch;
import org.apache.datasketches.req.ReqSketchSortedView;
import org.testng.annotations.Test;
/**
* This test suite runs a common set of tests against all of the quantiles-type sketches in the library.
* Although the unit tests for each of the sketches is quite extensive, the purpose of this test is to make
* sure that key corner cases are in fact handled the same way by all of the sketches.
*
* <p>These tests are not about estimation accuracy, per se, as each of the different quantile sketches have very
* different algorithms for selecting the data to be retained in the sketch and thus will have very different error
* properties. These tests are primarily interested in making sure that the internal search and comparison algorithms
* used within the sketches are producing the correct results for exact queries based on a chosen search
* criteria. The search criteria are selected from the enum {@link QuantileSearchCriteria}. The corner cases of
* interest here are to make sure that each of the search criteria behave correctly for the following.</p>
* <ul>
* <li>A sketch with a single value.</li>
* <li>A sketch with two identical values<li>
* <li>A sketch with multiple duplicates and where the duplicates have weights greater than one.
* Note that the case with weights greater than one is only tested via the Sorted Views. The data loaded into the
* sketches will all have weights of one.</li>
* </ul>
*
* @author Lee Rhodes
*/
public class CrossCheckQuantilesTest {
private ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
private final String minItem = "10";
private final Comparator<String> comparator = Comparator.naturalOrder();
private final static int k = 32; //all sketches are in exact mode
//These test sets are specifically designed for the corner cases mentioned in the class javadoc.
// Please don't mess with them unless you know what you are doing.
//These sets must start with 10 and be multiples of 10.
final float[][] svFValues =
{
{10}, //set 0
{10,10}, //set 1
{10,20,30,40}, //set 2
{10,20,20,30,30,30,40,50}, //set 3
{10,10,20,20,30,30,40,40} //set 4
};
final double[][] svDValues =
{
{10},
{10,10},
{10,20,30,40},
{10,20,20,30,30,30,40,50},
{10,10,20,20,30,30,40,40}
};
final String[][] svIValues =
{
{"10"},
{"10","10"},
{"10","20","30","40"},
{"10","20","20","30","30","30","40","50"},
{"10","10","20","20","30","30","40","40"}
};
//these are value weights and will be converted to cumulative.
final long[][] svWeights =
{
{1},
{1,1},
{2,2,2,2},
{2,2,2,2,2,2,2,2},
{2,1,2,1,2,1,2,1}
};
int numSets;
long[][] svCumWeights;
long[] totalN;
float[][] skFStreamValues;
double[][] skDStreamValues;
String[][] skIStreamValues;
ReqSketch reqFloatsSk = null;
KllFloatsSketch kllFloatsSk = null;
KllDoublesSketch kllDoublesSk = null;
UpdateDoublesSketch classicDoublesSk = null;
KllItemsSketch<String> kllItemsSk = null;
ItemsSketch<String> itemsSk = null;
ReqSketchSortedView reqFloatsSV = null;
KllFloatsSketchSortedView kllFloatsSV = null;
KllDoublesSketchSortedView kllDoublesSV = null;
DoublesSketchSortedView classicDoublesSV = null;
KllItemsSketchSortedViewString kllItemsSV = null;
ItemsSketchSortedViewString itemsSV = null;
public CrossCheckQuantilesTest() {}
@Test
public void runTests() throws Exception {
buildDataSets();
for (int set = 0; set < numSets; set++) {
buildSVs(set);
buildSketches(set);
println("");
println("TEST getRank, Set " + set + ", all Criteria, across all sketches and their Sorted Views:");
checkGetRank(set, INCLUSIVE);
checkGetRank(set, EXCLUSIVE);
println("");
println("TEST getQuantile, Set " + set + ", all Criteria, across all sketches and their Sorted Views:");
checkGetQuantile(set, INCLUSIVE);
checkGetQuantile(set, EXCLUSIVE);
}
}
private void checkGetRank(int set, QuantileSearchCriteria crit) {
double trueRank;
double testRank;
println(LS + "FLOATS getRank Test SV vs Sk");
float maxFloatvalue = getMaxFloatValue(set);
for (float v = 5f; v <= maxFloatvalue + 5f; v += 5f) {
trueRank = getTrueFloatRank(svCumWeights[set], svFValues[set],v, crit);
testRank = reqFloatsSV.getRank(v, crit);
assertEquals(testRank, trueRank);
testRank = reqFloatsSk.getRank(v, crit);
assertEquals(testRank, trueRank);
testRank = kllFloatsSV.getRank(v, crit);
assertEquals(testRank, trueRank);
testRank = kllFloatsSk.getRank(v, crit);
assertEquals(testRank, trueRank);
println("Floats set: " + set + ", value: " + v + ", rank: " + trueRank + ", crit: " + crit.toString());
}
println(LS + "DOUBLES getRank Test SV vs Sk");
double maxDoubleValue = getMaxDoubleValue(set);
for (double v = 5; v <= maxDoubleValue + 5; v += 5) {
trueRank = getTrueDoubleRank(svCumWeights[set], svDValues[set],v, crit);
testRank = kllDoublesSV.getRank(v, crit);
assertEquals(testRank, trueRank);
testRank = kllDoublesSk.getRank(v, crit);
assertEquals(testRank, trueRank);
testRank = classicDoublesSV.getRank(v, crit);
assertEquals(testRank, trueRank);
testRank = classicDoublesSk.getRank(v, crit);
assertEquals(testRank, trueRank);
println("Doubles set: " + set + ", value: " + v + ", rank: " + trueRank + ", crit: " + crit.toString());
}
println(LS + "ITEMS getRank Test SV vs Sk");
int maxItemValue;
try { maxItemValue = Integer.parseInt(getMaxItemValue(set)); }
catch (NumberFormatException e) { throw new SketchesArgumentException(e.toString()); }
for (int v = 5; v <= maxItemValue + 5; v += 5) {
String s = intToFixedLengthString(v, 2);
trueRank = getTrueItemRank(svCumWeights[set], svIValues[set], s, crit, comparator);
testRank = kllItemsSV.getRank(s, crit);
assertEquals(testRank, trueRank);
testRank = kllItemsSk.getRank(s, crit);
assertEquals(testRank, trueRank);
testRank = itemsSV.getRank(s, crit);
assertEquals(testRank, trueRank);
testRank = itemsSk.getRank(s, crit);
assertEquals(testRank, trueRank);
println("Items set: " + set + ", value: " + s + ", rank: " + trueRank + ", crit: " + crit.toString());
}
}
private void checkGetQuantile(int set, QuantileSearchCriteria crit) {
int twoN = (int)totalN[set] * 2;
double dTwoN = twoN;
float trueFQ;
float testFQ;
println(LS + "FLOATS getQuantile Test SV vs Sk");
for (int i = 0; i <= twoN; i++) {
double normRank = i / dTwoN;
trueFQ = getTrueFloatQuantile(svCumWeights[set], svFValues[set], normRank, crit);
testFQ = reqFloatsSV.getQuantile(normRank, crit);
assertEquals(testFQ, trueFQ);
testFQ = reqFloatsSk.getQuantile(normRank, crit);
assertEquals(testFQ, trueFQ);
testFQ = kllFloatsSV.getQuantile(normRank, crit);
assertEquals(testFQ, trueFQ);
testFQ = kllFloatsSk.getQuantile(normRank, crit);
assertEquals(testFQ, trueFQ);
println("Floats set: " + set + ", rank: " + normRank + ", Q: " + trueFQ + ", crit: " + crit.toString());
}
println(LS + "DOUBLES getQuantile Test SV vs Sk");
double trueDQ;
double testDQ;
for (int i = 0; i <= twoN; i++) {
double normRank = i / dTwoN;
trueDQ = getTrueDoubleQuantile(svCumWeights[set], svDValues[set], normRank, crit);
testDQ = kllDoublesSV.getQuantile(normRank, crit);
assertEquals(testDQ, trueDQ);
testDQ = kllDoublesSk.getQuantile(normRank, crit);
assertEquals(testDQ, trueDQ);
testDQ = classicDoublesSV.getQuantile(normRank, crit);
assertEquals(testDQ, trueDQ);
testDQ = classicDoublesSk.getQuantile(normRank, crit);
assertEquals(testDQ, trueDQ);
println("Doubles set: " + set + ", rank: " + normRank + ", Q: " + trueDQ + ", crit: " + crit.toString());
}
println(LS + "ITEMS getQuantile Test SV vs Sk");
String trueIQ;
String testIQ;
for (int i = 0; i <= twoN; i++) {
double normRank = i / dTwoN;
trueIQ = getTrueItemQuantile(svCumWeights[set], svIValues[set], normRank, crit);
testIQ = kllItemsSV.getQuantile(normRank, crit);
assertEquals(testIQ, trueIQ);
testIQ = kllItemsSk.getQuantile(normRank, crit);
assertEquals(testIQ, trueIQ);
testIQ = itemsSV.getQuantile(normRank, crit);
assertEquals(testIQ, trueIQ);
testIQ = itemsSk.getQuantile(normRank, crit);
assertEquals(testIQ, trueIQ);
println("Items set: " + set + ", rank: " + normRank + ", Q: " + trueIQ + ", crit: " + crit.toString());
}
}
private double getMaxDoubleValue(int set) {
int streamLen = skDStreamValues[set].length;
return skDStreamValues[set][streamLen -1];
}
private float getMaxFloatValue(int set) {
int streamLen = skFStreamValues[set].length;
return skFStreamValues[set][streamLen -1];
}
private String getMaxItemValue(int set) {
int streamLen = skIStreamValues[set].length;
return skIStreamValues[set][streamLen -1];
}
/*******BUILD & LOAD SKETCHES***********/
private void buildSketches(int set) {
reqFloatsSk = ReqSketch.builder().setK(k).build();
kllFloatsSk = KllFloatsSketch.newHeapInstance(k);
kllDoublesSk = KllDoublesSketch.newHeapInstance(k);
classicDoublesSk = DoublesSketch.builder().setK(k).build();
kllItemsSk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
itemsSk = ItemsSketch.getInstance(String.class, k, Comparator.naturalOrder());
int count = skFStreamValues[set].length;
for (int i = 0; i < count; i++) {
reqFloatsSk.update(skFStreamValues[set][i]);
kllFloatsSk.update(skFStreamValues[set][i]);
kllDoublesSk.update(skDStreamValues[set][i]);
classicDoublesSk.update(skDStreamValues[set][i]);
kllItemsSk.update(skIStreamValues[set][i]);
itemsSk.update(skIStreamValues[set][i]);
}
}
/*******BUILD & LOAD SVs***********/
private void buildSVs(int set) throws Exception {
reqFloatsSV = getRawReqSV(svFValues[set], svCumWeights[set], totalN[set]);
kllFloatsSV = getRawKllFloatsSV(svFValues[set], svCumWeights[set], totalN[set]);
kllDoublesSV = getRawKllDoublesSV(svDValues[set], svCumWeights[set], totalN[set]);
classicDoublesSV = getRawClassicDoublesSV(svDValues[set], svCumWeights[set], totalN[set]);
kllItemsSV = new KllItemsSketchSortedViewString(svIValues[set], svCumWeights[set], totalN[set], minItem, comparator);
itemsSV = new ItemsSketchSortedViewString(svIValues[set], svCumWeights[set], totalN[set], comparator);
}
private final static ReqSketchSortedView getRawReqSV(
final float[] values, final long[] cumWeights, final long totalN) throws Exception {
return (ReqSketchSortedView) REQ_SV_CTOR.newInstance(values, cumWeights, totalN);
}
private final static KllFloatsSketchSortedView getRawKllFloatsSV(
final float[] values, final long[] cumWeights, final long totalN) throws Exception {
return (KllFloatsSketchSortedView) KLL_FLOATS_SV_CTOR.newInstance(values, cumWeights, totalN);
}
private final static KllDoublesSketchSortedView getRawKllDoublesSV(
final double[] values, final long[] cumWeights, final long totalN) throws Exception {
return (KllDoublesSketchSortedView) KLL_DOUBLES_SV_CTOR.newInstance(values, cumWeights, totalN);
}
private final static DoublesSketchSortedView getRawClassicDoublesSV(
final double[] values, final long[] cumWeights, final long totalN) throws Exception {
return (DoublesSketchSortedView) CLASSIC_DOUBLES_SV_CTOR.newInstance(values, cumWeights, totalN);
}
/********BUILD DATA SETS**********/
private void buildDataSets() {
numSets = svWeights.length;
svCumWeights = new long[numSets][];
totalN = new long[numSets];
skFStreamValues = new float[numSets][];
skDStreamValues = new double[numSets][];
skIStreamValues = new String[numSets][];
for (int i = 0; i < numSets; i++) {
svCumWeights[i] = convertToCumWeights(svWeights[i]);
int len = svCumWeights[i].length;
int totalCount = (int)svCumWeights[i][len -1];
totalN[i] = totalCount;
skFStreamValues[i] = convertToFloatStream(svFValues[i], svWeights[i], totalCount);
skDStreamValues[i] = convertToDoubleStream(svDValues[i], svWeights[i], totalCount);
skIStreamValues[i] = convertToItemStream(svIValues[i], svWeights[i], totalCount);
}
println("");
}
private static float[] convertToFloatStream(
final float[] svFValueArr,
final long[] svWeightsArr,
final int totalCount) {
float[] out = new float[totalCount];
int len = svWeightsArr.length;
int i = 0;
for (int j = 0; j < len; j++) {
float f = svFValueArr[j];
int wt = (int)svWeightsArr[j];
for (int w = 0; w < wt; w++) {
out[i++] = f;
}
}
return out;
}
private static double[] convertToDoubleStream(
final double[] svDValueArr,
final long[] svWeightsArr,
final int totalCount) {
double[] out = new double[totalCount];
int len = svWeightsArr.length;
int i = 0;
for (int j = 0; j < len; j++) {
double d = svDValueArr[j];
int wt = (int)svWeightsArr[j];
for (int w = 0; w < wt; w++) {
out[i++] = d;
}
}
return out;
}
private static String[] convertToItemStream(
final String[] svIValueArr,
final long[] svWeightsArr,
final int totalCount) {
String[] out = new String[totalCount];
int len = svWeightsArr.length;
int i = 0;
for (int j = 0; j < len; j++) {
String s = svIValueArr[j];
int wt = (int)svWeightsArr[j];
for (int w = 0; w < wt; w++) {
out[i++] = s;
}
}
return out;
}
private static long[] convertToCumWeights(final long[] weights) {
final int len = weights.length;
final long[] out = new long[len];
out[0] = weights[0];
for (int i = 1; i < len; i++) {
out[i] = weights[i] + out[i - 1];
}
return out;
}
/*******************/
private final static boolean enablePrinting = false;
/**
* @param o the Object to println
*/
private static final void println(final Object o) {
if (enablePrinting) { System.out.println(o.toString()); }
}
}
| 2,430 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantilescommon/ReflectUtilityTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantilescommon;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.*;
import static org.testng.Assert.assertEquals;
import org.apache.datasketches.req.ReqSketchSortedView;
import org.testng.annotations.Test;
public final class ReflectUtilityTest {
private ReflectUtilityTest() {}
static final Class<?> REQ_SV;
static final Class<?> KLL_FLOATS_SV;
static final Class<?> KLL_DOUBLES_SV;
static final Class<?> CLASSIC_DOUBLES_SV;
static final Constructor<?> REQ_SV_CTOR;
static final Constructor<?> KLL_FLOATS_SV_CTOR;
static final Constructor<?> KLL_DOUBLES_SV_CTOR;
static final Constructor<?> CLASSIC_DOUBLES_SV_CTOR;
static {
REQ_SV = getClass("org.apache.datasketches.req.ReqSketchSortedView");
KLL_FLOATS_SV = getClass("org.apache.datasketches.kll.KllFloatsSketchSortedView");
KLL_DOUBLES_SV = getClass("org.apache.datasketches.kll.KllDoublesSketchSortedView");
CLASSIC_DOUBLES_SV = getClass("org.apache.datasketches.quantiles.DoublesSketchSortedView");
REQ_SV_CTOR = getConstructor(REQ_SV, float[].class, long[].class, long.class);
KLL_FLOATS_SV_CTOR = getConstructor(KLL_FLOATS_SV, float[].class, long[].class, long.class);
KLL_DOUBLES_SV_CTOR = getConstructor(KLL_DOUBLES_SV, double[].class, long[].class, long.class);
CLASSIC_DOUBLES_SV_CTOR = getConstructor(CLASSIC_DOUBLES_SV, double[].class, long[].class, long.class);
}
@Test //Example
public static void checkCtr() throws Exception {
float[] farr = { 10, 20, 30 };
long[] larr = { 1, 2, 3 };
long n = 3;
ReqSketchSortedView reqSV =
(ReqSketchSortedView) REQ_SV_CTOR.newInstance(farr, larr, n);
float q = reqSV.getQuantile(1.0, INCLUSIVE);
assertEquals(q, 30f);
}
/**
* Gets a Class reference to the given class loaded by the SystemClassLoader.
* This will work for private, package-private and abstract classes.
* @param fullyQualifiedBinaryName the binary name is the name of the class file on disk. This does not instantiate
* a concrete class, but allows access to constructors, static fields and static methods.
* @return the Class object of the given class.
*/
public static Class<?> getClass(final String fullyQualifiedBinaryName) {
try {
final ClassLoader scl = ClassLoader.getSystemClassLoader();
return scl.loadClass(fullyQualifiedBinaryName);
} catch (final ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* Gets a declared constructor given the owner class and parameter types
* @param ownerClass the Class object of the class loaded by the SystemClassLoader.
* @param parameterTypes parameter types for the constructor
* @return the constructor
*/
public static Constructor<?> getConstructor(final Class<?> ownerClass, final Class<?>... parameterTypes ) {
try {
final Constructor<?> ctor = ownerClass.getDeclaredConstructor(parameterTypes);
ctor.setAccessible(true);
return ctor;
} catch (final NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e);
}
}
/**
* Gets a class instance from its constructor and initializing arguments.
* @param constructor the given Constructor
* @param initargs the initializing arguments
* @return the instantiated class.
*/
public static Object getInstance(final Constructor<?> constructor, final Object... initargs) {
try {
constructor.setAccessible(true);
return constructor.newInstance(initargs);
} catch (final InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | SecurityException e) {
throw new RuntimeException(e);
}
}
/**
* Gets a declared field of the given the loaded owner class and field name. The accessible flag will be set true.
* @param ownerClass the Class object of the class loaded by the SystemClassLoader.
* @param fieldName the desired field name
* @return the desired field.
*/
public static Field getField(final Class<?> ownerClass, final String fieldName) {
try {
final Field field = ownerClass.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (final NoSuchFieldException | SecurityException e) {
throw new RuntimeException(e);
}
}
/**
* Gets a field value given the loaded owner class and the Field. The accessible flag will be set true.
* @param ownerClass the loaded class owning the field
* @param field The Field object
* @return the returned value as an object.
*/
public static Object getFieldValue(final Class<?> ownerClass, final Field field) {
try {
field.setAccessible(true);
return field.get(ownerClass);
} catch (final IllegalAccessException | SecurityException | IllegalArgumentException e) {
throw new RuntimeException(e);
}
}
/**
* Gets a declared method of the given the loaded owning class, method name and parameter types.
* The accessible flag will be set true.
* @param ownerClass the given
* @param methodName the given method name
* @param parameterTypes the list of parameter types
* @return the desired method.
*/
public static Method getMethod(
final Class<?> ownerClass, final String methodName, final Class<?>... parameterTypes ) {
try {
final Method method = (parameterTypes == null)
? ownerClass.getDeclaredMethod(methodName)
: ownerClass.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return method;
} catch (final NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e);
}
}
}
| 2,431 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantilescommon/InequalitySearchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantilescommon;
import static org.apache.datasketches.quantilescommon.InequalitySearch.EQ;
import static org.apache.datasketches.quantilescommon.InequalitySearch.GE;
import static org.apache.datasketches.quantilescommon.InequalitySearch.GT;
import static org.apache.datasketches.quantilescommon.InequalitySearch.LE;
import static org.apache.datasketches.quantilescommon.InequalitySearch.LT;
import static org.testng.Assert.assertEquals;
import java.util.Random;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class InequalitySearchTest {
static Random rand = new Random(1);
private static final String LS = System.getProperty("line.separator");
private static int randDelta() { return rand.nextDouble() < 0.4 ? 0 : 1; }
private static float[] buildRandFloatArr(final int len) {
final float[] arr = new float[len];
float v = 1.0f;
for (int i = 0; i < len; i++) {
arr[i] = v;
v += randDelta();
}
return arr;
}
private static double[] buildRandDoubleArr(final int len) {
final double[] arr = new double[len];
double v = 1.0;
for (int i = 0; i < len; i++) {
arr[i] = v;
v += randDelta();
}
return arr;
}
private static long[] buildRandLongArr(final int len) {
final long[] arr = new long[len];
long v = 1L;
for (int i = 0; i < len; i++) {
arr[i] = v;
v += 2L * randDelta();
}
return arr;
}
//double array
@Test
public void checkBinSearchDblLimits() {
for (int len = 10; len <= 13; len++) {
final double[] tarr = buildRandDoubleArr(len);
final int low = 2;
final int high = len - 2;
println(listDblArray(tarr, low, high));
checkBinarySearchDoubleLimits(tarr, low, high);
}
}
private static String listDblArray(final double[] arr, final int low, final int high) {
final StringBuilder sb = new StringBuilder();
sb.append(LS);
final int len = arr.length;
sb.append("double[" + len + "]: ");
for (int i = 0; i < len; i++) {
if (i == low || i == high) { sb.append(String.format("(%.0f) ", arr[i])); }
else { sb.append(String.format("%.0f ", arr[i])); }
}
return sb.toString();
}
private static void checkBinarySearchDoubleLimits(final double[] arr, final int low, final int high) {
final double lowV = arr[low];
final double highV = arr[high];
double v;
int res;
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, LT);
println(LT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = lowV;
res = InequalitySearch.find(arr, low, high, v, LT);
println(LT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, LT);
println(LT.desc(arr, low, high, v, res));
assertEquals(res, high);
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, LE);
println(LE.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV;
res = InequalitySearch.find(arr, low, high, v, LE);
println(LE.desc(arr, low, high, v, res));
assertEquals(res, high);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, LE);
println(LE.desc(arr, low, high, v, res));
assertEquals(res, high);
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, EQ);
println(EQ.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV;
res = InequalitySearch.find(arr, low, high, v, EQ);
println(EQ.desc(arr, low, high, v, res));
assertEquals(arr[res], v);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, EQ);
println(EQ.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, GT);
println(GT.desc(arr, low, high, v, res));
assertEquals(res, low);
v = highV;
res = InequalitySearch.find(arr, low, high, v, GT);
println(GT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, GT);
println(GT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, GE);
println(GE.desc(arr, low, high, v, res));
assertEquals(res, low);
v = lowV;
res = InequalitySearch.find(arr, low, high, v, GE);
println(GE.desc(arr, low, high, v, res));
assertEquals(res, low);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, GE);
println(GE.desc(arr, low, high, v, res));
assertEquals(res, -1);
}
//float array
@Test
public void checkBinSearchFltLimits() {
for (int len = 10; len <= 13; len++) {
final float[] tarr = buildRandFloatArr(len);
final int low = 2;
final int high = len - 2;
println(listFltArray(tarr, low, high));
checkBinarySearchFloatLimits(tarr, low, high);
}
}
private static String listFltArray(final float[] arr, final int low, final int high) {
final StringBuilder sb = new StringBuilder();
sb.append(LS);
final int len = arr.length;
sb.append("float[" + len + "]: ");
for (int i = 0; i < len; i++) {
if (i == low || i == high) { sb.append(String.format("(%.0f) ", arr[i])); }
else { sb.append(String.format("%.0f ", arr[i])); }
}
return sb.toString();
}
private static void checkBinarySearchFloatLimits(final float[] arr, final int low, final int high) {
final float lowV = arr[low];
final float highV = arr[high];
float v;
int res;
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, LT);
println(LT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = lowV;
res = InequalitySearch.find(arr, low, high, v, LT);
println(LT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, LT);
println(LT.desc(arr, low, high, v, res));
assertEquals(res, high);
v = lowV -1;
res = InequalitySearch.find(arr, low, high, v, LE);
println(LE.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV;
res = InequalitySearch.find(arr, low, high, v, LE);
println(LE.desc(arr, low, high, v, res));
assertEquals(res, high);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, LE);
println(LE.desc(arr, low, high, v, res));
assertEquals(res, high);
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, EQ);
println(EQ.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV;
res = InequalitySearch.find(arr, low, high, v, EQ);
println(EQ.desc(arr, low, high, v, res));
assertEquals(arr[res], v);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, EQ);
println(EQ.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, GT);
println(GT.desc(arr, low, high, v, res));
assertEquals(res, low);
v = highV;
res = InequalitySearch.find(arr, low, high, v, GT);
println(GT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, GT);
println(GT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, GE);
println(GE.desc(arr, low, high, v, res));
assertEquals(res, low);
v = lowV;
res = InequalitySearch.find(arr, low, high, v, GE);
println(GE.desc(arr, low, high, v, res));
assertEquals(res, low);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, GE);
println(GE.desc(arr, low, high, v, res));
assertEquals(res, -1);
}
//long array
@Test
public void checkBinSearchLongLimits() {
for (int len = 10; len <= 13; len++) {
final long[] tarr = buildRandLongArr(len);
final int low = 2;
final int high = len - 2;
println(listLongArray(tarr, low, high));
checkBinarySearchLongLimits(tarr, low, high);
}
}
private static String listLongArray(final long[] arr, final int low, final int high) {
final StringBuilder sb = new StringBuilder();
sb.append(LS);
final int len = arr.length;
sb.append("long[" + len + "]: ");
for (int i = 0; i < len; i++) {
if (i == low || i == high) { sb.append(String.format("(%d) ", arr[i])); }
else { sb.append(String.format("%d ", arr[i])); }
}
return sb.toString();
}
private static void checkBinarySearchLongLimits(final long[] arr, final int low, final int high) {
final long lowV = arr[low];
final long highV = arr[high];
long v;
int res;
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, LT);
println(LT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = lowV;
res = InequalitySearch.find(arr, low, high, v, LT);
println(LT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, LT);
println(LT.desc(arr, low, high, v, res));
assertEquals(res, high);
v = lowV -1;
res = InequalitySearch.find(arr, low, high, v, LE);
println(LE.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV;
res = InequalitySearch.find(arr, low, high, v, LE);
println(LE.desc(arr, low, high, v, res));
assertEquals(res, high);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, LE);
println(LE.desc(arr, low, high, v, res));
assertEquals(res, high);
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, EQ);
println(EQ.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV;
res = InequalitySearch.find(arr, low, high, v, EQ);
println(EQ.desc(arr, low, high, v, res));
assertEquals(arr[res], v);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, EQ);
println(EQ.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, GT);
println(GT.desc(arr, low, high, v, res));
assertEquals(res, low);
v = highV;
res = InequalitySearch.find(arr, low, high, v, GT);
println(GT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, GT);
println(GT.desc(arr, low, high, v, res));
assertEquals(res, -1);
v = lowV - 1;
res = InequalitySearch.find(arr, low, high, v, GE);
println(GE.desc(arr, low, high, v, res));
assertEquals(res, low);
v = lowV;
res = InequalitySearch.find(arr, low, high, v, GE);
println(GE.desc(arr, low, high, v, res));
assertEquals(res, low);
v = highV + 1;
res = InequalitySearch.find(arr, low, high, v, GE);
println(GE.desc(arr, low, high, v, res));
assertEquals(res, -1);
}
/****************/
@Test // visual only for doubles inequality
public void exerciseDoublesSearch() {
println("--------{1f}--------");
double[] arr = {1};
exerciseDoubles(arr);
println("------{1f, 1f}------");
arr = new double[] {1f, 1f};
exerciseDoubles(arr);
println("---------{1,1,1,2,2,2,3,4,4,4}--------");
// 0 1 2 3 4 5 6 7 8 9
arr = new double[] {1,1,1,2,2,2,3,4,4,4};
exerciseDoubles(arr);
}
private static void exerciseDoubles(final double[] arr) {
checkFindDouble(arr, LT);
checkFindDouble(arr, LE);
checkFindDouble(arr, EQ);
checkFindDouble(arr, GE);
checkFindDouble(arr, GT);
}
private static void checkFindDouble(final double[] arr, final InequalitySearch crit) {
println("InequalitySearch: " + crit.name());
final int len = arr.length;
for (double v = 0.5; v <= arr[len - 1] + 0.5; v += .5) {
final int low = 0;
final int high = len - 1;
final int idx = InequalitySearch.find(arr, low, high, v, crit);
println(crit.desc(arr, low, high, v, idx));
}
println("");
}
/****************/
@Test // visual only for floats inequality
public void exerciseFloatsSearch() {
println("--------{1f}--------");
float[] arr = {1f};
exerciseFloats(arr);
println("------{1f, 1f}------");
arr = new float[] {1f, 1f};
exerciseFloats(arr);
println("---------{1,1,1,2,2,2,3,4,4,4}--------");
// 0 1 2 3 4 5 6 7 8 9
arr = new float[] {1,1,1,2,2,2,3,4,4,4};
exerciseFloats(arr);
}
private static void exerciseFloats(final float[] arr) {
checkFindFloat(arr, LT);
checkFindFloat(arr, LE);
checkFindFloat(arr, EQ);
checkFindFloat(arr, GE);
checkFindFloat(arr, GT);
}
private static void checkFindFloat(final float[] arr, final InequalitySearch crit) {
println("InequalitySearch: " + crit.name());
final int len = arr.length;
for (float v = 0.5f; v <= arr[len - 1] + 0.5f; v += 0.5f) {
final int low = 0;
final int high = len - 1;
final int idx = InequalitySearch.find(arr, low, high, v, crit);
println(crit.desc(arr, low, high, v, idx));
}
println("");
}
/****************/
@Test // visual only for longs inequality
public void exerciseLongsSearch() {
println("--------{1}--------");
long[] arr = {1};
exerciseLongs(arr);
println("------{1, 1}------");
arr = new long[] {1, 1};
exerciseLongs(arr);
println("--------{1,1,1,2,2,2,3,4,4,4}--------");
// 0 1 2 3 4 5 6 7 8 9
arr = new long[] {1,1,1,2,2,2,3,4,4,4};
exerciseLongs(arr);
}
private static void exerciseLongs(final long[] arr) {
checkFindLong(arr, LT);
checkFindLong(arr, LE);
checkFindLong(arr, EQ);
checkFindLong(arr, GE);
checkFindLong(arr, GT);
}
private static void checkFindLong(final long[] arr, final InequalitySearch crit) {
println("InequalitySearch: " + crit.name());
final int len = arr.length;
for (long v = 0L; v <= arr[len - 1] + 1L; v++) {
final int low = 0;
final int high = len - 1;
final int idx = InequalitySearch.find(arr, low, high, v, crit);
println(crit.desc(arr, low, high, v, idx));
}
println("");
}
/****************/
//test equality binary searches
@Test
public void checkSimpleFindFloat() {
final int len = 10;
final float[] arr = new float[len];
for (int i = 0; i < len; i++) { arr[i] = i; }
int idx;
for (int i = 0; i < len; i++) {
idx = BinarySearch.find(arr, 0, len - 1, i);
assertEquals(idx, i);
}
idx = BinarySearch.find(arr, 0, len - 1, -1);
assertEquals(idx, -1);
idx = BinarySearch.find(arr, 0, len - 1, len);
assertEquals(idx, -1);
}
@Test
public void checkSimpleFindDouble() {
final int len = 11;
final double[] arr = new double[len];
for (int i = 0; i < len; i++) { arr[i] = i; }
int idx;
for (int i = 0; i < len; i++) {
idx = BinarySearch.find(arr, 0, len - 1, i);
assertEquals(idx, i);
}
idx = BinarySearch.find(arr, 0, len - 1, -1);
assertEquals(idx, -1);
idx = BinarySearch.find(arr, 0, len - 1, len);
assertEquals(idx, -1);
}
@Test
public void checkSimpleFindLong() {
final int len = 11;
final long[] arr = new long[len];
for (int i = 0; i < len; i++) { arr[i] = i; }
int idx;
for (int i = 0; i < len; i++) {
idx = BinarySearch.find(arr, 0, len - 1, i);
assertEquals(idx, i);
}
idx = BinarySearch.find(arr, 0, len - 1, -1);
assertEquals(idx, -1);
idx = BinarySearch.find(arr, 0, len - 1, len);
assertEquals(idx, -1);
}
/****************/
@Test //visual testing only
//@SuppressWarnings("unused")
private static void checkBuildRandFloatArr() {
final int len = 10;
for (int i = 0; i < 10; i++) {
final float[] tarr = buildRandFloatArr(len);
for (int j = 0; j < len; j++) {
printf("%4.1f,", tarr[j]);
}
println("");
}
}
private final static boolean enablePrinting = false;
/**
* @param format the format
* @param args the args
*/
static final void printf(final String format, final Object ...args) {
if (enablePrinting) { System.out.printf(format, args); }
}
/**
* @param o the Object to println
*/
static final void println(final Object o) {
if (enablePrinting) { System.out.println(o.toString()); }
}
}
| 2,432 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantilescommon/QuantilesUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantilescommon;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.testng.annotations.Test;
public class QuantilesUtilTest {
@Test
public void checkEvenlySpacedRanks() {
double[] arr = QuantilesUtil.equallyWeightedRanks(2);
assertEquals(arr[1], 0.5);
arr = QuantilesUtil.equallyWeightedRanks(4);
assertEquals(arr[0], 0.0);
assertEquals(arr[1], 0.25);
assertEquals(arr[2], 0.5);
assertEquals(arr[3], 0.75);
assertEquals(arr[4], 1.0);
}
@Test
public void checkEvenlySpacedFloats() {
float[] arr = QuantilesUtil.evenlySpacedFloats(0, 1, 3);
assertEquals(arr[0], 0.0f);
assertEquals(arr[1], 0.5f);
assertEquals(arr[2], 1.0f);
arr = QuantilesUtil.evenlySpacedFloats(3, 7, 3);
assertEquals(arr[0], 3.0f);
assertEquals(arr[1], 5.0f);
assertEquals(arr[2], 7.0f);
arr = QuantilesUtil.evenlySpacedFloats(0f, 1.0f, 2);
assertEquals(arr[0], 0f);
assertEquals(arr[1], 1f);
try { QuantilesUtil.evenlySpacedFloats(0f, 1f, 1); fail(); } catch (SketchesArgumentException e) {}
}
@Test
public void checkEvenlySpacedDoubles() {
double[] arr = QuantilesUtil.evenlySpacedDoubles(0, 1, 3);
assertEquals(arr[0], 0.0);
assertEquals(arr[1], 0.5);
assertEquals(arr[2], 1.0);
arr = QuantilesUtil.evenlySpacedDoubles(3, 7, 3);
assertEquals(arr[0], 3.0);
assertEquals(arr[1], 5.0);
assertEquals(arr[2], 7.0);
arr = QuantilesUtil.evenlySpacedDoubles(0, 1.0, 2);
assertEquals(arr[0], 0);
assertEquals(arr[1], 1.0);
try { QuantilesUtil.evenlySpacedDoubles(0, 1.0, 1); fail(); } catch (SketchesArgumentException e) {}
}
@Test
public void checkEvenlyLogSpaced() {
final double[] arr = QuantilesUtil.evenlyLogSpaced(1, 8, 4);
assertEquals(arr[0], 1.0);
assertEquals(arr[1], 2.0);
assertEquals(arr[2], 4.0);
assertEquals(arr[3], 8.0);
try { QuantilesUtil.evenlyLogSpaced(-1.0, 1.0, 2); fail(); } catch (SketchesArgumentException e) {}
try { QuantilesUtil.evenlyLogSpaced(1.0, -1.0, 2); fail(); } catch (SketchesArgumentException e) {}
try { QuantilesUtil.evenlyLogSpaced(-1.0, -1.0, 2); fail(); } catch (SketchesArgumentException e) {}
try { QuantilesUtil.evenlyLogSpaced(1.0, 1.0, 1); fail(); } catch (SketchesArgumentException e) {}
}
}
| 2,433 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/CpcCompressionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.apache.datasketches.cpc.CompressionData.decodingTablesForHighEntropyByte;
import static org.apache.datasketches.cpc.CompressionData.encodingTablesForHighEntropyByte;
import static org.apache.datasketches.cpc.CompressionData.lengthLimitedUnaryDecodingTable65;
import static org.apache.datasketches.cpc.CompressionData.lengthLimitedUnaryEncodingTable65;
import static org.apache.datasketches.cpc.CpcCompression.BIT_BUF;
import static org.apache.datasketches.cpc.CpcCompression.BUF_BITS;
import static org.apache.datasketches.cpc.CpcCompression.NEXT_WORD_IDX;
import static org.apache.datasketches.cpc.CpcCompression.lowLevelCompressBytes;
import static org.apache.datasketches.cpc.CpcCompression.lowLevelCompressPairs;
import static org.apache.datasketches.cpc.CpcCompression.lowLevelUncompressBytes;
import static org.apache.datasketches.cpc.CpcCompression.lowLevelUncompressPairs;
import static org.apache.datasketches.cpc.CpcCompression.readUnary;
import static org.apache.datasketches.cpc.CpcCompression.writeUnary;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Arrays;
import java.util.Random;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class CpcCompressionTest {
@Test
public void checkWriteReadUnary() {
final int[] compressedWords = new int[256];
final long[] ptrArr = new long[3];
int nextWordIndex = 0; //must be int
long bitBuf = 0; //must be long
int bufBits = 0; //could be byte
for (int i = 0; i < 100; i++) {
//TODO Inline WriteUnary
ptrArr[NEXT_WORD_IDX] = nextWordIndex;
ptrArr[BIT_BUF] = bitBuf;
ptrArr[BUF_BITS] = bufBits;
assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; //catch sign extension error
writeUnary(compressedWords, ptrArr, i);
nextWordIndex = (int) ptrArr[NEXT_WORD_IDX];
bitBuf = ptrArr[BIT_BUF];
bufBits = (int) ptrArr[BUF_BITS];
assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; //catch truncation error
//END Inline WriteUnary
}
// Pad the bitstream so that the decompressor's 12-bit peek can't overrun its input.
final long padding = 7;
bufBits += (int)padding;
//MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex);
if (bufBits >= 32) {
compressedWords[nextWordIndex++] = (int) bitBuf;
bitBuf >>>= 32;
bufBits -= 32;
}
if (bufBits > 0) { // We are done encoding now, so we flush the bit buffer.
assert (bufBits < 32);
compressedWords[nextWordIndex++] = (int) bitBuf;
}
final int numWordsUsed = nextWordIndex;
println("Words used: " + numWordsUsed);
nextWordIndex = 0; //must be int
bitBuf = 0; //must be long
bufBits = 0; //could be byte
for (int i = 0; i < 100; i++) {
//TODO Inline ReadUnary
ptrArr[NEXT_WORD_IDX] = nextWordIndex;
ptrArr[BIT_BUF] = bitBuf;
ptrArr[BUF_BITS] = bufBits;
assert nextWordIndex == ptrArr[NEXT_WORD_IDX];
final long result = readUnary(compressedWords, ptrArr);
println("Result: " + result + ", expected: " + i);
assertEquals(result, i);
nextWordIndex = (int) ptrArr[NEXT_WORD_IDX];
bitBuf = ptrArr[BIT_BUF];
bufBits = (int) ptrArr[BUF_BITS];
assert nextWordIndex == ptrArr[NEXT_WORD_IDX];
//END Inline ReadUnary
}
assertTrue(nextWordIndex <= numWordsUsed);
}
@Test
public void checkWriteReadBytes() {
final int[] compressedWords = new int[128];
final byte[] byteArray = new byte[256];
final byte[] byteArray2 = new byte[256]; //output
for (int i = 0; i < 256; i++) { byteArray[i] = (byte) i; }
for (int j = 0; j < 22; j++) {
final long numWordsWritten = lowLevelCompressBytes(
byteArray, 256, encodingTablesForHighEntropyByte[j], compressedWords);
lowLevelUncompressBytes(byteArray2, 256, decodingTablesForHighEntropyByte[j],
compressedWords, numWordsWritten);
println("Words used: " + numWordsWritten);
assertEquals(byteArray2, byteArray);
}
}
@Test
public void checkWriteReadBytes65() {
final int size = 65;
final int[] compressedWords = new int[128];
final byte[] byteArray = new byte[size];
final byte[] byteArray2 = new byte[size]; //output
for (int i = 0; i < size; i++) { byteArray[i] = (byte) i; }
final long numWordsWritten = lowLevelCompressBytes(
byteArray, size, lengthLimitedUnaryEncodingTable65, compressedWords);
lowLevelUncompressBytes(byteArray2, size, lengthLimitedUnaryDecodingTable65,
compressedWords, numWordsWritten);
println("Words used: " + numWordsWritten);
assertEquals(byteArray2, byteArray);
}
@Test
public void checkWriteReadPairs() {
final Random rgen = new Random(1);
final int lgK = 14;
final int N = 3000;
final int MAX_WORDS = 4000;
final int[] pairArray = new int[N];
final int[] pairArray2 = new int[N];
int i;
for (i = 0; i < N; i++) {
final int rand = rgen.nextInt(1 << (lgK + 6));
pairArray[i] = rand;
}
Arrays.sort(pairArray); //must be unsigned sort! So keep lgK < 26
int prev = -1;
int nxt = 0;
for (i = 0; i < N; i++) { // uniquify
if (pairArray[i] != prev) {
prev = pairArray[i];
pairArray[nxt++] = pairArray[i];
}
}
final int numPairs = nxt;
println("numCsv = " + numPairs);
final int[] compressedWords = new int[MAX_WORDS];
int bb; // numBaseBits
for (bb = 0; bb <= 11; bb++) {
final long numWordsWritten =
lowLevelCompressPairs(pairArray, numPairs, bb, compressedWords);
println("numWordsWritten = " + numWordsWritten + ", bb = " + bb);
lowLevelUncompressPairs(pairArray2, numPairs, bb, compressedWords, numWordsWritten);
for (i = 0; i < numPairs; i++) {
assert (pairArray[i] == pairArray2[i]);
}
}
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,434 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/CompressedStateTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import java.io.PrintStream;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class CompressedStateTest {
static PrintStream ps = System.out;
long vIn = 0;
int lgK = 10;
private void updateStateUnion(final CpcSketch sk) {
Format skFmt = sk.getFormat();
CompressedState state = CompressedState.compress(sk);
Flavor f = state.getFlavor();
Format fmt = state.getFormat();
assertEquals(fmt, skFmt);
long c = state.numCoupons;
WritableMemory wmem = WritableMemory.allocate((int)state.getRequiredSerializedBytes());
state.exportToMemory(wmem);
printf("%8d %8d %10s %35s\n", vIn, c, f.toString(), fmt.toString());
CompressedState state2 = CompressedState.importFromMemory(wmem);
final CpcUnion union = new CpcUnion(lgK);
union.update(sk);
final CpcSketch sk2 = union.getResult();
skFmt = sk2.getFormat();
state = CompressedState.compress(sk2);
f = state.getFlavor();
fmt = state.getFormat();
assertEquals(fmt, skFmt);
c = state.numCoupons;
wmem = WritableMemory.allocate((int)state.getRequiredSerializedBytes());
state.exportToMemory(wmem);
printf("%8d %8d %10s %35s\n", vIn, c, f.toString(), fmt.toString());
state2 = CompressedState.importFromMemory(wmem);
fmt = state2.getFormat();
assertEquals(fmt, skFmt);
}
@Test
public void checkLoadMemory() {
printf("%8s %8s %10s %35s\n", "vIn", "c", "Flavor", "Format");
final CpcSketch sk = new CpcSketch(lgK);
final int k = 1 << lgK;
//EMPTY_MERGED
updateStateUnion(sk);
//SPARSE
sk.update(++vIn);
updateStateUnion(sk);
//HYBRID
while ((sk.numCoupons << 5) < (3L * k)) { sk.update(++vIn); }
updateStateUnion(sk);
//PINNED
while ((sk.numCoupons << 1) < k) { sk.update(++vIn); }
updateStateUnion(sk); //here
//SLIDING
while ((sk.numCoupons << 3) < (27L * k)) { sk.update(++vIn); }
updateStateUnion(sk);
}
@Test
public void checkToString() {
final CpcSketch sketch = new CpcSketch(10);
CompressedState state = CompressedState.compress(sketch);
println(state.toString());
sketch.update(0);
state = CompressedState.compress(sketch);
println(CompressedState.toString(state, true));
for (int i = 1; i < 600; i++) { sketch.update(i); }
state = CompressedState.compress(sketch);
println(CompressedState.toString(state, true));
}
@Test
public void checkIsCompressed() {
final CpcSketch sk = new CpcSketch(10);
final byte[] byteArr = sk.toByteArray();
byteArr[5] &= (byte) -3;
try {
CompressedState.importFromMemory(Memory.wrap(byteArr));
fail();
} catch (final AssertionError e) { }
}
/**
* @param format the string to print
* @param args the arguments
*/
private static void printf(final String format, final Object... args) {
//ps.printf(format, args);
}
/**
* @param s the string to print
*/
private static void println(final String s) {
//ps.println(s); //disable here
}
}
| 2,435 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/PairTableTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.apache.datasketches.cpc.PairTable.introspectiveInsertionSort;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import java.util.Random;
import org.apache.datasketches.common.SketchesArgumentException;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class PairTableTest {
Random rand = new Random();
@Test
public void checkSort() {
int len = 10;
int[] arr1 = new int[len];
for (int i = 0; i < len; i++) {
int r1 = rand.nextInt(10000);
arr1[i] = r1;
}
introspectiveInsertionSort(arr1, 0, len-1);
println("");
for (int i : arr1) { println(""+i); }
}
@Test
public void checkSort2() {
int len = 10;
int[] arr2 = new int[len];
for (int i = 0; i < len; i++) {
int r1 = rand.nextInt(10000);
long r2 = 3_000_000_000L;
arr2[i] = (int) (r2 + r1);
}
println("");
introspectiveInsertionSort(arr2, 0, len-1);
for (int i : arr2) { println("" + (i & 0XFFFF_FFFFL)); }
}
@Test
public void checkSort3() {
int len = 20;
int[] arr3 = new int[len];
for (int i = 0; i < len; i++) {
arr3[i] = (len - i) + 1;
}
println("");
introspectiveInsertionSort(arr3, 0, len-1);
for (int i : arr3) { println(""+i); }
}
@Test
public void checkMerge() {
int[] arrA = new int[] { 1, 3, 5 };
int[] arrB = new int[] { 2, 4, 6 };
int[] arrC = new int[6];
PairTable.merge(arrA, 0, 3, arrB, 0, 3, arrC, 0);
for (int i : arrC) { println(""+i); }
}
@Test
public void checkMerge2() {
int[] arrA = new int[] { 1, 3, 5 };
int[] arrB = new int[] { 2, 4, 6 };
int[] arrC = new int[6];
for (int i = 0; i < 3; i++) {
arrA[i] = (int) (arrA[i] + 3_000_000_000L);
arrB[i] = (int) (arrB[i] + 3_000_000_000L);
}
PairTable.merge(arrA, 0, 3, arrB, 0, 3, arrC, 0);
for (int i : arrC) { println("" + (i & 0XFFFF_FFFFL)); }
}
@SuppressWarnings("unused")
@Test
public void checkException() {
int lgK = 10;
PairTable a = new PairTable(2, lgK + 6);
assertEquals(a.getValidBits(), lgK + 6);
println(a.toString());
PairTable b = null;
try {
PairTable.equals(a, b);
fail();
} catch (SketchesArgumentException e) { }
try {
PairTable.equals(b, a);
fail();
} catch (SketchesArgumentException e) { }
try {
PairTable c = new PairTable(1, 16);
fail();
} catch (SketchesArgumentException e) { }
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,436 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/CpcSketchCrossLanguageTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES;
import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES;
import static org.apache.datasketches.common.TestUtil.cppPath;
import static org.apache.datasketches.common.TestUtil.javaPath;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.nio.file.Files;
import org.apache.datasketches.memory.Memory;
import org.testng.annotations.Test;
/**
* Serialize binary sketches to be tested by C++ code.
* Test deserialization of binary sketches serialized by C++ code.
*/
public class CpcSketchCrossLanguageTest {
@Test(groups = {GENERATE_JAVA_FILES})
public void generateBinariesForCompatibilityTesting() throws IOException {
final int[] nArr = {0, 100, 200, 2000, 20_000};
final Flavor[] flavorArr = {Flavor.EMPTY, Flavor.SPARSE, Flavor.HYBRID, Flavor.PINNED, Flavor.SLIDING};
int flavorIdx = 0;
for (int n: nArr) {
final CpcSketch sk = new CpcSketch(11);
for (int i = 0; i < n; i++) sk.update(i);
assertEquals(sk.getFlavor(), flavorArr[flavorIdx++]);
Files.newOutputStream(javaPath.resolve("cpc_n" + n + "_java.sk")).write(sk.toByteArray());
}
}
@Test(groups = {GENERATE_JAVA_FILES})
void negativeIntEquivalence() throws Exception {
CpcSketch sk = new CpcSketch();
byte v1 = (byte) -1;
sk.update(v1);
short v2 = -1;
sk.update(v2);
int v3 = -1;
sk.update(v3);
long v4 = -1;
sk.update(v4);
assertEquals(sk.getEstimate(), 1, 0.01);
Files.newOutputStream(javaPath.resolve("cpc_negative_one_java.sk")).write(sk.toByteArray());
}
@Test(groups = {CHECK_CPP_FILES})
public void allFlavors() throws IOException {
final int[] nArr = {0, 100, 200, 2000, 20000};
final Flavor[] flavorArr = {Flavor.EMPTY, Flavor.SPARSE, Flavor.HYBRID, Flavor.PINNED, Flavor.SLIDING};
int flavorIdx = 0;
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("cpc_n" + n + "_cpp.sk"));
final CpcSketch sketch = CpcSketch.heapify(Memory.wrap(bytes));
assertEquals(sketch.getFlavor(), flavorArr[flavorIdx++]);
assertEquals(sketch.getEstimate(), n, n * 0.02);
}
}
}
| 2,437 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/RuntimeAssertsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert;
import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals;
import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertFalse;
import static org.testng.Assert.fail;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class RuntimeAssertsTest {
@Test
public void checkPositives() {
rtAssertFalse(false);
short[] shortArr1 = new short[] { 1, 2, 3 };
short[] shortArr2 = shortArr1.clone();
rtAssertEquals(shortArr1, shortArr2);
shortArr1 = null;
shortArr2 = null;
rtAssertEquals(shortArr1, shortArr2);
float[] floatArr1 = new float[] { 1, 2, 3 };
float[] floatArr2 = floatArr1.clone();
rtAssertEquals(floatArr1, floatArr2, 0);
floatArr1 = null;
floatArr2 = null;
rtAssertEquals(floatArr1, floatArr2, 0);
double[] doubleArr1 = new double[] { 1, 2, 3 };
double[] doubleArr2 = doubleArr1.clone();
rtAssertEquals(doubleArr1, doubleArr2, 0);
doubleArr1 = null;
doubleArr2 = null;
rtAssertEquals(doubleArr1, doubleArr2, 0);
}
@Test
public void checkSimpleExceptions() {
try { rtAssert(false); fail(); } catch (AssertionError e) { }
try { rtAssertFalse(true); fail(); } catch (AssertionError e) { }
try { rtAssertEquals(1L, 2L); fail(); } catch (AssertionError e) { }
try { rtAssertEquals(1.0, 2.0, 0); fail(); } catch (AssertionError e) { }
try { rtAssertEquals(true, false); fail(); } catch (AssertionError e) { }
}
@Test
public void checkByteArr() {
byte[] arr1 = {1, 2};
byte[] arr2 = {1};
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = new byte[] {1, 3};
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = null;
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = arr1;
arr1 = null;
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = null;
rtAssertEquals(arr1, arr2);
}
@Test
public void checkShortArr() {
short[] arr1 = {1, 2};
short[] arr2 = {1};
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = new short[] {1, 3};
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = null;
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = arr1;
arr1 = null;
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = null;
rtAssertEquals(arr1, arr2);
}
@Test
public void checkIntArr() {
int[] arr1 = {1, 2};
int[] arr2 = {1};
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = new int[] {1, 3};
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = null;
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = arr1;
arr1 = null;
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = null;
rtAssertEquals(arr1, arr2);
}
@Test
public void checkLongArr() {
long[] arr1 = {1, 2};
long[] arr2 = {1};
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = new long[] {1, 3};
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = null;
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = arr1;
arr1 = null;
try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { }
arr2 = null;
rtAssertEquals(arr1, arr2);
}
@Test
public void checkFloatArr() {
float[] arr1 = {1, 2};
float[] arr2 = {1};
try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { }
arr2 = new float[] {1, 3};
try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { }
arr2 = null;
try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { }
arr2 = arr1;
arr1 = null;
try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { }
arr2 = null;
rtAssertEquals(arr1, arr2, 0);
}
@Test
public void checkDoubleArr() {
double[] arr1 = {1, 2};
double[] arr2 = {1};
try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { }
arr2 = new double[] {1, 3};
try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { }
arr2 = null;
try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { }
arr2 = arr1;
arr1 = null;
try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { }
arr2 = null;
rtAssertEquals(arr1, arr2, 0);
}
}
| 2,438 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/CpcUnionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.testng.annotations.Test;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesStateException;
/**
* @author Lee Rhodes
*/
public class CpcUnionTest {
@Test
public void checkExceptions() {
CpcSketch sk = new CpcSketch(10, 1);
CpcUnion union = new CpcUnion();
try {
union.update(sk);
fail();
} catch (SketchesArgumentException e) {}
sk = null;
union.update(sk);
union = null;
try {
CpcUnion.getBitMatrix(union);
fail();
} catch (SketchesStateException e) {}
}
@Test
public void checkGetters() {
int lgK = 10;
CpcUnion union = new CpcUnion(lgK);
assertEquals(union.getLgK(), lgK);
assertEquals(union.getNumCoupons(), 0L);
CpcSketch sk = new CpcSketch(lgK);
for (int i = 0; i <= (4 << lgK); i++) { sk.update(i); }
union.update(sk);
assertTrue(union.getNumCoupons() > 0);
assertTrue(CpcUnion.getBitMatrix(union) != null);
assertEquals(Family.CPC, CpcUnion.getFamily());
}
@Test
public void checkReduceK() {
CpcUnion union = new CpcUnion(12);
CpcSketch sk = new CpcSketch(11);
int u = 1;
sk.update(u);
union.update(sk);
CpcUnion.getBitMatrix(union);
CpcSketch sk2 = new CpcSketch(10);
int shTrans = ((3 * 512) / 32); //sparse-hybrid transition for lgK=9
while (sk2.numCoupons < shTrans) { sk2.update(++u); }
union.update(sk2);
CpcSketch sk3 = new CpcSketch(9);
sk3.update(++u);
union.update(sk3);
CpcSketch sk4 = new CpcSketch(8);
sk4.update(++u);
union.update(sk4);
}
}
| 2,439 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/PreambleUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.apache.datasketches.cpc.PreambleUtil.COMPRESSED_FLAG_MASK;
import static org.apache.datasketches.cpc.PreambleUtil.SER_VER;
import static org.apache.datasketches.cpc.PreambleUtil.getDefinedPreInts;
import static org.apache.datasketches.cpc.PreambleUtil.getFamily;
import static org.apache.datasketches.cpc.PreambleUtil.getFiCol;
import static org.apache.datasketches.cpc.PreambleUtil.getFlags;
import static org.apache.datasketches.cpc.PreambleUtil.getFormat;
import static org.apache.datasketches.cpc.PreambleUtil.getHipAccum;
import static org.apache.datasketches.cpc.PreambleUtil.getKxP;
import static org.apache.datasketches.cpc.PreambleUtil.getLgK;
import static org.apache.datasketches.cpc.PreambleUtil.getNumCoupons;
import static org.apache.datasketches.cpc.PreambleUtil.getNumSv;
import static org.apache.datasketches.cpc.PreambleUtil.getPreInts;
import static org.apache.datasketches.cpc.PreambleUtil.getSeedHash;
import static org.apache.datasketches.cpc.PreambleUtil.getSerVer;
import static org.apache.datasketches.cpc.PreambleUtil.getSvLengthInts;
import static org.apache.datasketches.cpc.PreambleUtil.getSvStreamOffset;
import static org.apache.datasketches.cpc.PreambleUtil.getWLengthInts;
import static org.apache.datasketches.cpc.PreambleUtil.getWStreamOffset;
import static org.apache.datasketches.cpc.PreambleUtil.hasHip;
import static org.apache.datasketches.cpc.PreambleUtil.putEmptyMerged;
import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingHip;
import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingHipNoSv;
import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingMerged;
import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingMergedNoSv;
import static org.apache.datasketches.cpc.PreambleUtil.putSparseHybridHip;
import static org.apache.datasketches.cpc.PreambleUtil.putSparseHybridMerged;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.testng.annotations.Test;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesStateException;
import org.apache.datasketches.cpc.PreambleUtil.HiField;
/**
* @author Lee Rhodes
*/
public class PreambleUtilTest {
static final short defaultSeedHash = ThetaUtil.computeSeedHash(ThetaUtil.DEFAULT_UPDATE_SEED) ;
private static void checkFirst8(WritableMemory wmem, Format format, int lgK, int fiCol) {
assertEquals(getFormat(wmem), format);
assertEquals(getPreInts(wmem), getDefinedPreInts(format));
assertEquals(getSerVer(wmem), SER_VER);
assertEquals(getFamily(wmem), Family.CPC);
assertEquals(getLgK(wmem), lgK);
assertEquals(getFiCol(wmem), fiCol);
assertEquals(getFlags(wmem), (format.ordinal() << 2) | COMPRESSED_FLAG_MASK);
assertEquals(getSeedHash(wmem), defaultSeedHash);
}
@Test
public void checkNormalPutMemory() {
int lgK = 12;
double kxp = lgK;
double hipAccum = 1005;
int fiCol = 1;
int[] csvStream = new int[] {1, 2, 3};
int numCoupons = csvStream.length;
int csvLength = csvStream.length;
short seedHash = defaultSeedHash;
int[] cwStream = new int[] {4, 5, 6};
int cwLength = cwStream.length;
int numSv = cwStream.length;
int maxInts = 10 + csvLength + cwLength;
WritableMemory wmem = WritableMemory.allocate(4 * maxInts);
Format format;
format = Format.EMPTY_MERGED;
putEmptyMerged(wmem, lgK, seedHash);
println(CpcSketch.toString((byte[])wmem.getArray(), true));
checkFirst8(wmem, format, lgK, (byte) 0);
assertFalse(hasHip(wmem));
format = Format.SPARSE_HYBRID_MERGED;
putSparseHybridMerged(wmem, lgK, numCoupons, csvLength, seedHash, csvStream);
println(CpcSketch.toString(wmem, true));
println(CpcSketch.toString(wmem, false));
checkFirst8(wmem, format, lgK, (byte) 0);
assertEquals(getNumCoupons(wmem), numCoupons);
assertEquals(getSvLengthInts(wmem), csvLength);
format = Format.SPARSE_HYBRID_HIP;
putSparseHybridHip(wmem, lgK, numCoupons, csvLength, kxp, hipAccum, seedHash, csvStream);
println(CpcSketch.toString(wmem, true));
println(CpcSketch.toString(wmem, false));
checkFirst8(wmem, format, lgK, (byte) 0);
assertEquals(getNumCoupons(wmem), numCoupons);
assertEquals(getSvLengthInts(wmem), csvLength);
assertEquals(getKxP(wmem), kxp);
assertEquals(getHipAccum(wmem), hipAccum);
assertTrue(hasHip(wmem));
format = Format.PINNED_SLIDING_MERGED_NOSV;
putPinnedSlidingMergedNoSv(wmem, lgK, fiCol, numCoupons, cwLength, seedHash, cwStream);
println(CpcSketch.toString(wmem, true));
println(CpcSketch.toString(wmem, false));
checkFirst8(wmem, format, lgK, fiCol);
assertEquals(getNumCoupons(wmem), numCoupons);
assertEquals(getWLengthInts(wmem), cwLength);
format = Format.PINNED_SLIDING_HIP_NOSV;
putPinnedSlidingHipNoSv(wmem, lgK, fiCol, numCoupons, cwLength, kxp, hipAccum, seedHash,
cwStream);
println(CpcSketch.toString(wmem, true));
println(CpcSketch.toString(wmem, false));
checkFirst8(wmem, format, lgK, fiCol);
assertEquals(getNumCoupons(wmem), numCoupons);
assertEquals(getWLengthInts(wmem), cwLength);
assertEquals(getKxP(wmem), kxp);
assertEquals(getHipAccum(wmem), hipAccum);
format = Format.PINNED_SLIDING_MERGED;
putPinnedSlidingMerged(wmem, lgK, fiCol, numCoupons, numSv, csvLength, cwLength, seedHash,
csvStream, cwStream);
println(CpcSketch.toString(wmem, true));
println(CpcSketch.toString(wmem, false));
checkFirst8(wmem, format, lgK, fiCol);
assertEquals(getNumCoupons(wmem), numCoupons);
assertEquals(getNumSv(wmem), numSv);
assertEquals(getSvLengthInts(wmem), csvLength);
assertEquals(getWLengthInts(wmem), cwLength);
format = Format.PINNED_SLIDING_HIP;
putPinnedSlidingHip(wmem, lgK, fiCol, numCoupons, numSv, kxp, hipAccum, csvLength, cwLength,
seedHash, csvStream, cwStream);
println(CpcSketch.toString(wmem, true));
println(CpcSketch.toString(wmem, false));
checkFirst8(wmem, format, lgK, fiCol);
assertEquals(getNumCoupons(wmem), numCoupons);
assertEquals(getNumSv(wmem), numSv);
assertEquals(getSvLengthInts(wmem), csvLength);
assertEquals(getWLengthInts(wmem), cwLength);
assertEquals(getKxP(wmem), kxp);
assertEquals(getHipAccum(wmem), hipAccum);
}
@Test
public void checkStreamErrors() {
WritableMemory wmem = WritableMemory.allocate(4 * 10);
putEmptyMerged(wmem, (byte) 12, defaultSeedHash);
try { getSvStreamOffset(wmem); fail(); } catch (SketchesArgumentException e) { }
wmem.putByte(5, (byte) (7 << 2));
try { getSvStreamOffset(wmem); fail(); } catch (SketchesStateException e) { }
wmem.putByte(5, (byte) 0);
try { getWStreamOffset(wmem); fail(); } catch (SketchesArgumentException e) { }
wmem.putByte(5, (byte) (7 << 2));
try { getWStreamOffset(wmem); fail(); } catch (SketchesStateException e) { }
}
@Test
public void checkStreamErrors2() {
WritableMemory wmem = WritableMemory.allocate(4 * 10);
int[] svStream = { 1 };
int[] wStream = { 2 };
try {
putPinnedSlidingMerged(wmem, 4, 0, 1, 1, 1, 0, (short) 0, svStream, wStream);
fail();
} catch (SketchesStateException e) { }
assertTrue(PreambleUtil.isCompressed(wmem));
}
@Test
public void checkEmptyMemory() {
WritableMemory wmem = WritableMemory.allocate(4 * 10);
wmem.putByte(2, (byte) 16); //legal Family
wmem.putByte(5, (byte) (1 << 2)); //select NONE
println(CpcSketch.toString(wmem, false));
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkFieldError() {
PreambleUtil.fieldError(Format.EMPTY_MERGED, HiField.NUM_COUPONS);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkCapacity() {
PreambleUtil.checkCapacity(100, 101);
}
@Test(expectedExceptions = SketchesStateException.class)
public void checkHiFieldError() {
PreambleUtil.getHiFieldOffset(Format.EMPTY_MERGED, HiField.NUM_COUPONS);
}
@Test
public void checkWindowOffset() {
long offset = CpcUtil.determineCorrectOffset(4, 54);
assertEquals(offset, 1L);
}
@Test
public void checkFormatEnum() {
assertEquals(Format.EMPTY_MERGED, Format.ordinalToFormat(0));
assertEquals(Format.EMPTY_HIP, Format.ordinalToFormat(1));
assertEquals(Format.SPARSE_HYBRID_MERGED, Format.ordinalToFormat(2));
assertEquals(Format.SPARSE_HYBRID_HIP, Format.ordinalToFormat(3));
assertEquals(Format.PINNED_SLIDING_MERGED_NOSV, Format.ordinalToFormat(4));
assertEquals(Format.PINNED_SLIDING_HIP_NOSV, Format.ordinalToFormat(5));
assertEquals(Format.PINNED_SLIDING_MERGED, Format.ordinalToFormat(6));
assertEquals(Format.PINNED_SLIDING_HIP, Format.ordinalToFormat(7));
}
@Test
public void checkFlavorEnum() {
assertEquals(Flavor.EMPTY, Flavor.ordinalToFlavor(0));
assertEquals(Flavor.SPARSE, Flavor.ordinalToFlavor(1));
assertEquals(Flavor.HYBRID, Flavor.ordinalToFlavor(2));
assertEquals(Flavor.PINNED, Flavor.ordinalToFlavor(3));
assertEquals(Flavor.SLIDING, Flavor.ordinalToFlavor(4));
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,440 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/TestAllTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.testng.Assert.assertEquals;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Arrays;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class TestAllTest {
// Enable these as desired for all tests.
private PrintStream ps = null; //System.out; //prints to console
private PrintWriter pw = null; //prints to file (optional)
//STREAMING
@Test //scope = Test
public void streamingCheck() {
int lgMinK = 10;
int lgMaxK = 10;
int trials = 10;
int ppoN = 1;
StreamingValidation sVal = new StreamingValidation(
lgMinK, lgMaxK, trials, ppoN, ps, pw);
sVal.start();
}
//Matrix
@Test
public void matrixCouponCountCheck() {
long pat = 0xA5A5A5A5_5A5A5A5AL;
int len = 16;
long[] arr = new long[len];
Arrays.fill(arr, pat);
long trueCount = (long)len * Long.bitCount(pat);
long testCount = BitMatrix.countCoupons(arr);
assertEquals(testCount, trueCount);
}
//COMPRESSION
@Test //scope = Test
public void compressionCharacterizationCheck() {
int lgMinK = 10;
int lgMaxK = 10;
int lgMaxT = 5; //Trials at start
int lgMinT = 2; //Trials at end
int lgMulK = 7;
int uPPO = 1;
int incLgK = 1;
CompressionCharacterization cc = new CompressionCharacterization(
lgMinK, lgMaxK, lgMinT, lgMaxT, lgMulK, uPPO, incLgK, ps, pw);
cc.start();
}
//@Test //used for troubleshooting a specific rowCol problems
public void singleRowColCheck() {
int lgK = 20;
CpcSketch srcSketch = new CpcSketch(lgK);
int rowCol = 54746379;
srcSketch.rowColUpdate(rowCol);
ps.println(srcSketch.toString(true));
CompressedState state = CompressedState.compress(srcSketch);
ps.println(CompressedState.toString(state, true));
CpcSketch uncSketch = CpcSketch.uncompress(state, ThetaUtil.DEFAULT_UPDATE_SEED);
ps.println(uncSketch.toString(true));
}
//MERGING
@Test //longer test. use for characterization
public void mergingValidationCheck() {
int lgMinK = 10;
int lgMaxK = 10; //inclusive
int lgMulK = 5; //5
int uPPO = 1; //16
int incLgK = 1;
MergingValidation mv = new MergingValidation(
lgMinK, lgMaxK, lgMulK, uPPO, incLgK, ps, pw);
mv.start();
}
@Test //scope = Test
public void quickMergingValidationCheck() {
int lgMinK = 10;
int lgMaxK = 10;
int incLgK = 1;
QuickMergingValidation qmv = new QuickMergingValidation(
lgMinK, lgMaxK, incLgK, ps, pw);
qmv.start();
}
@Test
public void checkPwrLaw10NextDouble() {
double next = TestUtil.pwrLaw10NextDouble(1, 10.0);
assertEquals(next, 100.0);
}
}
| 2,441 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/CpcWrapperTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import java.io.PrintStream;
import org.testng.annotations.Test;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.memory.Memory;
/**
* @author Lee Rhodes
*/
public class CpcWrapperTest {
static PrintStream ps = System.out;
@SuppressWarnings("unused")
@Test
public void check() {
int lgK = 10;
CpcSketch sk1 = new CpcSketch(lgK);
CpcSketch sk2 = new CpcSketch(lgK);
CpcSketch skD = new CpcSketch(lgK);
double dEst = skD.getEstimate();
double dlb = skD.getLowerBound(2);
double dub = skD.getUpperBound(2);
int n = 100000;
for (int i = 0; i < n; i++) {
sk1.update(i);
sk2.update(i + n);
skD.update(i);
skD.update(i + n);
}
byte[] concatArr = skD.toByteArray();
CpcUnion union = new CpcUnion(lgK);
CpcSketch result = union.getResult();
double uEst = result.getEstimate();
double ulb = result.getLowerBound(2);
double uub = result.getUpperBound(2);
union.update(sk1);
union.update(sk2);
CpcSketch merged = union.getResult();
byte[] mergedArr = merged.toByteArray();
Memory concatMem = Memory.wrap(concatArr);
CpcWrapper concatSk = new CpcWrapper(concatMem);
assertEquals(concatSk.getLgK(), lgK);
printf(" %12s %12s %12s\n", "Lb", "Est", "Ub");
double ccEst = concatSk.getEstimate();
double ccLb = concatSk.getLowerBound(2);
double ccUb = concatSk.getUpperBound(2);
printf("Concatenated: %12.0f %12.0f %12.0f\n", ccLb, ccEst, ccUb);
//Memory mergedMem = Memory.wrap(mergedArr);
CpcWrapper mergedSk = new CpcWrapper(mergedArr);
double mEst = mergedSk.getEstimate();
double mLb = mergedSk.getLowerBound(2);
double mUb = mergedSk.getUpperBound(2);
printf("Merged: %12.0f %12.0f %12.0f\n", mLb, mEst, mUb);
assertEquals(Family.CPC, CpcWrapper.getFamily());
}
@SuppressWarnings("unused")
@Test
public void checkIsCompressed() {
CpcSketch sk = new CpcSketch(10);
byte[] byteArr = sk.toByteArray();
byteArr[5] &= (byte) -3;
try {
CpcWrapper wrapper = new CpcWrapper(Memory.wrap(byteArr));
fail();
} catch (AssertionError e) {}
}
/**
* @param format the string to print
* @param args the arguments
*/
static void printf(String format, Object... args) {
//ps.printf(format, args); //disable here
}
/**
* @param s the string to print
*/
static void println(String s) {
//ps.println(s); //disable here
}
}
| 2,442 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/IconEstimatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.apache.datasketches.cpc.IconEstimator.getIconEstimate;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.common.SketchesStateException;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class IconEstimatorTest {
//SLOW EXACT VERSION, Eventually move to characterization
/**
* Important note: do not change anything in the following function.
* It has been carefully designed and tested for numerical accuracy.
* In particular, the use of log1p and expm1 is critically important.
* @param kf the value of k as a double
* @param nf the value of n as a double
* @param col the given column
* @return the quantity qnj
*/
static double qnj(final double kf, final double nf, final int col) {
final double tmp1 = -1.0 / (kf * (Math.pow(2.0, col)));
final double tmp2 = Math.log1p(tmp1);
return (-1.0 * (Math.expm1(nf * tmp2)));
}
static double exactCofN(final double kf, final double nf) {
double total = 0.0;
for (int col = 128; col >= 1; col--) {
total += qnj(kf, nf, col);
}
return kf * total;
}
static final double iconInversionTolerance = 1.0e-15;
static double exactIconEstimatorBinarySearch(final double kf, final double targetC,
final double nLoIn, final double nHiIn) {
int depth = 0;
double nLo = nLoIn;
double nHi = nHiIn;
while (true) { // manual tail recursion optimization
if (depth > 100) {
throw new SketchesStateException("Excessive recursion in binary search\n");
}
assert nHi > nLo;
final double nMid = nLo + (0.5 * (nHi - nLo));
assert ((nMid > nLo) && (nMid < nHi));
if (((nHi - nLo) / nMid) < iconInversionTolerance) {
return (nMid);
}
final double midC = exactCofN(kf, nMid);
if (midC == targetC) {
return nMid;
}
if (midC < targetC) {
nLo = nMid;
depth++;
continue;
}
if (midC > targetC) {
nHi = nMid;
depth++;
continue;
}
throw new SketchesStateException("bad value in binary search\n");
}
}
static double exactIconEstimatorBracketHi(final double kf, final double targetC, final double nLo) {
int depth = 0;
double curN = 2.0 * nLo;
double curC = exactCofN(kf, curN);
while (curC <= targetC) {
if (depth > 100) {
throw new SketchesStateException("Excessive looping in exactIconEstimatorBracketHi\n");
}
depth++;
curN *= 2.0;
curC = exactCofN(kf, curN);
}
assert (curC > targetC);
return (curN);
}
static double exactIconEstimator(final int lgK, final long c) {
final double targetC = c;
if ((c == 0L) || (c == 1L)) {
return targetC;
}
final double kf = (1L << lgK);
final double nLo = targetC;
assert exactCofN(kf, nLo) < targetC; // bracket lo
final double nHi = exactIconEstimatorBracketHi(kf, targetC, nLo); // bracket hi
return exactIconEstimatorBinarySearch(kf, targetC, nLo, nHi);
}
//@Test //used for characterization
public static void testIconEstimator() {
final int lgK = 12;
final int k = 1 << lgK;
long c = 1;
while (c < (k * 64)) { // was K * 15
final double exact = exactIconEstimator(lgK, c);
final double approx = getIconEstimate(lgK, c);
final double relDiff = (approx - exact) / exact;
printf("%d\t%.19g\t%.19g\t%.19g\n", c, relDiff, exact, approx);
final long a = c + 1;
final long b = (1001 * c) / 1000;
c = ((a > b) ? a : b);
}
}
@Test //used for unit test
public static void quickIconEstimatorTest() {
for (int lgK = 4; lgK <= 26; lgK++) {
final long k = 1L << lgK;
long[] cArr = {2, 5 * k, 6 * k, 60L * k};
assertEquals(getIconEstimate(lgK, 0L), 0.0, 0.0);
assertEquals(getIconEstimate(lgK, 1L), 1.0, 0.0);
for (long c : cArr) {
final double exact = exactIconEstimator(lgK, c);
final double approx = getIconEstimate(lgK, c);
final double relDiff = Math.abs((approx - exact) / exact);
printf("%d\t %d\t %.19g\t %.19g\t %.19g\n", lgK, c, relDiff, exact, approx);
assertTrue(relDiff < Math.max(2E-6, 1.0/(80 * k)));
}
}
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* Print with format
* @param format the given format
* @param args the args
*/
static void printf(String format, Object ... args) {
String out = String.format(format, args);
print(out);
}
/**
* @param s value to print
*/
static void println(String s) {
print(s + "\n");
}
/**
* @param s value to print
*/
static void print(String s) {
//System.out.print(s); //disable here
}
}
| 2,443 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/CpcSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.apache.datasketches.cpc.TestUtil.specialEquals;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.io.PrintStream;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class CpcSketchTest {
static PrintStream ps = System.out;
@Test
public void checkUpdatesEstimate() {
final CpcSketch sk = new CpcSketch(10, 0);
println(sk.toString(true));
assertEquals(sk.getFormat(), Format.EMPTY_HIP);
sk.update(1L);
sk.update(2.0);
sk.update("3");
sk.update(new byte[] { 4 });
sk.update(new char[] { 5 });
sk.update(new int[] { 6 });
sk.update(new long[] { 7 });
final double est = sk.getEstimate();
final double lb = sk.getLowerBound(2);
final double ub = sk.getUpperBound(2);
assertTrue(lb >= 0);
assertTrue(lb <= est);
assertTrue(est <= ub);
assertEquals(sk.getFlavor(), Flavor.SPARSE);
assertEquals(sk.getFormat(), Format.SPARSE_HYBRID_HIP);
println(sk.toString());
println(sk.toString(true));
}
@Test
public void checkEstimatesWithMerge() {
final int lgK = 4;
final CpcSketch sk1 = new CpcSketch(lgK);
final CpcSketch sk2 = new CpcSketch(lgK);
final int n = 1 << lgK;
for (int i = 0; i < n; i++ ) {
sk1.update(i);
sk2.update(i + n);
}
final CpcUnion union = new CpcUnion(lgK);
union.update(sk1);
union.update(sk2);
final CpcSketch result = union.getResult();
final double est = result.getEstimate();
final double lb = result.getLowerBound(2);
final double ub = result.getUpperBound(2);
assertTrue(lb >= 0);
assertTrue(lb <= est);
assertTrue(est <= ub);
assertTrue(result.validate());
println(result.toString(true));
}
@Test
public void checkCornerCaseUpdates() {
final int lgK = 4;
final CpcSketch sk = new CpcSketch(lgK);
sk.update(0.0);
sk.update(-0.0);
int est = (int) Math.round(sk.getEstimate());
assertEquals(est, 1);
String s = null;
sk.update(s);
s = "";
sk.update(s);
est = (int) Math.round(sk.getEstimate());
assertEquals(est, 1);
byte[] barr = null;
sk.update(barr);
est = (int) Math.round(sk.getEstimate());
assertEquals(est, 1);
barr = new byte[0];
est = (int) Math.round(sk.getEstimate());
assertEquals(est, 1);
char[] carr = null;
sk.update(carr);
est = (int) Math.round(sk.getEstimate());
assertEquals(est, 1);
carr = new char[0];
est = (int) Math.round(sk.getEstimate());
assertEquals(est, 1);
int[] iarr = null;
sk.update(iarr);
est = (int) Math.round(sk.getEstimate());
assertEquals(est, 1);
iarr = new int[0];
est = (int) Math.round(sk.getEstimate());
assertEquals(est, 1);
long[] larr = null;
sk.update(larr);
est = (int) Math.round(sk.getEstimate());
assertEquals(est, 1);
larr = new long[0];
est = (int) Math.round(sk.getEstimate());
assertEquals(est, 1);
}
@Test
public void checkCornerHashUpdates() {
final CpcSketch sk = new CpcSketch(26);
final long hash1 = 0;
final long hash0 = -1L;
sk.hashUpdate(hash0, hash1);
final PairTable table = sk.pairTable;
println(table.toString(true));
}
@SuppressWarnings("unused")
@Test
public void checkCopyWithWindow() {
final int lgK = 4;
final CpcSketch sk = new CpcSketch(lgK);
CpcSketch sk2 = sk.copy();
for (int i = 0; i < (1 << lgK); i++) { //pinned
sk.update(i);
}
sk2 = sk.copy();
final long[] bitMatrix = CpcUtil.bitMatrixOfSketch(sk);
CpcSketch.refreshKXP(sk, bitMatrix);
}
@Test
public void checkFamily() {
assertEquals(CpcSketch.getFamily(), Family.CPC);
}
@Test
public void checkLgK() {
CpcSketch sk = new CpcSketch(10);
assertEquals(sk.getLgK(), 10);
try {
sk = new CpcSketch(3);
fail();
} catch (final SketchesArgumentException e) { }
}
@Test
public void checkIconHipUBLBLg15() {
CpcConfidence.getIconConfidenceUB(15, 1, 2);
CpcConfidence.getIconConfidenceLB(15, 1, 2);
CpcConfidence.getHipConfidenceUB(15, 1, 1.0, 2);
CpcConfidence.getHipConfidenceLB(15, 1, 1.0, 2);
}
@Test
public void checkHeapify() {
int lgK = 10;
CpcSketch sk = new CpcSketch(lgK, ThetaUtil.DEFAULT_UPDATE_SEED);
assertTrue(sk.isEmpty());
byte[] byteArray = sk.toByteArray();
CpcSketch sk2 = CpcSketch.heapify(byteArray, ThetaUtil.DEFAULT_UPDATE_SEED);
assertTrue(specialEquals(sk2, sk, false, false));
}
@Test
public void checkHeapify2() {
int lgK = 10;
CpcSketch sk = new CpcSketch(lgK);
assertTrue(sk.isEmpty());
byte[] byteArray = sk.toByteArray();
Memory mem = Memory.wrap(byteArray);
CpcSketch sk2 = CpcSketch.heapify(mem);
assertTrue(specialEquals(sk2, sk, false, false));
}
@Test
public void checkRowColUpdate() {
int lgK = 10;
CpcSketch sk = new CpcSketch(lgK, ThetaUtil.DEFAULT_UPDATE_SEED);
sk.rowColUpdate(0);
assertEquals(sk.getFlavor(), Flavor.SPARSE);
}
@Test
public void checkGetMaxSize() {
final int size4 = CpcSketch.getMaxSerializedBytes(4);
final int size26 = CpcSketch.getMaxSerializedBytes(26);
assertEquals(size4, 24 + 40);
assertEquals(size26, (int) ((0.6 * (1 << 26)) + 40));
}
/**
* @param s the string to print
*/
private static void println(String s) {
//ps.println(s); //disable here
}
}
| 2,444 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/cpc/CompressionDataTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static org.apache.datasketches.cpc.CompressionData.decodingTablesForHighEntropyByte;
import static org.apache.datasketches.cpc.CompressionData.encodingTablesForHighEntropyByte;
import static org.apache.datasketches.cpc.CompressionData.lengthLimitedUnaryDecodingTable65;
import static org.apache.datasketches.cpc.CompressionData.lengthLimitedUnaryEncodingTable65;
import static org.apache.datasketches.cpc.CompressionData.validateDecodingTable;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class CompressionDataTest {
@Test
public static void checkTables() {
validateDecodingTable(lengthLimitedUnaryDecodingTable65, lengthLimitedUnaryEncodingTable65);
for (int i = 0; i < (16 + 6); i++) {
validateDecodingTable(decodingTablesForHighEntropyByte[i], encodingTablesForHighEntropyByte[i]);
}
}
}
| 2,445 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/SingleItemSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.hash.MurmurHash3.hash;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class SingleItemSketchTest {
final static short DEFAULT_SEED_HASH = (short) (ThetaUtil.computeSeedHash(ThetaUtil.DEFAULT_UPDATE_SEED) & 0XFFFFL);
@Test
public void check1() {
Union union = Sketches.setOperationBuilder().buildUnion();
union.union(SingleItemSketch.create(1));
union.union(SingleItemSketch.create(1.0));
union.union(SingleItemSketch.create(0.0));
union.union(SingleItemSketch.create("1"));
union.union(SingleItemSketch.create(new byte[] {1,2,3,4}));
union.union(SingleItemSketch.create(new char[] {'a'}));
union.union(SingleItemSketch.create(new int[] {2}));
union.union(SingleItemSketch.create(new long[] {3}));
union.union(SingleItemSketch.create(-0.0)); //duplicate
double est = union.getResult().getEstimate();
println(""+est);
assertEquals(est, 8.0, 0.0);
assertNull(SingleItemSketch.create(""));
String str = null;
assertNull(SingleItemSketch.create(str));//returns null
assertNull(SingleItemSketch.create(new byte[0]));//returns null
byte[] byteArr = null;
assertNull(SingleItemSketch.create(byteArr));//returns null
assertNull(SingleItemSketch.create(new char[0]));//returns null
char[] charArr = null;
assertNull(SingleItemSketch.create(charArr));//returns null
assertNull(SingleItemSketch.create(new int[0]));//returns null
int[] intArr = null;
assertNull(SingleItemSketch.create(intArr));//returns null
assertNull(SingleItemSketch.create(new long[0]));//returns null
long[] longArr = null;
assertNull(SingleItemSketch.create(longArr));//returns null
}
@Test
public void check2() {
long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
Union union = Sketches.setOperationBuilder().buildUnion();
union.union(SingleItemSketch.create(1, seed));
union.union(SingleItemSketch.create(1.0, seed));
union.union(SingleItemSketch.create(0.0, seed));
union.union(SingleItemSketch.create("1", seed));
union.union(SingleItemSketch.create(new byte[] {1,2,3,4}, seed));
union.union(SingleItemSketch.create(new char[] {'a'}, seed));
union.union(SingleItemSketch.create(new int[] {2}, seed));
union.union(SingleItemSketch.create(new long[] {3}, seed));
union.union(SingleItemSketch.create(-0.0, seed)); //duplicate
double est = union.getResult().getEstimate();
println(""+est);
assertEquals(est, 8.0, 0.0);
assertNull(SingleItemSketch.create("", seed));
String str = null;
assertNull(SingleItemSketch.create(str, seed));//returns null
assertNull(SingleItemSketch.create(new byte[0], seed));//returns null
byte[] byteArr = null;
assertNull(SingleItemSketch.create(byteArr, seed));//returns null
assertNull(SingleItemSketch.create(new char[0], seed));//returns null
char[] charArr = null;
assertNull(SingleItemSketch.create(charArr, seed));//returns null
assertNull(SingleItemSketch.create(new int[0], seed));//returns null
int[] intArr = null;
assertNull(SingleItemSketch.create(intArr, seed));//returns null
assertNull(SingleItemSketch.create(new long[0], seed));//returns null
long[] longArr = null;
assertNull(SingleItemSketch.create(longArr, seed));//returns null
}
@Test
public void checkSketchInterface() {
SingleItemSketch sis = SingleItemSketch.create(1);
assertEquals(sis.getCompactBytes(), 16);
assertEquals(sis.getEstimate(), 1.0);
assertEquals(sis.getLowerBound(1), 1.0);
assertEquals(sis.getRetainedEntries(true), 1);
assertEquals(sis.getUpperBound(1), 1.0);
assertFalse(sis.isDirect());
assertFalse(sis.hasMemory());
assertFalse(sis.isEmpty());
assertTrue(sis.isOrdered());
}
@Test
public void checkLessThanThetaLong() {
for (int i = 0; i < 10; i++) {
long[] data = { i };
long h = hash(data, ThetaUtil.DEFAULT_UPDATE_SEED)[0] >>> 1;
SingleItemSketch sis = SingleItemSketch.create(i);
long halfMax = Long.MAX_VALUE >> 1;
int count = sis.getCountLessThanThetaLong(halfMax);
assertEquals(count, (h < halfMax) ? 1 : 0);
}
}
@Test
public void checkSerDe() {
SingleItemSketch sis = SingleItemSketch.create(1);
byte[] byteArr = sis.toByteArray();
Memory mem = Memory.wrap(byteArr);
final short defaultSeedHash = ThetaUtil.computeSeedHash(ThetaUtil.DEFAULT_UPDATE_SEED);
SingleItemSketch sis2 = SingleItemSketch.heapify(mem, defaultSeedHash);
assertEquals(sis2.getEstimate(), 1.0);
SingleItemSketch sis3 = SingleItemSketch.heapify(mem, defaultSeedHash);
assertEquals(sis3.getEstimate(), 1.0);
Union union = Sketches.setOperationBuilder().buildUnion();
union.union(sis);
union.union(sis2);
union.union(sis3);
CompactSketch csk = union.getResult();
assertTrue(csk instanceof SingleItemSketch);
assertEquals(union.getResult().getEstimate(), 1.0);
}
@Test
public void checkRestricted() {
SingleItemSketch sis = SingleItemSketch.create(1);
assertNull(sis.getMemory());
assertEquals(sis.getCompactPreambleLongs(), 1);
}
@Test
public void unionWrapped() {
Sketch sketch = SingleItemSketch.create(1);
Union union = Sketches.setOperationBuilder().buildUnion();
Memory mem = Memory.wrap(sketch.toByteArray());
union.union(mem);
assertEquals(union.getResult().getEstimate(), 1, 0);
}
@Test
public void buildAndCompact() {
UpdateSketch sk1;
CompactSketch csk;
int bytes;
//On-heap
sk1 = Sketches.updateSketchBuilder().setNominalEntries(32).build();
sk1.update(1);
csk = sk1.compact(true, null);
assertTrue(csk instanceof SingleItemSketch);
csk = sk1.compact(false, null);
assertTrue(csk instanceof SingleItemSketch);
//Off-heap
bytes = Sketches.getMaxUpdateSketchBytes(32);
WritableMemory wmem = WritableMemory.writableWrap(new byte[bytes]);
sk1= Sketches.updateSketchBuilder().setNominalEntries(32).build(wmem);
sk1.update(1);
csk = sk1.compact(true, null);
assertTrue(csk instanceof SingleItemSketch);
csk = sk1.compact(false, null);
assertTrue(csk instanceof SingleItemSketch);
bytes = Sketches.getMaxCompactSketchBytes(1);
wmem = WritableMemory.writableWrap(new byte[bytes]);
csk = sk1.compact(true, wmem);
assertTrue(csk.isOrdered());
csk = sk1.compact(false, wmem);
assertTrue(csk.isOrdered());
}
@Test
public void intersection() {
UpdateSketch sk1, sk2;
CompactSketch csk;
int bytes;
//Intersection on-heap
sk1 = Sketches.updateSketchBuilder().setNominalEntries(32).build();
sk2 = Sketches.updateSketchBuilder().setNominalEntries(32).build();
sk1.update(1);
sk1.update(2);
sk2.update(1);
Intersection inter = Sketches.setOperationBuilder().buildIntersection();
inter.intersect(sk1);
inter.intersect(sk2);
csk = inter.getResult(true, null);
assertTrue(csk instanceof SingleItemSketch);
//Intersection off-heap
bytes = Sketches.getMaxIntersectionBytes(32);
WritableMemory wmem = WritableMemory.writableWrap(new byte[bytes]);
inter = Sketches.setOperationBuilder().buildIntersection(wmem);
inter.intersect(sk1);
inter.intersect(sk2);
csk = inter.getResult(true, null);
assertTrue(csk instanceof SingleItemSketch);
csk = inter.getResult(false, null);
assertTrue(csk instanceof SingleItemSketch);
}
@Test
public void union() {
UpdateSketch sk1, sk2;
CompactSketch csk;
int bytes;
//Union on-heap
sk1 = Sketches.updateSketchBuilder().setNominalEntries(32).build();
sk2 = Sketches.updateSketchBuilder().setNominalEntries(32).build();
sk1.update(1);
sk2.update(1);
Union union = Sketches.setOperationBuilder().buildUnion();
union.union(sk1);
union.union(sk2);
csk = union.getResult(true, null);
assertTrue(csk instanceof SingleItemSketch);
//Union off-heap
bytes = Sketches.getMaxUnionBytes(32);
WritableMemory wmem = WritableMemory.writableWrap(new byte[bytes]);
union = Sketches.setOperationBuilder().buildUnion(wmem);
union.union(sk1);
union.union(sk2);
csk = union.getResult(true, null);
assertTrue(csk instanceof SingleItemSketch);
csk = union.getResult(false, null);
assertTrue(csk instanceof SingleItemSketch);
}
@Test
public void aNotB() {
UpdateSketch sk1, sk2;
CompactSketch csk;
//AnotB on-heap
sk1 = Sketches.updateSketchBuilder().setNominalEntries(32).build();
sk2 = Sketches.updateSketchBuilder().setNominalEntries(32).build();
sk1.update(1);
sk2.update(2);
AnotB aNotB = Sketches.setOperationBuilder().buildANotB();
aNotB.setA(sk1);
aNotB.notB(sk2);
csk = aNotB.getResult(true, null, true);
assertTrue(csk instanceof SingleItemSketch);
//not AnotB off-heap form
}
@Test
public void checkHeapifyInstance() {
UpdateSketch sk1 = new UpdateSketchBuilder().build();
sk1.update(1);
UpdateSketch sk2 = new UpdateSketchBuilder().build();
sk2.update(1);
Intersection inter = Sketches.setOperationBuilder().buildIntersection();
inter.intersect(sk1);
inter.intersect(sk2);
WritableMemory wmem = WritableMemory.writableWrap(new byte[16]);
CompactSketch csk = inter.getResult(false, wmem);
assertTrue(csk.isOrdered());
Sketch csk2 = Sketches.heapifySketch(wmem);
assertTrue(csk2 instanceof SingleItemSketch);
println(csk2.toString(true, true, 1, true));
}
@Test
public void checkSingleItemBadFlags() {
final short defaultSeedHash = ThetaUtil.computeSeedHash(ThetaUtil.DEFAULT_UPDATE_SEED);
UpdateSketch sk1 = new UpdateSketchBuilder().build();
sk1.update(1);
WritableMemory wmem = WritableMemory.allocate(16);
sk1.compact(true, wmem);
wmem.putByte(5, (byte) 0); //corrupt flags to zero
try {
SingleItemSketch.heapify(wmem, defaultSeedHash); //fails due to corrupted flags bytes
fail();
} catch (SketchesArgumentException e) { }
}
@Test
public void checkDirectUnionSingleItem2() {
Sketch sk = Sketch.wrap(siSkWoutSiFlag24Bytes());
assertEquals(sk.getEstimate(), 1.0, 0.0);
//println(sk.toString());
sk = Sketch.wrap(siSkWithSiFlag24Bytes());
assertEquals(sk.getEstimate(), 1.0, 0.0);
//println(sk.toString());
}
@Test
public void checkSingleItemCompact() {
UpdateSketch sk1 = new UpdateSketchBuilder().build();
sk1.update(1);
CompactSketch csk = sk1.compact();
assertTrue(csk instanceof SingleItemSketch);
CompactSketch csk2 = csk.compact();
assertEquals(csk, csk2);
CompactSketch csk3 = csk.compact(true, WritableMemory.allocate(16));
assertTrue(csk3 instanceof DirectCompactSketch);
assertEquals(csk2.getCurrentPreambleLongs(), 1);
assertEquals(csk3.getCurrentPreambleLongs(), 1);
}
static final long SiSkPre0WithSiFlag = 0x93cc3a0000030301L;
static final long SiSkPre0WoutSiFlag = 0x93cc1a0000030301L;
static final long Hash = 0x05a186bdcb7df915L;
static Memory siSkWithSiFlag24Bytes() {
int cap = 24; //8 extra bytes
WritableMemory wmem = WritableMemory.allocate(cap);
wmem.putLong(0, SiSkPre0WithSiFlag);
wmem.putLong(8, Hash);
return wmem;
}
static Memory siSkWoutSiFlag24Bytes() {
int cap = 24; //8 extra bytes
WritableMemory wmem = WritableMemory.allocate(cap);
wmem.putLong(0, SiSkPre0WoutSiFlag);
wmem.putLong(8, Hash);
return wmem;
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,446 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/ReadOnlyMemoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.apache.datasketches.common.SketchesReadOnlyException;
import org.apache.datasketches.memory.Memory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ReadOnlyMemoryTest {
@Test
public void wrapAndTryUpdatingUpdateSketch() {
UpdateSketch updateSketch = UpdateSketch.builder().build();
updateSketch.update(1);
Memory mem = Memory.wrap(ByteBuffer.wrap(updateSketch.toByteArray())
.asReadOnlyBuffer().order(ByteOrder.nativeOrder()));
UpdateSketch sketch = (UpdateSketch) Sketch.wrap(mem);
assertEquals(sketch.getEstimate(), 1.0);
boolean thrown = false;
try {
sketch.update(2);
} catch (SketchesReadOnlyException e) {
thrown = true;
}
Assert.assertTrue(thrown);
}
@Test
public void wrapCompactUnorderedSketch() {
UpdateSketch updateSketch = UpdateSketch.builder().build();
updateSketch.update(1);
Memory mem = Memory.wrap(ByteBuffer.wrap(updateSketch.compact(false, null).toByteArray())
.asReadOnlyBuffer().order(ByteOrder.nativeOrder()));
Sketch sketch = Sketch.wrap(mem);
assertEquals(sketch.getEstimate(), 1.0);
}
@Test
public void wrapCompactOrderedSketch() {
UpdateSketch updateSketch = UpdateSketch.builder().build();
updateSketch.update(1);
Memory mem = Memory.wrap(ByteBuffer.wrap(updateSketch.compact().toByteArray())
.asReadOnlyBuffer().order(ByteOrder.nativeOrder()));
Sketch sketch = Sketch.wrap(mem);
assertEquals(sketch.getEstimate(), 1.0);
}
@Test
public void heapifyUpdateSketch() {
UpdateSketch us1 = UpdateSketch.builder().build();
us1.update(1);
Memory mem = Memory.wrap(ByteBuffer.wrap(us1.toByteArray())
.asReadOnlyBuffer().order(ByteOrder.nativeOrder()));
// downcasting is not recommended, for testing only
UpdateSketch us2 = (UpdateSketch) Sketch.heapify(mem);
us2.update(2);
assertEquals(us2.getEstimate(), 2.0);
}
@Test
public void heapifyCompactUnorderedSketch() {
UpdateSketch updateSketch = UpdateSketch.builder().build();
updateSketch.update(1);
Memory mem = Memory.wrap(ByteBuffer.wrap(updateSketch.compact(false, null).toByteArray())
.asReadOnlyBuffer().order(ByteOrder.nativeOrder()));
Sketch sketch = Sketch.heapify(mem);
assertEquals(sketch.getEstimate(), 1.0);
}
@Test
public void heapifyCompactOrderedSketch() {
UpdateSketch updateSketch = UpdateSketch.builder().build();
updateSketch.update(1);
Memory mem = Memory.wrap(ByteBuffer.wrap(updateSketch.compact().toByteArray())
.asReadOnlyBuffer().order(ByteOrder.nativeOrder()));
Sketch sketch = Sketch.heapify(mem);
assertEquals(sketch.getEstimate(), 1.0);
}
@Test
public void heapifyUnion() {
Union u1 = SetOperation.builder().buildUnion();
u1.update(1);
Memory mem = Memory.wrap(ByteBuffer.wrap(u1.toByteArray())
.asReadOnlyBuffer().order(ByteOrder.nativeOrder()));
Union u2 = (Union) SetOperation.heapify(mem);
u2.update(2);
Assert.assertEquals(u2.getResult().getEstimate(), 2.0);
}
@Test
public void wrapAndTryUpdatingUnion() {
Union u1 = SetOperation.builder().buildUnion();
u1.update(1);
Memory mem = Memory.wrap(ByteBuffer.wrap(u1.toByteArray())
.asReadOnlyBuffer().order(ByteOrder.nativeOrder()));
Union u2 = (Union) Sketches.wrapSetOperation(mem);
Union u3 = Sketches.wrapUnion(mem);
Assert.assertEquals(u2.getResult().getEstimate(), 1.0);
Assert.assertEquals(u3.getResult().getEstimate(), 1.0);
try {
u2.update(2);
fail();
} catch (SketchesReadOnlyException e) {
//expected
}
try {
u3.update(2);
fail();
} catch (SketchesReadOnlyException e) {
//expected
}
}
@Test
public void heapifyIntersection() {
UpdateSketch us1 = UpdateSketch.builder().build();
us1.update(1);
us1.update(2);
UpdateSketch us2 = UpdateSketch.builder().build();
us2.update(2);
us2.update(3);
Intersection i1 = SetOperation.builder().buildIntersection();
i1.intersect(us1);
i1.intersect(us2);
Memory mem = Memory.wrap(ByteBuffer.wrap(i1.toByteArray())
.asReadOnlyBuffer().order(ByteOrder.nativeOrder()));
Intersection i2 = (Intersection) SetOperation.heapify(mem);
i2.intersect(us1);
Assert.assertEquals(i2.getResult().getEstimate(), 1.0);
}
@Test
public void wrapIntersection() {
UpdateSketch us1 = UpdateSketch.builder().build();
us1.update(1);
us1.update(2);
UpdateSketch us2 = UpdateSketch.builder().build();
us2.update(2);
us2.update(3);
Intersection i1 = SetOperation.builder().buildIntersection();
i1.intersect(us1);
i1.intersect(us2);
Memory mem = Memory.wrap(ByteBuffer.wrap(i1.toByteArray())
.asReadOnlyBuffer().order(ByteOrder.nativeOrder()));
Intersection i2 = (Intersection) SetOperation.wrap(mem);
Assert.assertEquals(i2.getResult().getEstimate(), 1.0);
boolean thrown = false;
try {
i2.intersect(us1);
} catch (SketchesReadOnlyException e) {
thrown = true;
}
Assert.assertTrue(thrown);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,447 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/BitPackingTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.testng.Assert.assertEquals;
import org.apache.datasketches.common.Util;
import org.testng.annotations.Test;
public class BitPackingTest {
private final static boolean enablePrinting = false;
//for every number of bits from 1 to 63
//generate pseudo-random data, pack, unpack and compare
@Test
public void packUnpackBits() {
for (int bits = 1; bits <= 63; bits++) {
final long mask = (1 << bits) - 1;
long[] input = new long[8];
final long golden64 = Util.INVERSE_GOLDEN_U64;
long value = 0xaa55aa55aa55aa55L; // arbitrary starting value
for (int i = 0; i < 8; ++i) {
input[i] = value & mask;
value += golden64;
}
byte[] bytes = new byte[8 * Long.BYTES];
int bitOffset = 0;
int bufOffset = 0;
for (int i = 0; i < 8; ++i) {
BitPacking.packBits(input[i], bits, bytes, bufOffset, bitOffset);
bufOffset += (bitOffset + bits) >>> 3;
bitOffset = (bitOffset + bits) & 7;
}
long[] output = new long[8];
bitOffset = 0;
bufOffset = 0;
for (int i = 0; i < 8; ++i) {
BitPacking.unpackBits(output, i, bits, bytes, bufOffset, bitOffset);
bufOffset += (bitOffset + bits) >>> 3;
bitOffset = (bitOffset + bits) & 7;
}
for (int i = 0; i < 8; ++i) {
assertEquals(output[i], input[i]);
}
}
}
@Test
public void packUnpackBlocks() {
for (int bits = 1; bits <= 63; bits++) {
if (enablePrinting) { System.out.println("bits " + bits); }
final long mask = (1L << bits) - 1;
long[] input = new long[8];
final long golden64 = Util.INVERSE_GOLDEN_U64;
long value = 0xaa55aa55aa55aa55L; // arbitrary starting value
for (int i = 0; i < 8; ++i) {
input[i] = value & mask;
value += golden64;
}
byte[] bytes = new byte[8 * Long.BYTES];
BitPacking.packBitsBlock8(input, 0, bytes, 0, bits);
if (enablePrinting) { hexDump(bytes); }
long[] output = new long[8];
BitPacking.unpackBitsBlock8(output, 0, bytes, 0, bits);
for (int i = 0; i < 8; ++i) {
if (enablePrinting) { System.out.println("checking value " + i); }
assertEquals(output[i], input[i]);
}
}
}
void hexDump(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
System.out.print(String.format("%02x ", bytes[i]));
}
System.out.println();
}
}
| 2,448 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/HeapifyWrapSerVer1and2Test.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableHandle;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.apache.datasketches.tuple.Util;
import org.testng.annotations.Test;
@SuppressWarnings("resource")
public class HeapifyWrapSerVer1and2Test {
private static final short defaultSeedHash = Util.computeSeedHash(ThetaUtil.DEFAULT_UPDATE_SEED);
@Test
public void checkHeapifyCompactSketchAssumedDefaultSeed() {
final int k = 64;
final long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3csk = sv3usk.compact();
Memory sv3cskMem = Memory.wrap(sv3csk.toByteArray());
CompactSketch sv3cskResult;
//SV3 test
sv3cskResult = Sketches.heapifyCompactSketch(sv3cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV2 test
Memory sv2cskMem = BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed);
sv3cskResult = Sketches.heapifyCompactSketch(sv2cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV1 test
Memory sv1cskMem = BackwardConversions.convertSerVer3toSerVer1(sv3csk);
sv3cskResult = Sketches.heapifyCompactSketch(sv1cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
}
@Test
public void checkHeapifyCompactSketchAssumedDifferentSeed() {
final int k = 64;
final long seed = 128L;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3csk = sv3usk.compact();
Memory sv3cskMem = Memory.wrap(sv3csk.toByteArray());
CompactSketch sv3cskResult;
//SV3 test
sv3cskResult = Sketches.heapifyCompactSketch(sv3cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV2 test
Memory sv2cskMem = BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed);
sv3cskResult = Sketches.heapifyCompactSketch(sv2cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV1 test
Memory sv1cskMem = BackwardConversions.convertSerVer3toSerVer1(sv3csk);
sv3cskResult = Sketches.heapifyCompactSketch(sv1cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), defaultSeedHash);
}
@Test
public void checkHeapifyCompactSketchGivenDefaultSeed() {
final int k = 64;
final long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3csk = sv3usk.compact();
Memory sv3cskMem = Memory.wrap(sv3csk.toByteArray());
CompactSketch sv3cskResult;
//SV3 test
sv3cskResult = Sketches.heapifyCompactSketch(sv3cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV2 test
Memory sv2cskMem = BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed);
sv3cskResult = Sketches.heapifyCompactSketch(sv2cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV1 test
Memory sv1cskMem = BackwardConversions.convertSerVer3toSerVer1(sv3csk);
sv3cskResult = Sketches.heapifyCompactSketch(sv1cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
}
@Test
public void checkHeapifyCompactSketchGivenDifferentSeed() {
final int k = 64;
final long seed = 128L;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3csk = sv3usk.compact();
Memory sv3cskMem = Memory.wrap(sv3csk.toByteArray());
CompactSketch sv3cskResult;
//SV3 test
sv3cskResult = Sketches.heapifyCompactSketch(sv3cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV2 test
Memory sv2cskMem = BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed);
sv3cskResult = Sketches.heapifyCompactSketch(sv2cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV1 test
Memory sv1cskMem = BackwardConversions.convertSerVer3toSerVer1(sv3csk);
sv3cskResult = Sketches.heapifyCompactSketch(sv1cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
}
@Test
public void checkHeapifySketchAssumedDefaultSeed() {
final int k = 64;
final long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3csk = sv3usk.compact();
Memory sv3cskMem = Memory.wrap(sv3csk.toByteArray());
CompactSketch sv3cskResult;
//SV3 test
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv3cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV2 test
Memory sv2cskMem = BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed);
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv2cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV1 test
Memory sv1cskMem = BackwardConversions.convertSerVer3toSerVer1(sv3csk);
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv1cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
}
@Test
public void checkHeapifySketchAssumedDifferentSeed() {
final int k = 64;
final long seed = 128L;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3csk = sv3usk.compact();
Memory sv3cskMem = Memory.wrap(sv3csk.toByteArray());
CompactSketch sv3cskResult;
//SV3 test
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv3cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV2 test
Memory sv2cskMem = BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed);
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv2cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV1 test
Memory sv1cskMem = BackwardConversions.convertSerVer3toSerVer1(sv3csk);
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv1cskMem);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), defaultSeedHash);
}
@Test
public void checkHeapifySketchGivenDefaultSeed() {
final int k = 64;
final long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3csk = sv3usk.compact();
Memory sv3cskMem = Memory.wrap(sv3csk.toByteArray());
CompactSketch sv3cskResult;
//SV3 test
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv3cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV2 test
Memory sv2cskMem = BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed);
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv2cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV1 test
Memory sv1cskMem = BackwardConversions.convertSerVer3toSerVer1(sv3csk);
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv1cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
}
@Test
public void checkHeapifySketchGivenDifferentSeed() {
final int k = 64;
final long seed = 128L;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3csk = sv3usk.compact();
Memory sv3cskMem = Memory.wrap(sv3csk.toByteArray());
CompactSketch sv3cskResult;
//SV3 test
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv3cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV2 test
Memory sv2cskMem = BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed);
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv2cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
//SV1 test
Memory sv1cskMem = BackwardConversions.convertSerVer3toSerVer1(sv3csk);
sv3cskResult = (CompactSketch) Sketches.heapifySketch(sv1cskMem, seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
}
@Test
public void checkWrapCompactSketchAssumedDefaultSeed() {
final int k = 64;
final long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3cskResult;
WritableHandle wh;
CompactSketch sv3csk = sv3usk.compact();
//SV3 test
wh = putOffHeap(Memory.wrap(sv3csk.toByteArray()));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertTrue(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV2 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV1 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer1(sv3csk));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
}
@Test
public void checkWrapCompactSketchAssumedDifferentSeed() {
final int k = 64;
final long seed = 128L;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3cskResult;
WritableHandle wh;
CompactSketch sv3csk = sv3usk.compact();
//SV3 test
wh = putOffHeap(Memory.wrap(sv3csk.toByteArray()));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertTrue(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV2 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV1 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer1(sv3csk));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), defaultSeedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
}
@Test
public void checkWrapCompactSketchGivenDefaultSeed() {
final int k = 64;
final long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3cskResult;
WritableHandle wh;
CompactSketch sv3csk = sv3usk.compact();
//SV3 test
wh = putOffHeap(Memory.wrap(sv3csk.toByteArray()));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertTrue(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV2 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV1 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer1(sv3csk));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {/* ignore */}
}
@Test
public void checkWrapCompactSketchGivenDifferentSeed() {
final int k = 64;
final long seed = 128L;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3cskResult;
WritableHandle wh;
CompactSketch sv3csk = sv3usk.compact();
//SV3 test
wh = putOffHeap(Memory.wrap(sv3csk.toByteArray()));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertTrue(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV2 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV1 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer1(sv3csk));
sv3cskResult = Sketches.wrapCompactSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
}
@Test
public void checkWrapSketchAssumedDefaultSeed() {
final int k = 64;
final long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3cskResult;
WritableHandle wh;
CompactSketch sv3csk = sv3usk.compact();
//SV3 test
wh = putOffHeap(Memory.wrap(sv3csk.toByteArray()));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertTrue(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV2 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV1 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer1(sv3csk));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
}
@Test
public void checkWrapSketchAssumedDifferentSeed() {
final int k = 64;
final long seed = 128L;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3cskResult;
WritableHandle wh;
CompactSketch sv3csk = sv3usk.compact();
//SV3 test
wh = putOffHeap(Memory.wrap(sv3csk.toByteArray()));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertTrue(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV2 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV1 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer1(sv3csk));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable());
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), defaultSeedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
}
@Test
public void checkWrapSketchGivenDefaultSeed() {
final int k = 64;
final long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3cskResult;
WritableHandle wh;
CompactSketch sv3csk = sv3usk.compact();
//SV3 test
wh = putOffHeap(Memory.wrap(sv3csk.toByteArray()));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertTrue(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV2 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV1 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer1(sv3csk));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
}
@Test
public void checkWrapSketchGivenDifferentSeed() {
final int k = 64;
final long seed = 128L;
final short seedHash = Util.computeSeedHash(seed);
UpdateSketch sv3usk = UpdateSketch.builder().setNominalEntries(k).setSeed(seed).build();
for (int i=0; i<k; i++) { sv3usk.update(i); }
CompactSketch sv3cskResult;
WritableHandle wh;
CompactSketch sv3csk = sv3usk.compact();
//SV3 test
wh = putOffHeap(Memory.wrap(sv3csk.toByteArray()));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertTrue(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV2 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer2(sv3csk, seed));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
//SV1 test
wh = putOffHeap(BackwardConversions.convertSerVer3toSerVer1(sv3csk));
sv3cskResult = (CompactSketch) Sketches.wrapSketch(wh.getWritable(), seed);
assertEquals(sv3cskResult.getEstimate(), sv3usk.getEstimate());
assertEquals(sv3cskResult.getSeedHash(), seedHash);
assertFalse(sv3cskResult.isDirect());
try { wh.close(); } catch (Exception e) {}
}
private static WritableHandle putOffHeap(Memory heapMem) {
final long cap = heapMem.getCapacity();
WritableHandle wh = WritableMemory.allocateDirect(cap);
WritableMemory wmem = wh.getWritable();
heapMem.copyTo(0, wmem, 0, cap);
return wh;
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,449 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/JaccardSimilarityTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.theta.JaccardSimilarity.exactlyEqual;
import static org.apache.datasketches.theta.JaccardSimilarity.jaccard;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class JaccardSimilarityTest {
@Test
public void checkNullsEmpties() {
int minK = 1 << 12;
double threshold = 0.95;
println("Check nulls & empties, minK: " + minK + "\t Th: " + threshold);
//check both null
double[] jResults = jaccard(null, null);
boolean state = jResults[1] > threshold;
println("null \t null:\t" + state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(null, null);
assertFalse(state);
UpdateSketch measured = UpdateSketch.builder().setNominalEntries(minK).build();
UpdateSketch expected = UpdateSketch.builder().setNominalEntries(minK).build();
//check both empty
jResults = jaccard(measured, expected);
state = jResults[1] > threshold;
println("empty\tempty:\t" + state + "\t" + jaccardString(jResults));
assertTrue(state);
state = exactlyEqual(measured, expected);
assertTrue(state);
state = exactlyEqual(measured, measured);
assertTrue(state);
//adjust one
expected.update(1);
jResults = jaccard(measured, expected);
state = jResults[1] > threshold;
println("empty\t 1:\t" + state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(measured, expected);
assertFalse(state);
println("");
}
@Test
public void checkExactMode() {
int k = 1 << 12;
int u = k;
double threshold = 0.9999;
println("Exact Mode, minK: " + k + "\t Th: " + threshold);
UpdateSketch measured = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch expected = UpdateSketch.builder().setNominalEntries(k).build();
for (int i = 0; i < (u-1); i++) { //one short
measured.update(i);
expected.update(i);
}
double[] jResults = jaccard(measured, expected);
boolean state = jResults[1] > threshold;
println(state + "\t" + jaccardString(jResults));
assertTrue(state);
state = exactlyEqual(measured, expected);
assertTrue(state);
measured.update(u-1); //now exactly k entries
expected.update(u); //now exactly k entries but differs by one
jResults = jaccard(measured, expected);
state = jResults[1] > threshold;
println(state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(measured, expected);
assertFalse(state);
println("");
}
@Test
public void checkEstMode() {
int k = 1 << 12;
int u = 1 << 20;
double threshold = 0.9999;
println("Estimation Mode, minK: " + k + "\t Th: " + threshold);
UpdateSketch measured = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch expected = UpdateSketch.builder().setNominalEntries(k).build();
for (int i = 0; i < u; i++) {
measured.update(i);
expected.update(i);
}
double[] jResults = jaccard(measured, expected);
boolean state = jResults[1] > threshold;
println(state + "\t" + jaccardString(jResults));
assertTrue(state);
state = exactlyEqual(measured, expected);
assertTrue(state);
for (int i = u; i < (u + 50); i++) { //empirically determined
measured.update(i);
}
jResults = jaccard(measured, expected);
state = jResults[1] >= threshold;
println(state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(measured, expected);
assertFalse(state);
println("");
}
/**
* Enable printing on this test and you will see that the distribution is pretty tight,
* about +/- 0.7%, which is pretty good since the accuracy of the underlying sketch is about
* +/- 1.56%.
*/
@Test
public void checkSimilarity() {
int minK = 1 << 12;
int u1 = 1 << 20;
int u2 = (int) (u1 * 0.95);
double threshold = 0.943;
println("Estimation Mode, minK: " + minK + "\t Th: " + threshold);
UpdateSketch expected = UpdateSketch.builder().setNominalEntries(minK).build();
UpdateSketch measured = UpdateSketch.builder().setNominalEntries(minK).build();
for (int i = 0; i < u1; i++) {
expected.update(i);
}
for (int i = 0; i < u2; i++) {
measured.update(i);
}
double[] jResults = JaccardSimilarity.jaccard(measured, expected);
boolean state = JaccardSimilarity.similarityTest(measured, expected, threshold);
println(state + "\t" + jaccardString(jResults));
assertTrue(state);
//check identity case
state = JaccardSimilarity.similarityTest(measured, measured, threshold);
assertTrue(state);
}
/**
* Enable printing on this test and you will see that the distribution is much looser,
* about +/- 14%. This is due to the fact that intersections loose accuracy as the ratio of
* intersection to the union becomes a small number.
*/
@Test
public void checkDissimilarity() {
int minK = 1 << 12;
int u1 = 1 << 20;
int u2 = (int) (u1 * 0.05);
double threshold = 0.061;
println("Estimation Mode, minK: " + minK + "\t Th: " + threshold);
UpdateSketch expected = UpdateSketch.builder().setNominalEntries(minK).build();
UpdateSketch measured = UpdateSketch.builder().setNominalEntries(minK).build();
for (int i = 0; i < u1; i++) {
expected.update(i);
}
for (int i = 0; i < u2; i++) {
measured.update(i);
}
double[] jResults = JaccardSimilarity.jaccard(measured, expected);
boolean state = JaccardSimilarity.dissimilarityTest(measured, expected, threshold);
println(state + "\t" + jaccardString(jResults));
assertTrue(state);
}
private static String jaccardString(double[] jResults) {
double lb = jResults[0];
double est = jResults[1];
double ub = jResults[2];
return lb + "\t" + est + "\t" + ub + "\t" + ((lb/est) - 1.0) + "\t" + ((ub/est) - 1.0);
}
@Test
public void checkMinK() {
UpdateSketch skA = UpdateSketch.builder().build(); //4096
UpdateSketch skB = UpdateSketch.builder().build(); //4096
skA.update(1);
skB.update(1);
double[] result = JaccardSimilarity.jaccard(skA, skB);
println(result[0] + ", " + result[1] + ", " + result[2]);
for (int i = 1; i < 4096; i++) {
skA.update(i);
skB.update(i);
}
result = JaccardSimilarity.jaccard(skA, skB);
println(result[0] + ", " + result[1] + ", " + result[2]);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,450 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/BackwardConversions.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
/**
* This class converts current compact sketches into prior SerVer 1 and SerVer 2 format for testing.
*
* @author Lee Rhodes
*/
public class BackwardConversions {
/**
* Converts a SerVer3 ordered, heap CompactSketch to a SerVer1 ordered, SetSketch in Memory.
* This is exclusively for testing purposes.
*
* <p>V1 dates from roughly Aug 2014 to about May 2015.
* The library at that time had an early Theta sketch with set operations based on ByteBuffer,
* the Alpha sketch, and an early HLL sketch. It also had an early adaptor for Pig.
* It also had code for the even earlier CountUniqueSketch (for backward compatibility),
* which was the bucket sketch based on Giroire.
*
* <p><b>Serialization Version 1:</b></p>
* <pre>
* Long || Start Byte Adr:
* Adr:
* || 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
* 0 || | Flags | LgResize | LgArr | lgNom | SkType | SerVer | MD_LONGS |
*
* || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
* 1 || | ------------CurCount-------------- |
*
* || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 |
* 2 || --------------------------THETA_LONG------------------------------ |
*
* || | 24 |
* 3 || ----------------------Start of Long Array------------------------ |
* </pre>
*
* <ul>
* <li>The serialization for V1 was always to a compact form (no hash table spaces).</li>
* <li><i>MD_LONGS</i> (Metadata Longs, now Preamble Longs) was always 3.</li>
* <li><i>SerVer</i> is always 1.</li>
* <li>The <i>SkType</i> had three values: 1,2,3 for Alpha, QuickSelect, and SetSketch,
* respectively.</li>
* <li>Bytes <i>lgNom</i> and <i>lgArr</i> were only used by the QS and Alpha sketches.</li>
* <li>V1 <i>LgResize</i> (2 bits) was only relevant to the Alpha and QS sketches.</li>
* <li>The flags byte is in byte 6 (moved to 5 in V2).</li>
* <li>The only flag bits are BE(bit0)=0, and Read-Only(bit1)=1. Read-only was only set for the
* SetSketch.</li>
* <li>There is no seedHash.</li>
* <li>There is no concept of p-sampling so bytes 12-15 of Pre1 are empty.</li>
* <li>The determination of empty is when both curCount=0 and thetaLong = Long.MAX_VALUE.</li>
* </ul>
*
* @param skV3 a SerVer3, ordered CompactSketch
* @return a SerVer1 SetSketch as Memory object.
*/
public static Memory convertSerVer3toSerVer1(final CompactSketch skV3) {
//Check input sketch
final boolean validIn = skV3.isCompact() && skV3.isOrdered() && !skV3.hasMemory();
if (!validIn) {
throw new SketchesArgumentException("Invalid input sketch.");
}
//Build V1 SetSketch in memory
final int curCount = skV3.getRetainedEntries(true);
final WritableMemory wmem = WritableMemory.allocate((3 + curCount) << 3);
//Pre0
wmem.putByte(0, (byte) 3); //preLongs
wmem.putByte(1, (byte) 1); //SerVer
wmem.putByte(2, (byte) 3); //Compact (SetSketch)
wmem.putByte(6, (byte) 2); //Flags ReadOnly, LittleEndian
//Pre1
wmem.putInt(8, curCount);
//Pre2
wmem.putLong(16, skV3.getThetaLong());
//Data
if (curCount > 0) {
wmem.putLongArray(24, skV3.getCache(), 0, curCount);
}
return wmem;
}
/**
* Converts a SerVer3 ordered, heap CompactSketch to a SerVer2 ordered, SetSketch in Memory.
* This is exclusively for testing purposes.
*
* <p>V2 is short-lived and dates from roughly Mid May 2015 to about June 1st, 2015.
* (V3 was created about June 15th in preparation for OpenSource in July.)
* The Theta sketch had evolved but still based on ByteBuffer. There was an UpdateSketch,
* the Alpha sketch, and the early HLL sketch. It also had an early adaptor for Pig.
*
*
* <p><b>Serialization Version 2:</b></p>
* <pre>
* Long || Start Byte Adr:
* Adr:
* || 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
* 0 || Seed Hash | Flags | lgArr | lgNom | SkType | SerVer | MD_LONGS + RR |
*
* || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
* 1 || --------------p-------------- | ---------Retained Entries Count-------- |
*
* || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 |
* 2 || --------------------------THETA_LONG----------------------------------- |
*
* || | 24 |
* 3 || ----------Start of Long Array, could be at 2 or 3 -------------------- |
* </pre>
*
* <ul>
* <li>The serialization for V2 was always to a compact form (no hash table spaces).</li>
* <li><i>MD_LONGS</i> low 6 bits: 1 (Empty), 2 (Exact), 3 (Estimating).</li>
* <li><i>SerVer</i> is always 2.</li>
* <li>The <i>SkType</i> had 4 values: 1,2,3,4; see below.</li>
* <li>Bytes <i>lgNom</i> and <i>lgArr</i> were only used by the QS and Alpha sketches.</li>
* <li>V2 <i>LgResize</i> top 2 bits if byte 0. Only relevant to the Alpha and QS sketches.</li>
* <li>The flags byte is in byte 5.</li>
* <li>The flag bits are specified below.</li>
* <li>There is a seedHash in bytes 6-7.</li>
* <li>p-sampling is bytes 12-15 of Pre1.</li>
* <li>The determination of empty based on the sketch field empty_.</li>
* </ul>
* <pre>
* // Metadata byte Addresses
* private static final int METADATA_LONGS_BYTE = 0; //low 6 bits
* private static final int LG_RESIZE_RATIO_BYTE = 0; //upper 2 bits
* private static final int SER_VER_BYTE = 1;
* private static final int SKETCH_TYPE_BYTE = 2;
* private static final int LG_NOM_LONGS_BYTE = 3;
* private static final int LG_ARR_LONGS_BYTE = 4;
* private static final int FLAGS_BYTE = 5;
* private static final int SEED_HASH_SHORT = 6; //byte 6,7
* private static final int RETAINED_ENTRIES_COUNT_INT = 8; //4 byte aligned
* private static final int P_FLOAT = 12; //4 byte aligned
* private static final int THETA_LONG = 16; //8-byte aligned
* //Backward compatibility
* private static final int FLAGS_BYTE_V1 = 6;
* private static final int LG_RESIZE_RATIO_BYTE_V1 = 5;
*
* // Constant Values
* static final int SER_VER = 2;
* static final int ALPHA_SKETCH = 1; //SKETCH_TYPE_BYTE
* static final int QUICK_SELECT_SKETCH = 2;
* static final int SET_SKETCH = 3;
* static final int BUFFERED_QUICK_SELECT_SKETCH = 4;
* static final String[] SKETCH_TYPE_STR =
* { "None", "AlphaSketch", "QuickSelectSketch", "SetSketch", "BufferedQuickSelectSketch" };
*
* // flag bit masks
* static final int BIG_ENDIAN_FLAG_MASK = 1;
* static final int READ_ONLY_FLAG_MASK = 2;
* static final int EMPTY_FLAG_MASK = 4;
* static final int NO_REBUILD_FLAG_MASK = 8;
* static final int UNORDERED_FLAG_MASK = 16;
* </pre>
*
* @param skV3 a SerVer3, ordered CompactSketch
* @param seed used for checking the seed hash (if one exists).
* @return a SerVer2 SetSketch as Memory object.
*/
public static Memory convertSerVer3toSerVer2(final CompactSketch skV3, final long seed) {
final short seedHash = ThetaUtil.computeSeedHash(seed);
WritableMemory wmem = null;
if (skV3 instanceof EmptyCompactSketch) {
wmem = WritableMemory.allocate(8);
wmem.putByte(0, (byte) 1); //preLongs
wmem.putByte(1, (byte) 2); //SerVer
wmem.putByte(2, (byte) 3); //SetSketch
final byte flags = (byte) 0xE; //NoRebuild, Empty, ReadOnly, LE
wmem.putByte(5, flags);
wmem.putShort(6, seedHash);
return wmem;
}
if (skV3 instanceof SingleItemSketch) {
final SingleItemSketch sis = (SingleItemSketch) skV3;
wmem = WritableMemory.allocate(24);
wmem.putByte(0, (byte) 2); //preLongs
wmem.putByte(1, (byte) 2); //SerVer
wmem.putByte(2, (byte) 3); //SetSketch
final byte flags = (byte) 0xA; //NoRebuild, notEmpty, ReadOnly, LE
wmem.putByte(5, flags);
wmem.putShort(6, seedHash);
wmem.putInt(8, 1);
final long[] arr = sis.getCache();
wmem.putLong(16, arr[0]);
return wmem;
}
//General CompactSketch
final int preLongs = skV3.getCompactPreambleLongs();
final int entries = skV3.getRetainedEntries(true);
final boolean unordered = !(skV3.isOrdered());
final byte flags = (byte) (0xA | (unordered ? 16 : 0)); //Unordered, NoRebuild, notEmpty, ReadOnly, LE
wmem = WritableMemory.allocate((preLongs + entries) << 3);
wmem.putByte(0, (byte) preLongs); //preLongs
wmem.putByte(1, (byte) 2); //SerVer
wmem.putByte(2, (byte) 3); //SetSketch
wmem.putByte(5, flags);
wmem.putShort(6, seedHash);
wmem.putInt(8, entries);
if (preLongs == 3) {
wmem.putLong(16, skV3.getThetaLong());
}
final long[] arr = skV3.getCache();
wmem.putLongArray(preLongs * 8L, arr, 0, entries);
return wmem;
}
}
| 2,451 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/HeapQuickSelectSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.common.Family.QUICKSELECT;
import static org.apache.datasketches.common.ResizeFactor.X1;
import static org.apache.datasketches.common.ResizeFactor.X2;
import static org.apache.datasketches.common.ResizeFactor.X8;
import static org.apache.datasketches.theta.PreambleUtil.FAMILY_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.FLAGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.LG_NOM_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.THETA_LONG;
import static org.apache.datasketches.theta.PreambleUtil.insertLgResizeFactor;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.Arrays;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class HeapQuickSelectSketchTest {
private Family fam_ = QUICKSELECT;
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
int k = 512;
int u = k;
long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setSeed(seed).setNominalEntries(k).build();
HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) {
sk1.update(i);
}
assertFalse(usk.isEmpty());
assertEquals(usk.getEstimate(), u, 0.0);
assertEquals(sk1.getRetainedEntries(false), u);
byte[] byteArray = usk.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(byteArray);
mem.putByte(SER_VER_BYTE, (byte) 0); //corrupt the SerVer byte
Sketch.heapify(mem, seed);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkIllegalSketchID_UpdateSketch() {
int k = 512;
int u = k;
long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setSeed(seed).setNominalEntries(k).build();
HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) {
usk.update(i);
}
assertFalse(usk.isEmpty());
assertEquals(usk.getEstimate(), u, 0.0);
assertEquals(sk1.getRetainedEntries(false), u);
byte[] byteArray = usk.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(byteArray);
mem.putByte(FAMILY_BYTE, (byte) 0); //corrupt the Sketch ID byte
//try to heapify the corruped mem
Sketch.heapify(mem, seed);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifySeedConflict() {
int k = 512;
long seed1 = 1021;
long seed2 = ThetaUtil.DEFAULT_UPDATE_SEED;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setSeed(seed1).setNominalEntries(k).build();
byte[] byteArray = usk.toByteArray();
Memory srcMem = Memory.wrap(byteArray);
Sketch.heapify(srcMem, seed2);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyCorruptLgNomLongs() {
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(16).build();
WritableMemory srcMem = WritableMemory.writableWrap(usk.toByteArray());
srcMem.putByte(LG_NOM_LONGS_BYTE, (byte)2); //corrupt
Sketch.heapify(srcMem, ThetaUtil.DEFAULT_UPDATE_SEED);
}
@Test
public void checkHeapifyByteArrayExact() {
int k = 512;
int u = k;
long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setSeed(seed).setNominalEntries(k).build();
for (int i=0; i<u; i++) {
usk.update(i);
}
int bytes = usk.getCurrentBytes();
byte[] byteArray = usk.toByteArray();
assertEquals(bytes, byteArray.length);
Memory srcMem = Memory.wrap(byteArray);
UpdateSketch usk2 = Sketches.heapifyUpdateSketch(srcMem, seed);
assertEquals(usk2.getEstimate(), u, 0.0);
assertEquals(usk2.getLowerBound(2), u, 0.0);
assertEquals(usk2.getUpperBound(2), u, 0.0);
assertEquals(usk2.isEmpty(), false);
assertEquals(usk2.isEstimationMode(), false);
assertEquals(usk2.getClass().getSimpleName(), usk.getClass().getSimpleName());
assertEquals(usk2.getResizeFactor(), usk.getResizeFactor());
usk2.toString(true, true, 8, true);
}
@Test
public void checkHeapifyByteArrayEstimating() {
int k = 4096;
int u = 2*k;
long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setSeed(seed).setNominalEntries(k).build();
for (int i=0; i<u; i++) {
usk.update(i);
}
double uskEst = usk.getEstimate();
double uskLB = usk.getLowerBound(2);
double uskUB = usk.getUpperBound(2);
assertEquals(usk.isEstimationMode(), true);
byte[] byteArray = usk.toByteArray();
Memory srcMem = Memory.wrap(byteArray);
UpdateSketch usk2 = UpdateSketch.heapify(srcMem, seed);
assertEquals(usk2.getEstimate(), uskEst);
assertEquals(usk2.getLowerBound(2), uskLB);
assertEquals(usk2.getUpperBound(2), uskUB);
assertEquals(usk2.isEmpty(), false);
assertEquals(usk2.isEstimationMode(), true);
assertEquals(usk2.getClass().getSimpleName(), usk.getClass().getSimpleName());
assertEquals(usk2.getResizeFactor(), usk.getResizeFactor());
}
@Test
public void checkHeapifyMemoryEstimating() {
int k = 512;
int u = 2*k; //thus estimating
long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
UpdateSketch sk1 = UpdateSketch.builder().setFamily(fam_).setSeed(seed).setNominalEntries(k).build();
for (int i=0; i<u; i++) {
sk1.update(i);
}
double sk1est = sk1.getEstimate();
double sk1lb = sk1.getLowerBound(2);
double sk1ub = sk1.getUpperBound(2);
assertTrue(sk1.isEstimationMode());
byte[] byteArray = sk1.toByteArray();
Memory mem = Memory.wrap(byteArray);
UpdateSketch sk2 = UpdateSketch.heapify(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
assertEquals(sk2.getEstimate(), sk1est);
assertEquals(sk2.getLowerBound(2), sk1lb);
assertEquals(sk2.getUpperBound(2), sk1ub);
assertEquals(sk2.isEmpty(), false);
assertTrue(sk2.isEstimationMode());
assertEquals(sk2.getClass().getSimpleName(), sk1.getClass().getSimpleName());
}
@Test
public void checkHQStoCompactForms() {
int k = 512;
int u = 4*k; //thus estimating
//boolean compact = false;
int maxBytes = (k << 4) + (Family.QUICKSELECT.getMinPreLongs() << 3);
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setNominalEntries(k).build();
HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks
assertEquals(usk.getClass().getSimpleName(), "HeapQuickSelectSketch");
assertFalse(usk.isDirect());
assertFalse(usk.hasMemory());
assertFalse(usk.isCompact());
assertFalse(usk.isOrdered());
for (int i=0; i<u; i++) {
usk.update(i);
}
sk1.rebuild(); //forces size back to k
//get baseline values
double uskEst = usk.getEstimate();
double uskLB = usk.getLowerBound(2);
double uskUB = usk.getUpperBound(2);
int uskBytes = usk.getCurrentBytes(); //size stored as UpdateSketch
int uskCompBytes = usk.getCompactBytes(); //size stored as CompactSketch
assertEquals(uskBytes, maxBytes);
assertTrue(usk.isEstimationMode());
CompactSketch comp1, comp2, comp3, comp4;
comp1 = usk.compact(false, null);
assertEquals(comp1.getEstimate(), uskEst);
assertEquals(comp1.getLowerBound(2), uskLB);
assertEquals(comp1.getUpperBound(2), uskUB);
assertEquals(comp1.isEmpty(), false);
assertTrue(comp1.isEstimationMode());
assertEquals(comp1.getCompactBytes(), uskCompBytes);
assertEquals(comp1.getClass().getSimpleName(), "HeapCompactSketch");
comp2 = usk.compact(true, null);
assertEquals(comp2.getEstimate(), uskEst);
assertEquals(comp2.getLowerBound(2), uskLB);
assertEquals(comp2.getUpperBound(2), uskUB);
assertEquals(comp2.isEmpty(), false);
assertTrue(comp2.isEstimationMode());
assertEquals(comp2.getCompactBytes(), uskCompBytes);
assertEquals(comp2.getClass().getSimpleName(), "HeapCompactSketch");
byte[] memArr2 = new byte[uskCompBytes];
WritableMemory mem2 = WritableMemory.writableWrap(memArr2); //allocate mem for compact form
comp3 = usk.compact(false, mem2); //load the mem2
assertEquals(comp3.getEstimate(), uskEst);
assertEquals(comp3.getLowerBound(2), uskLB);
assertEquals(comp3.getUpperBound(2), uskUB);
assertEquals(comp3.isEmpty(), false);
assertTrue(comp3.isEstimationMode());
assertEquals(comp3.getCompactBytes(), uskCompBytes);
assertEquals(comp3.getClass().getSimpleName(), "DirectCompactSketch");
mem2.clear();
comp4 = usk.compact(true, mem2);
assertEquals(comp4.getEstimate(), uskEst);
assertEquals(comp4.getLowerBound(2), uskLB);
assertEquals(comp4.getUpperBound(2), uskUB);
assertEquals(comp4.isEmpty(), false);
assertTrue(comp4.isEstimationMode());
assertEquals(comp4.getCompactBytes(), uskCompBytes);
assertEquals(comp4.getClass().getSimpleName(), "DirectCompactSketch");
comp4.toString(false, true, 0, false);
}
@Test
public void checkHQStoCompactEmptyForms() {
int k = 512;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setResizeFactor(X2).setNominalEntries(k).build();
println("lgArr: "+ usk.getLgArrLongs());
//empty
println(usk.toString(false, true, 0, false));
boolean estimating = false;
assertEquals(usk.getClass().getSimpleName(), "HeapQuickSelectSketch");
double uskEst = usk.getEstimate();
double uskLB = usk.getLowerBound(2);
double uskUB = usk.getUpperBound(2);
int currentUSBytes = usk.getCurrentBytes();
assertEquals(currentUSBytes, (32*8) + 24); // clumsy, but a function of RF and TCF
int compBytes = usk.getCompactBytes(); //compact form
assertEquals(compBytes, 8);
assertEquals(usk.isEstimationMode(), estimating);
byte[] arr2 = new byte[compBytes];
WritableMemory mem2 = WritableMemory.writableWrap(arr2);
CompactSketch csk2 = usk.compact(false, mem2);
assertEquals(csk2.getEstimate(), uskEst);
assertEquals(csk2.getLowerBound(2), uskLB);
assertEquals(csk2.getUpperBound(2), uskUB);
assertEquals(csk2.isEmpty(), true);
assertEquals(csk2.isEstimationMode(), estimating);
assertEquals(csk2.getClass().getSimpleName(), "DirectCompactSketch");
CompactSketch csk3 = usk.compact(true, mem2);
println(csk3.toString(false, true, 0, false));
println(csk3.toString());
assertEquals(csk3.getEstimate(), uskEst);
assertEquals(csk3.getLowerBound(2), uskLB);
assertEquals(csk3.getUpperBound(2), uskUB);
assertEquals(csk3.isEmpty(), true);
assertEquals(csk3.isEstimationMode(), estimating);
assertEquals(csk3.getClass().getSimpleName(), "DirectCompactSketch");
}
@Test
public void checkExactMode() {
int k = 4096;
int u = 4096;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setNominalEntries(k).build();
HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) {
usk.update(i);
}
assertEquals(usk.getEstimate(), u, 0.0);
assertEquals(sk1.getRetainedEntries(false), u);
}
@Test
public void checkEstMode() {
int k = 4096;
int u = 2*k;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setResizeFactor(ResizeFactor.X4).setNominalEntries(k).build();
HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) {
usk.update(i);
}
assertTrue(sk1.getRetainedEntries(false) > k); // in general it might be exactly k, but in this case must be greater
}
@Test
public void checkSamplingMode() {
int k = 4096;
int u = k;
float p = (float)0.5;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setP(p).setNominalEntries(k).build();
HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks
for (int i = 0; i < u; i++ ) {
usk.update(i);
}
double p2 = sk1.getP();
double theta = sk1.getTheta();
assertTrue(theta <= p2);
double est = usk.getEstimate();
double kdbl = k;
assertEquals(kdbl, est, kdbl*.05);
double ub = usk.getUpperBound(1);
assertTrue(ub > est);
double lb = usk.getLowerBound(1);
assertTrue(lb < est);
}
@Test
public void checkErrorBounds() {
int k = 512;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setResizeFactor(X1).setNominalEntries(k).build();
//Exact mode
for (int i = 0; i < k; i++ ) {
usk.update(i);
}
double est = usk.getEstimate();
double lb = usk.getLowerBound(2);
double ub = usk.getUpperBound(2);
assertEquals(est, ub, 0.0);
assertEquals(est, lb, 0.0);
//Est mode
int u = 10*k;
for (int i = k; i < u; i++ ) {
usk.update(i);
usk.update(i); //test duplicate rejection
}
est = usk.getEstimate();
lb = usk.getLowerBound(2);
ub = usk.getUpperBound(2);
assertTrue(est <= ub);
assertTrue(est >= lb);
}
//Empty Tests
@Test
public void checkEmptyAndP() {
//virgin, p = 1.0
int k = 1024;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setNominalEntries(k).build();
HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
usk.update(1);
assertEquals(sk1.getRetainedEntries(true), 1);
assertFalse(usk.isEmpty());
//virgin, p = .001
UpdateSketch usk2 = UpdateSketch.builder().setFamily(fam_).setP((float)0.001).setNominalEntries(k).build();
sk1 = (HeapQuickSelectSketch)usk2;
assertTrue(usk2.isEmpty());
usk2.update(1); //will be rejected
assertEquals(sk1.getRetainedEntries(true), 0);
assertFalse(usk2.isEmpty());
double est = usk2.getEstimate();
//println("Est: "+est);
assertEquals(est, 0.0, 0.0); //because curCount = 0
double ub = usk2.getUpperBound(2); //huge because theta is tiny!
//println("UB: "+ub);
assertTrue(ub > 0.0);
double lb = usk2.getLowerBound(2);
assertTrue(lb <= est);
//println("LB: "+lb);
}
@Test
public void checkUpperAndLowerBounds() {
int k = 512;
int u = 2*k;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setResizeFactor(X2).setNominalEntries(k).build();
for (int i = 0; i < u; i++ ) {
usk.update(i);
}
double est = usk.getEstimate();
double ub = usk.getUpperBound(1);
double lb = usk.getLowerBound(1);
assertTrue(ub > est);
assertTrue(lb < est);
}
@Test
public void checkRebuild() {
int k = 16;
int u = 4*k;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setNominalEntries(k).build();
HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) {
usk.update(i);
}
assertFalse(usk.isEmpty());
assertTrue(usk.getEstimate() > 0.0);
assertTrue(sk1.getRetainedEntries(false) > k);
sk1.rebuild();
assertEquals(sk1.getRetainedEntries(false), k);
assertEquals(sk1.getRetainedEntries(true), k);
sk1.rebuild();
assertEquals(sk1.getRetainedEntries(false), k);
assertEquals(sk1.getRetainedEntries(true), k);
}
@Test
public void checkResetAndStartingSubMultiple() {
int k = 1024;
int u = 4*k;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setResizeFactor(X8).setNominalEntries(k).build();
HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i=0; i<u; i++) {
usk.update(i);
}
assertEquals(1 << sk1.getLgArrLongs(), 2*k);
sk1.reset();
ResizeFactor rf = sk1.getResizeFactor();
int subMul = ThetaUtil.startingSubMultiple(11, rf.lg(), 5); //messy
assertEquals(sk1.getLgArrLongs(), subMul);
UpdateSketch usk2 = UpdateSketch.builder().setFamily(fam_).setResizeFactor(ResizeFactor.X1).setNominalEntries(k).build();
sk1 = (HeapQuickSelectSketch)usk2;
for (int i=0; i<u; i++) {
usk2.update(i);
}
assertEquals(1 << sk1.getLgArrLongs(), 2*k);
sk1.reset();
rf = sk1.getResizeFactor();
subMul = ThetaUtil.startingSubMultiple(11, rf.lg(), 5); //messy
assertEquals(sk1.getLgArrLongs(), subMul);
assertNull(sk1.getMemory());
assertFalse(sk1.isOrdered());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkNegativeHashes() {
int k = 512;
UpdateSketch qs = UpdateSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build();
qs.hashUpdate(-1L);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMinReqBytes() {
int k = 16;
UpdateSketch s1 = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i = 0; i < (4 * k); i++) { s1.update(i); }
byte[] byteArray = s1.toByteArray();
byte[] badBytes = Arrays.copyOfRange(byteArray, 0, 24);
Memory mem = Memory.wrap(badBytes);
Sketch.heapify(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkThetaAndLgArrLongs() {
int k = 16;
UpdateSketch s1 = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i = 0; i < k; i++) { s1.update(i); }
byte[] badArray = s1.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(badArray);
PreambleUtil.insertLgArrLongs(mem, 4);
PreambleUtil.insertThetaLong(mem, Long.MAX_VALUE / 2);
Sketch.heapify(mem);
}
@Test
public void checkFamily() {
UpdateSketch sketch = Sketches.updateSketchBuilder().build();
assertEquals(sketch.getFamily(), Family.QUICKSELECT);
}
@Test
public void checkMemSerDeExceptions() {
int k = 1024;
UpdateSketch sk1 = UpdateSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build();
sk1.update(1L); //forces preLongs to 3
byte[] bytearray1 = sk1.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(bytearray1);
long pre0 = mem.getLong(0);
tryBadMem(mem, PREAMBLE_LONGS_BYTE, 2); //Corrupt PreLongs
mem.putLong(0, pre0); //restore
tryBadMem(mem, SER_VER_BYTE, 2); //Corrupt SerVer
mem.putLong(0, pre0); //restore
tryBadMem(mem, FAMILY_BYTE, 1); //Corrupt Family
mem.putLong(0, pre0); //restore
tryBadMem(mem, FLAGS_BYTE, 2); //Corrupt READ_ONLY to true
mem.putLong(0, pre0); //restore
tryBadMem(mem, FAMILY_BYTE, 4); //Corrupt, Family to Union
mem.putLong(0, pre0); //restore
final long origThetaLong = mem.getLong(THETA_LONG);
try {
mem.putLong(THETA_LONG, Long.MAX_VALUE / 2); //Corrupt the theta value
HeapQuickSelectSketch.heapifyInstance(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
fail();
} catch (SketchesArgumentException e) {
//expected
}
mem.putLong(THETA_LONG, origThetaLong); //restore theta
byte[] byteArray2 = new byte[bytearray1.length -1];
WritableMemory mem2 = WritableMemory.writableWrap(byteArray2);
mem.copyTo(0, mem2, 0, mem2.getCapacity());
try {
HeapQuickSelectSketch.heapifyInstance(mem2, ThetaUtil.DEFAULT_UPDATE_SEED);
fail();
} catch (SketchesArgumentException e) {
//expected
}
// force ResizeFactor.X1, but allocated capacity too small
insertLgResizeFactor(mem, ResizeFactor.X1.lg());
UpdateSketch hqss = HeapQuickSelectSketch.heapifyInstance(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
assertEquals(hqss.getResizeFactor(), ResizeFactor.X2); // force-promote to X2
}
private static void tryBadMem(WritableMemory mem, int byteOffset, int byteValue) {
try {
mem.putByte(byteOffset, (byte) byteValue); //Corrupt
HeapQuickSelectSketch.heapifyInstance(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
fail();
} catch (SketchesArgumentException e) {
//expected
}
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,452 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/CompactSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableHandle;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class CompactSketchTest {
@Test
public void checkHeapifyWrap() {
int k = 4096;
final boolean ordered = true;
checkHeapifyWrap(k, 0, ordered);
checkHeapifyWrap(k, 1, ordered);
checkHeapifyWrap(k, 1, !ordered);
checkHeapifyWrap(k, k, ordered); //exact
checkHeapifyWrap(k, k, !ordered); //exact
checkHeapifyWrap(k, 4 * k, ordered); //estimating
checkHeapifyWrap(k, 4 * k, !ordered); //estimating
}
//test combinations of compact ordered/not ordered and heap/direct
public void checkHeapifyWrap(int k, int u, boolean ordered) {
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u; i++) { //populate update sketch
usk.update(i);
}
/****ON HEAP MEMORY -- HEAPIFY****/
CompactSketch refSk = usk.compact(ordered, null);
byte[] barr = refSk.toByteArray();
Memory srcMem = Memory.wrap(barr);
CompactSketch testSk = (CompactSketch) Sketch.heapify(srcMem);
checkByRange(refSk, testSk, u, ordered);
/**Via byte[]**/
byte[] byteArray = refSk.toByteArray();
Memory heapROMem = Memory.wrap(byteArray);
testSk = (CompactSketch)Sketch.heapify(heapROMem);
checkByRange(refSk, testSk, u, ordered);
/****OFF HEAP MEMORY -- WRAP****/
//Prepare Memory for direct
int bytes = usk.getCompactBytes(); //for Compact
try (WritableHandle wdh = WritableMemory.allocateDirect(bytes)) {
WritableMemory directMem = wdh.getWritable();
/**Via CompactSketch.compact**/
refSk = usk.compact(ordered, directMem);
testSk = (CompactSketch)Sketch.wrap(directMem);
checkByRange(refSk, testSk, u, ordered);
/**Via CompactSketch.compact**/
testSk = (CompactSketch)Sketch.wrap(directMem);
checkByRange(refSk, testSk, u, ordered);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
private static void checkByRange(Sketch refSk, Sketch testSk, int u, boolean ordered) {
if (u == 0) {
checkEmptySketch(testSk);
} else if (u == 1) {
checkSingleItemSketch(testSk, refSk);
} else {
checkOtherCompactSketch(testSk, refSk, ordered);
}
}
private static void checkEmptySketch(Sketch testSk) {
assertEquals(testSk.getFamily(), Family.COMPACT);
assertTrue(testSk instanceof EmptyCompactSketch);
assertTrue(testSk.isEmpty());
assertTrue(testSk.isOrdered());
assertNull(testSk.getMemory());
assertFalse(testSk.isDirect());
assertFalse(testSk.hasMemory());
assertEquals(testSk.getSeedHash(), 0);
assertEquals(testSk.getRetainedEntries(true), 0);
assertEquals(testSk.getEstimate(), 0.0, 0.0);
assertEquals(testSk.getCurrentBytes(), 8);
assertNotNull(testSk.iterator());
assertEquals(testSk.toByteArray().length, 8);
assertEquals(testSk.getCache().length, 0);
assertEquals(testSk.getCompactPreambleLongs(), 1);
}
private static void checkSingleItemSketch(Sketch testSk, Sketch refSk) {
assertEquals(testSk.getFamily(), Family.COMPACT);
assertTrue(testSk instanceof SingleItemSketch);
assertFalse(testSk.isEmpty());
assertTrue(testSk.isOrdered());
assertNull(testSk.getMemory());
assertFalse(testSk.isDirect());
assertFalse(testSk.hasMemory());
assertEquals(testSk.getSeedHash(), refSk.getSeedHash());
assertEquals(testSk.getRetainedEntries(true), 1);
assertEquals(testSk.getEstimate(), 1.0, 0.0);
assertEquals(testSk.getCurrentBytes(), 16);
assertNotNull(testSk.iterator());
assertEquals(testSk.toByteArray().length, 16);
assertEquals(testSk.getCache().length, 1);
assertEquals(testSk.getCompactPreambleLongs(), 1);
}
private static void checkOtherCompactSketch(Sketch testSk, Sketch refSk, boolean ordered) {
assertEquals(testSk.getFamily(), Family.COMPACT);
assertFalse(testSk.isEmpty());
assertNotNull(testSk.iterator());
assertEquals(testSk.isOrdered(), ordered);
if (refSk.hasMemory()) {
assertTrue(testSk.hasMemory());
assertNotNull(testSk.getMemory());
if (ordered) {
assertTrue(testSk.isOrdered());
} else {
assertFalse(testSk.isOrdered());
}
if (refSk.isDirect()) {
assertTrue(testSk.isDirect());
} else {
assertFalse(testSk.isDirect());
}
} else {
assertFalse(testSk.hasMemory());
assertTrue(testSk instanceof HeapCompactSketch);
}
assertEquals(testSk.getSeedHash(), refSk.getSeedHash());
assertEquals(testSk.getRetainedEntries(true), refSk.getRetainedEntries(true));
assertEquals(testSk.getEstimate(), refSk.getEstimate(), 0.0);
assertEquals(testSk.getCurrentBytes(), refSk.getCurrentBytes());
assertEquals(testSk.toByteArray().length, refSk.toByteArray().length);
assertEquals(testSk.getCache().length, refSk.getCache().length);
assertEquals(testSk.getCompactPreambleLongs(), refSk.getCompactPreambleLongs());
}
@Test
public void checkDirectSingleItemSketch() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
sk.update(1);
int bytes = sk.getCompactBytes();
WritableMemory wmem = WritableMemory.allocate(bytes);
sk.compact(true, wmem);
Sketch csk2 = Sketch.heapify(wmem);
assertTrue(csk2 instanceof SingleItemSketch);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMemTooSmall() {
int k = 512;
int u = k;
boolean ordered = false;
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u; i++) {
usk.update(i);
}
int bytes = usk.getCompactBytes();
byte[] byteArray = new byte[bytes -8]; //too small
WritableMemory mem = WritableMemory.writableWrap(byteArray);
usk.compact(ordered, mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMemTooSmallOrdered() {
int k = 512;
int u = k;
boolean ordered = true;
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u; i++) {
usk.update(i);
}
int bytes = usk.getCompactBytes();
byte[] byteArray = new byte[bytes -8]; //too small
WritableMemory mem = WritableMemory.writableWrap(byteArray);
usk.compact(ordered, mem);
}
@Test
public void checkCompactCachePart() {
//phony values except for curCount = 0.
long[] result = Intersection.compactCachePart(null, 4, 0, 0L, false);
assertEquals(result.length, 0);
}
//See class State
//Class Name
//Count
//Bytes
private static final boolean COMPACT = true;
private static final boolean EMPTY = true;
private static final boolean DIRECT = true;
private static final boolean MEMORY = true;
private static final boolean ORDERED = true;
private static final boolean ESTIMATION = true;
@Test
/**
* Empty, memory-based Compact sketches are always ordered
*/
public void checkEmptyMemoryCompactSketch() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
WritableMemory wmem1 = WritableMemory.allocate(16);
CompactSketch csk1 = sk.compact(false, wmem1); //the first parameter is ignored when empty
State state1 = new State("DirectCompactSketch", 0, 8, COMPACT, EMPTY, !DIRECT, MEMORY, ORDERED, !ESTIMATION);
state1.check(csk1);
WritableMemory wmem2 = WritableMemory.allocate(16);
CompactSketch csk2 = sk.compact(false, wmem2);
state1.check(csk2);
assertNotEquals(csk1, csk2); //different object because memory is valid
assertFalse(csk1 == csk2);
WritableMemory wmem3 = WritableMemory.allocate(16);
CompactSketch csk3 = csk1.compact(false, wmem3);
state1.check(csk3);
assertNotEquals(csk1, csk3); //different object because memory is valid
assertFalse(csk1 == csk3);
CompactSketch csk4 = csk1.compact(false, null);
State state4 = new State("EmptyCompactSketch", 0, 8, COMPACT, EMPTY, !DIRECT, !MEMORY, ORDERED, !ESTIMATION);
state4.check(csk4);
assertNotEquals(csk1, csk4); //different object because on heap
assertFalse(csk1 == csk4);
CompactSketch cskc = csk1.compact();
state1.check(cskc);
assertEquals(csk1, cskc); //the same object
assertTrue(csk1 == cskc);
}
@Test
/**
* Single-Item, memory-based Compact sketches are always ordered:
*/
public void checkSingleItemMemoryCompactSketch() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
sk.update(1);
WritableMemory wmem1 = WritableMemory.allocate(16);
CompactSketch csk1 = sk.compact(false, wmem1); //the first parameter is ignored when single item
State state1 = new State("DirectCompactSketch", 1, 16, COMPACT, !EMPTY, !DIRECT, MEMORY, ORDERED, !ESTIMATION);
state1.check(csk1);
WritableMemory wmem2 = WritableMemory.allocate(16);
CompactSketch csk2 = sk.compact(false, wmem2); //the first parameter is ignored when single item
state1.check(csk2);
assertNotEquals(csk1, csk2); //different object because memory is valid
assertFalse(csk1 == csk2);
WritableMemory wmem3 = WritableMemory.allocate(16);
CompactSketch csk3 = csk1.compact(false, wmem3);
state1.check(csk3);
assertNotEquals(csk1, csk3); //different object because memory is valid
assertFalse(csk1 == csk3);
CompactSketch cskc = csk1.compact();
state1.check(cskc);
assertEquals(csk1, cskc); //the same object
assertTrue(csk1 == cskc);
}
@Test
public void checkMultipleItemMemoryCompactSketch() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
//This sequence is naturally out-of-order by the hash values.
sk.update(1);
sk.update(2);
sk.update(3);
WritableMemory wmem1 = WritableMemory.allocate(50);
CompactSketch csk1 = sk.compact(true, wmem1);
State state1 = new State("DirectCompactSketch", 3, 40, COMPACT, !EMPTY, !DIRECT, MEMORY, ORDERED, !ESTIMATION);
state1.check(csk1);
WritableMemory wmem2 = WritableMemory.allocate(50);
CompactSketch csk2 = sk.compact(false, wmem2);
State state2 = new State("DirectCompactSketch", 3, 40, COMPACT, !EMPTY, !DIRECT, MEMORY, !ORDERED, !ESTIMATION);
state2.check(csk2);
assertNotEquals(csk1, csk2); //different object because memory is valid
assertFalse(csk1 == csk2);
WritableMemory wmem3 = WritableMemory.allocate(50);
CompactSketch csk3 = csk1.compact(false, wmem3);
state2.check(csk3);
assertNotEquals(csk1, csk3); //different object because memory is valid
assertFalse(csk1 == csk3);
CompactSketch cskc = csk1.compact();
state1.check(cskc);
assertEquals(csk1, cskc); //the same object
assertTrue(csk1 == cskc);
}
@Test
/**
* Empty, heap-based Compact sketches are always ordered.
* All empty, heap-based, compact sketches point to the same static, final constant of 8 bytes.
*/
public void checkEmptyHeapCompactSketch() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
CompactSketch csk1 = sk.compact(false, null); //the first parameter is ignored when empty
State state1 = new State("EmptyCompactSketch", 0, 8, COMPACT, EMPTY, !DIRECT, !MEMORY, ORDERED, !ESTIMATION);
state1.check(csk1);
CompactSketch csk2 = sk.compact(false, null); //the first parameter is ignored when empty
state1.check(csk1);
assertEquals(csk1, csk2);
assertTrue(csk1 == csk2);
CompactSketch csk3 = csk1.compact(false, null);
state1.check(csk3);
assertEquals(csk1, csk3); //The same object
assertTrue(csk1 == csk3);
CompactSketch cskc = csk1.compact();
state1.check(cskc);
assertEquals(csk1, cskc); //The same object
assertTrue(csk1 == cskc);
}
@Test
/**
* Single-Item, heap-based Compact sketches are always ordered.
*/
public void checkSingleItemHeapCompactSketch() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
sk.update(1);
CompactSketch csk1 = sk.compact(false, null); //the first parameter is ignored when single item
State state1 = new State("SingleItemSketch", 1, 16, COMPACT, !EMPTY, !DIRECT, !MEMORY, ORDERED, !ESTIMATION);
state1.check(csk1);
CompactSketch csk2 = sk.compact(false, null); //the first parameter is ignored when single item
state1.check(csk2);
assertNotEquals(csk1, csk2); //calling the compact(boolean, null) method creates a new object
assertFalse(csk1 == csk2);
CompactSketch csk3 = csk1.compact(false, null);
state1.check(csk3);
assertEquals(csk1, csk3); //The same object
assertTrue(csk1 == csk3);
CompactSketch cskc = csk1.compact(); //this, however just returns the same object.
state1.check(csk1);
assertEquals(csk1, cskc); //the same object
assertTrue(csk1 == cskc);
}
@Test
public void checkMultipleItemHeapCompactSketch() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
//This sequence is naturally out-of-order by the hash values.
sk.update(1);
sk.update(2);
sk.update(3);
CompactSketch csk1 = sk.compact(true, null); //creates a new object
State state1 = new State("HeapCompactSketch", 3, 40, COMPACT, !EMPTY, !DIRECT, !MEMORY, ORDERED, !ESTIMATION);
state1.check(csk1);
CompactSketch csk2 = sk.compact(false, null); //creates a new object, unordered
State state2 = new State("HeapCompactSketch", 3, 40, COMPACT, !EMPTY, !DIRECT, !MEMORY, !ORDERED, !ESTIMATION);
state2.check(csk2);
assertNotEquals(csk1, csk2); //order is different and different objects
assertFalse(csk1 == csk2);
CompactSketch csk3 = csk1.compact(true, null);
state1.check(csk3);
assertEquals(csk1, csk3); //the same object because wmem = null and csk1.ordered = dstOrdered
assertTrue(csk1 == csk3);
assertNotEquals(csk2, csk3); //different object because wmem = null and csk2.ordered = false && dstOrdered = true
assertFalse(csk2 == csk3);
CompactSketch cskc = csk1.compact();
state1.check(cskc);
assertEquals(csk1, cskc); //the same object
assertTrue(csk1 == cskc);
}
@Test
public void checkHeapifySingleItemSketch() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
sk.update(1);
int bytes = Sketches.getMaxCompactSketchBytes(2); //1 more than needed
WritableMemory wmem = WritableMemory.allocate(bytes);
sk.compact(false, wmem);
Sketch csk = Sketch.heapify(wmem);
assertTrue(csk instanceof SingleItemSketch);
}
@Test
public void checkHeapifyEmptySketch() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
WritableMemory wmem = WritableMemory.allocate(16); //empty, but extra bytes
CompactSketch csk = sk.compact(false, wmem); //ignores order because it is empty
assertTrue(csk instanceof DirectCompactSketch);
Sketch csk2 = Sketch.heapify(wmem);
assertTrue(csk2 instanceof EmptyCompactSketch);
}
@Test
public void checkGetCache() {
UpdateSketch sk = Sketches.updateSketchBuilder().setP((float).5).build();
sk.update(7);
int bytes = sk.getCompactBytes();
CompactSketch csk = sk.compact(true, WritableMemory.allocate(bytes));
long[] cache = csk.getCache();
assertTrue(cache.length == 0);
}
@Test
public void checkHeapCompactSketchCompact() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
sk.update(1);
sk.update(2);
CompactSketch csk = sk.compact();
assertTrue(csk.isOrdered());
assertEquals(csk.getCurrentPreambleLongs(), 2);
}
/**
* This is checking the empty, single, exact and estimating cases of an off-heap
* sketch to make sure they are being stored properly and to check the new capability
* of calling compact(boolean, Memory) on an already compact sketch. This allows the
* user to be able to change the order and heap status of an already compact sketch.
*/
@Test
public void checkDirectCompactSketchCompact() {
WritableMemory wmem1, wmem2;
CompactSketch csk1, csk2;
int bytes;
int lgK = 6;
//empty
UpdateSketch sk = Sketches.updateSketchBuilder().setLogNominalEntries(lgK).build();
bytes = sk.getCompactBytes(); //empty, 8 bytes
wmem1 = WritableMemory.allocate(bytes);
wmem2 = WritableMemory.allocate(bytes);
csk1 = sk.compact(false, wmem1); //place into memory as unordered
assertTrue(csk1 instanceof DirectCompactSketch);
assertTrue(csk1.isOrdered()); //empty is always ordered
csk2 = csk1.compact(false, wmem2); //set to unordered again
assertTrue(csk2 instanceof DirectCompactSketch);
assertTrue(csk2.isOrdered()); //empty is always ordered
assertTrue(csk2.getSeedHash() == 0); //empty has no seed hash
assertEquals(csk2.getCompactBytes(), 8);
//single
sk.update(1);
bytes = sk.getCompactBytes(); //single, 16 bytes
wmem1 = WritableMemory.allocate(bytes);
wmem2 = WritableMemory.allocate(bytes);
csk1 = sk.compact(false, wmem1); //place into memory as unordered
assertTrue(csk1 instanceof DirectCompactSketch);
assertTrue(csk1.isOrdered()); //single is always ordered
csk2 = csk1.compact(false, wmem2); //set to unordered again
assertTrue(csk2 instanceof DirectCompactSketch);
assertTrue(csk2.isOrdered()); //single is always ordered
assertTrue(csk2.getSeedHash() != 0); //has a seed hash
assertEquals(csk2.getCompactBytes(), 16);
//exact
sk.update(2);
bytes = sk.getCompactBytes(); //exact, 16 bytes preamble, 16 bytes data
wmem1 = WritableMemory.allocate(bytes);
wmem2 = WritableMemory.allocate(bytes);
csk1 = sk.compact(false, wmem1); //place into memory as unordered
assertTrue(csk1 instanceof DirectCompactSketch);
assertFalse(csk1.isOrdered()); //should be unordered
csk2 = csk1.compact(true, wmem2); //set to ordered
assertTrue(csk2 instanceof DirectCompactSketch);
assertTrue(csk2.isOrdered()); //should be ordered
assertTrue(csk2.getSeedHash() != 0); //has a seed hash
assertEquals(csk2.getCompactBytes(), 32);
//estimating
int n = 1 << (lgK + 1);
for (int i = 2; i < n; i++) { sk.update(i); }
bytes = sk.getCompactBytes(); //24 bytes preamble + curCount * 8,
wmem1 = WritableMemory.allocate(bytes);
wmem2 = WritableMemory.allocate(bytes);
csk1 = sk.compact(false, wmem1); //place into memory as unordered
assertTrue(csk1 instanceof DirectCompactSketch);
assertFalse(csk1.isOrdered()); //should be unordered
csk2 = csk1.compact(true, wmem2); //set to ordered
assertTrue(csk2 instanceof DirectCompactSketch);
assertTrue(csk2.isOrdered()); //should be ordered
assertTrue(csk2.getSeedHash() != 0); //has a seed hash
int curCount = csk2.getRetainedEntries();
assertEquals(csk2.getCompactBytes(), 24 + (curCount * 8));
}
@Test
public void serializeDeserializeHeapV4() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
for (int i = 0; i < 10000; i++) {
sk.update(i);
}
CompactSketch cs1 = sk.compact();
byte[] bytes = cs1.toByteArrayCompressed();
CompactSketch cs2 = CompactSketch.heapify(Memory.wrap(bytes));
assertEquals(cs1.getRetainedEntries(), cs2.getRetainedEntries());
HashIterator it1 = cs1.iterator();
HashIterator it2 = cs2.iterator();
while (it1.next() && it2.next()) {
assertEquals(it2.get(), it2.get());
}
}
@Test
public void serializeDeserializeDirectV4() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
for (int i = 0; i < 10000; i++) {
sk.update(i);
}
CompactSketch cs1 = sk.compact(true, WritableMemory.allocate(sk.getCompactBytes()));
byte[] bytes = cs1.toByteArrayCompressed();
CompactSketch cs2 = CompactSketch.wrap(Memory.wrap(bytes));
assertEquals(cs1.getRetainedEntries(), cs2.getRetainedEntries());
HashIterator it1 = cs1.iterator();
HashIterator it2 = cs2.iterator();
while (it1.next() && it2.next()) {
assertEquals(it2.get(), it2.get());
}
}
private static class State {
String classType = null;
int count = 0;
int bytes = 0;
boolean compact = false;
boolean empty = false;
boolean direct = false;
boolean memory = false;
boolean ordered = false;
boolean estimation = false;
State(String classType, int count, int bytes, boolean compact, boolean empty, boolean direct,
boolean memory, boolean ordered, boolean estimation) {
this.classType = classType;
this.count = count;
this.bytes = bytes;
this.compact = compact;
this.empty = empty;
this.direct = direct;
this.memory = memory;
this.ordered = ordered;
this.estimation = estimation;
}
void check(CompactSketch csk) {
assertEquals(csk.getClass().getSimpleName(), classType, "ClassType");
assertEquals(csk.getRetainedEntries(true), count, "curCount");
assertEquals(csk.getCurrentBytes(), bytes, "Bytes" );
assertEquals(csk.isCompact(), compact, "Compact");
assertEquals(csk.isEmpty(), empty, "Empty");
assertEquals(csk.isDirect(), direct, "Direct");
assertEquals(csk.hasMemory(), memory, "Memory");
assertEquals(csk.isOrdered(), ordered, "Ordered");
assertEquals(csk.isEstimationMode(), estimation, "Estimation");
}
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,453 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/ForwardCompatibilityTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.theta.BackwardConversions.convertSerVer3toSerVer1;
import static org.apache.datasketches.theta.BackwardConversions.convertSerVer3toSerVer2;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class ForwardCompatibilityTest {
@Test
public void checkSerVer1_Empty() {
CompactSketch csk = EmptyCompactSketch.getInstance();
Memory srcMem = convertSerVer3toSerVer1(csk);
Sketch sketch = Sketch.heapify(srcMem);
assertEquals(sketch.isEmpty(), true);
assertEquals(sketch.isEstimationMode(), false);
assertEquals(sketch.isDirect(), false);
assertEquals(sketch.hasMemory(), false);
assertEquals(sketch.isCompact(), true);
assertEquals(sketch.isOrdered(), true);
assertTrue(sketch instanceof EmptyCompactSketch);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkSerVer1_badPrelongs() {
CompactSketch csk = EmptyCompactSketch.getInstance();
Memory srcMem = convertSerVer3toSerVer1(csk);
WritableMemory srcMemW = (WritableMemory) srcMem;
srcMemW.putByte(0, (byte) 1);
Sketch.heapify(srcMemW); //throws because bad preLongs
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkSerVer1_tooSmall() {
UpdateSketch usk = Sketches.updateSketchBuilder().build();
usk.update(1);
usk.update(2);
CompactSketch csk = usk.compact(true, null);
Memory srcMem = convertSerVer3toSerVer1(csk);
Memory srcMem2 = srcMem.region(0, srcMem.getCapacity() - 8);
Sketch.heapify(srcMem2); //throws because too small
}
@Test
public void checkSerVer1_1Value() {
UpdateSketch usk = Sketches.updateSketchBuilder().build();
usk.update(1);
CompactSketch csk = usk.compact(true, null);
Memory srcMem = convertSerVer3toSerVer1(csk);
Sketch sketch = Sketch.heapify(srcMem);
assertEquals(sketch.isEmpty(), false);
assertEquals(sketch.isEstimationMode(), false);
assertEquals(sketch.isDirect(), false);
assertEquals(sketch.hasMemory(), false);
assertEquals(sketch.isCompact(), true);
assertEquals(sketch.isOrdered(), true);
assertEquals(sketch.getEstimate(), 1.0);
assertTrue(sketch instanceof SingleItemSketch);
}
@Test
public void checkSerVer2_1PreLong_Empty() {
CompactSketch csk = EmptyCompactSketch.getInstance();
Memory srcMem = convertSerVer3toSerVer2(csk, ThetaUtil.DEFAULT_UPDATE_SEED);
Sketch sketch = Sketch.heapify(srcMem);
assertEquals(sketch.isEmpty(), true);
assertEquals(sketch.isEstimationMode(), false);
assertEquals(sketch.isDirect(), false);
assertEquals(sketch.hasMemory(), false);
assertEquals(sketch.isCompact(), true);
assertEquals(sketch.isOrdered(), true);
assertTrue(sketch instanceof EmptyCompactSketch);
}
@Test
public void checkSerVer2_2PreLongs_Empty() {
UpdateSketch usk = Sketches.updateSketchBuilder().setLogNominalEntries(4).build();
for (int i = 0; i < 2; i++) { usk.update(i); } //exact mode
CompactSketch csk = usk.compact(true, null);
Memory srcMem = convertSerVer3toSerVer2(csk, ThetaUtil.DEFAULT_UPDATE_SEED);
WritableMemory srcMemW = WritableMemory.allocate(16);
srcMem.copyTo(0, srcMemW, 0, 16);
PreambleUtil.setEmpty(srcMemW); //Force
assertTrue(PreambleUtil.isEmptyFlag(srcMemW));
srcMemW.putInt(8, 0); //corrupt curCount = 0
Sketch sketch = Sketch.heapify(srcMemW);
assertTrue(sketch instanceof EmptyCompactSketch);
}
@Test
public void checkSerVer2_3PreLongs_Empty() {
UpdateSketch usk = Sketches.updateSketchBuilder().setLogNominalEntries(4).build();
for (int i = 0; i < 32; i++) { usk.update(i); } //est mode
CompactSketch csk = usk.compact(true, null);
Memory srcMem = convertSerVer3toSerVer2(csk, ThetaUtil.DEFAULT_UPDATE_SEED);
WritableMemory srcMemW = WritableMemory.allocate(24);
srcMem.copyTo(0, srcMemW, 0, 24);
PreambleUtil.setEmpty(srcMemW); //Force
assertTrue(PreambleUtil.isEmptyFlag(srcMemW));
srcMemW.putInt(8, 0); //corrupt curCount = 0
srcMemW.putLong(16, Long.MAX_VALUE); //corrupt to make it look empty
Sketch sketch = Sketch.heapify(srcMemW); //now serVer=3, EmptyCompactSketch
assertTrue(sketch instanceof EmptyCompactSketch);
}
@Test
public void checkSerVer2_2PreLongs_1Value() {
UpdateSketch usk = Sketches.updateSketchBuilder().setLogNominalEntries(4).build();
usk.update(1); //exact mode
CompactSketch csk = usk.compact(true, null);
Memory srcMem = convertSerVer3toSerVer2(csk, ThetaUtil.DEFAULT_UPDATE_SEED);
Sketch sketch = Sketch.heapify(srcMem);
assertEquals(sketch.isEmpty(), false);
assertEquals(sketch.isEstimationMode(), false);
assertEquals(sketch.isDirect(), false);
assertEquals(sketch.hasMemory(), false);
assertEquals(sketch.isCompact(), true);
assertEquals(sketch.isOrdered(), true);
assertTrue(sketch instanceof SingleItemSketch);
}
@Test
public void checkSerVer2_3PreLongs_1Value() {
UpdateSketch usk = Sketches.updateSketchBuilder().setLogNominalEntries(4).build();
for (int i = 0; i < 32; i++) { usk.update(i); } //est mode
CompactSketch csk = usk.compact(true, null);
Memory srcMem = convertSerVer3toSerVer2(csk, ThetaUtil.DEFAULT_UPDATE_SEED);
WritableMemory srcMemW = WritableMemory.allocate(32);
srcMem.copyTo(0, srcMemW, 0, 32);
srcMemW.putInt(8, 1); //corrupt curCount = 1
srcMemW.putLong(16, Long.MAX_VALUE); //corrupt theta to make it look exact
long[] cache = csk.getCache();
srcMemW.putLong(24, cache[0]); //corrupt cache with only one value
Sketch sketch = Sketch.heapify(srcMemW);
assertEquals(sketch.isEmpty(), false);
assertEquals(sketch.isEstimationMode(), false);
assertEquals(sketch.isDirect(), false);
assertEquals(sketch.hasMemory(), false);
assertEquals(sketch.isCompact(), true);
assertEquals(sketch.isOrdered(), true);
assertTrue(sketch instanceof SingleItemSketch);
}
@Test
public void checkSerVer2_3PreLongs_1Value_ThLessthan1() {
UpdateSketch usk = Sketches.updateSketchBuilder().setLogNominalEntries(4).build();
for (int i = 0; i < 32; i++) { usk.update(i); } //est mode
CompactSketch csk = usk.compact(true, null);
Memory srcMem = convertSerVer3toSerVer2(csk, ThetaUtil.DEFAULT_UPDATE_SEED);
WritableMemory srcMemW = WritableMemory.allocate(32);
srcMem.copyTo(0, srcMemW, 0, 32);
srcMemW.putInt(8, 1); //corrupt curCount = 1
//srcMemW.putLong(16, Long.MAX_VALUE);
long[] cache = csk.getCache();
srcMemW.putLong(24, cache[0]); //corrupt cache with only one value
Sketch sketch = Sketch.heapify(srcMemW);
assertEquals(sketch.isEmpty(), false);
assertEquals(sketch.isEstimationMode(), true);
assertEquals(sketch.isDirect(), false);
assertEquals(sketch.hasMemory(), false);
assertEquals(sketch.isCompact(), true);
assertEquals(sketch.isOrdered(), true);
assertTrue(sketch instanceof HeapCompactSketch);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,454 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/HeapIntersectionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.RETAINED_ENTRIES_INT;
import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesStateException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class HeapIntersectionTest {
@Test
public void checkExactIntersectionNoOverlap() {
final int lgK = 9;
final int k = 1<<lgK;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k/2; i++) {
usk1.update(i);
}
for (int i=k/2; i<k; i++) {
usk2.update(i);
}
final Intersection inter = SetOperation.builder().buildIntersection();
inter.intersect(usk1);
inter.intersect(usk2);
CompactSketch rsk1;
final boolean ordered = true;
assertTrue(inter.hasResult());
rsk1 = inter.getResult(!ordered, null);
assertEquals(rsk1.getEstimate(), 0.0);
rsk1 = inter.getResult(ordered, null);
assertEquals(rsk1.getEstimate(), 0.0);
final int bytes = rsk1.getCompactBytes();
final byte[] byteArray = new byte[bytes];
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
rsk1 = inter.getResult(!ordered, mem);
assertEquals(rsk1.getEstimate(), 0.0);
//executed twice to fully exercise the internal state machine
rsk1 = inter.getResult(ordered, mem);
assertEquals(rsk1.getEstimate(), 0.0);
assertFalse(inter.isSameResource(mem));
}
@Test
public void checkExactIntersectionFullOverlap() {
final int lgK = 9;
final int k = 1<<lgK;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
usk1.update(i);
}
for (int i=0; i<k; i++) {
usk2.update(i);
}
final Intersection inter = SetOperation.builder().buildIntersection();
inter.intersect(usk1);
inter.intersect(usk2);
CompactSketch rsk1;
final boolean ordered = true;
rsk1 = inter.getResult(!ordered, null);
assertEquals(rsk1.getEstimate(), k);
rsk1 = inter.getResult(ordered, null);
assertEquals(rsk1.getEstimate(), k);
final int bytes = rsk1.getCompactBytes();
final byte[] byteArray = new byte[bytes];
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
rsk1 = inter.getResult(!ordered, mem); //executed twice to fully exercise the internal state machine
assertEquals(rsk1.getEstimate(), k);
rsk1 = inter.getResult(ordered, mem);
assertEquals(rsk1.getEstimate(), k);
}
@Test
public void checkIntersectionEarlyStop() {
final int lgK = 10;
final int k = 1<<lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u; i++) {
usk1.update(i);
}
for (int i=u/2; i<u + u/2; i++)
{
usk2.update(i);
}
final CompactSketch csk1 = usk1.compact(true, null);
final CompactSketch csk2 = usk2.compact(true, null);
final Intersection inter = SetOperation.builder().buildIntersection();
inter.intersect(csk1);
inter.intersect(csk2);
final CompactSketch rsk1 = inter.getResult(true, null);
final double result = rsk1.getEstimate();
final double sd2err = 2048 * 2.0/Math.sqrt(k);
//println("2048 = " + rsk1.getEstimate() + " +/- " + sd2err);
assertEquals(result, 2048.0, sd2err);
}
//Calling getResult on a virgin Intersect is illegal
@Test(expectedExceptions = SketchesStateException.class)
public void checkNoCall() {
final Intersection inter = SetOperation.builder().buildIntersection();
assertFalse(inter.hasResult());
inter.getResult(false, null);
}
@Test
public void checkIntersectionNull() {
final Intersection inter = SetOperation.builder().buildIntersection();
final UpdateSketch sk = null;
try { inter.intersect(sk); fail(); }
catch (final SketchesArgumentException e) { }
try { inter.intersect(sk, sk); fail(); }
catch (final SketchesArgumentException e) { }
}
@Test
public void check1stCall() {
final int lgK = 9;
final int k = 1<<lgK;
Intersection inter;
UpdateSketch sk;
CompactSketch rsk1;
double est;
//1st call = empty
sk = UpdateSketch.builder().setNominalEntries(k).build(); //empty
inter = SetOperation.builder().buildIntersection();
inter.intersect(sk);
rsk1 = inter.getResult(false, null);
est = rsk1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est); // = 0
//1st call = valid and not empty
sk = UpdateSketch.builder().setNominalEntries(k).build();
sk.update(1);
inter = SetOperation.builder().buildIntersection();
inter.intersect(sk);
rsk1 = inter.getResult(false, null);
est = rsk1.getEstimate();
assertEquals(est, 1.0, 0.0);
println("Est: "+est); // = 1
}
@Test
public void check2ndCallAfterEmpty() {
Intersection inter;
UpdateSketch sk1, sk2;
CompactSketch comp1;
double est;
//1st call = empty
sk1 = UpdateSketch.builder().build(); //empty
inter = SetOperation.builder().buildIntersection();
inter.intersect(sk1);
//2nd call = empty
sk2 = UpdateSketch.builder().build(); //empty
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = empty
sk1 = UpdateSketch.builder().build(); //empty
inter = SetOperation.builder().buildIntersection();
inter.intersect(sk1);
//2nd call = valid and not empty
sk2 = UpdateSketch.builder().build();
sk2.update(1);
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
}
@Test
public void check2ndCallAfterValid() {
Intersection inter;
UpdateSketch sk1, sk2;
CompactSketch comp1;
double est;
//1st call = valid
sk1 = UpdateSketch.builder().build();
sk1.update(1);
inter = SetOperation.builder().buildIntersection();
inter.intersect(sk1);
//2nd call = empty
sk2 = UpdateSketch.builder().build(); //empty
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = valid
sk1 = UpdateSketch.builder().build();
sk1.update(1);
inter = SetOperation.builder().buildIntersection();
inter.intersect(sk1);
//2nd call = valid intersecting
sk2 = UpdateSketch.builder().build(); //empty
sk2.update(1);
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 1.0, 0.0);
println("Est: "+est);
//1st call = valid
sk1 = UpdateSketch.builder().build();
sk1.update(1);
inter = SetOperation.builder().buildIntersection();
inter.intersect(sk1);
//2nd call = valid not intersecting
sk2 = UpdateSketch.builder().build(); //empty
sk2.update(2);
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
}
@Test
public void checkEstimatingIntersect() {
final int lgK = 9;
final int k = 1<<lgK;
Intersection inter;
UpdateSketch sk1, sk2;
CompactSketch comp1;
double est;
//1st call = valid
sk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<2*k; i++)
{
sk1.update(i); //est mode
}
println("sk1: "+sk1.getEstimate());
inter = SetOperation.builder().buildIntersection();
inter.intersect(sk1);
//2nd call = valid intersecting
sk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<2*k; i++)
{
sk2.update(i); //est mode
}
println("sk2: "+sk2.getEstimate());
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertTrue(est > k);
println("Est: "+est);
}
@Test
public void checkHeapifyAndWrap() {
final int lgK = 9;
final int k = 1<<lgK;
final UpdateSketch sk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i = 0; i < 2 * k; i++) {
sk1.update(i); //est mode
}
final CompactSketch cSk1 = sk1.compact(true, null);
final double cSk1Est = cSk1.getEstimate();
println("cSk1Est: " + cSk1Est);
final Intersection inter = SetOperation.builder().buildIntersection();
//1st call with a valid sketch
inter.intersect(cSk1);
final UpdateSketch sk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i = 0; i < 2 * k; i++) {
sk2.update(i); //est mode
}
final CompactSketch cSk2 = sk2.compact(true, null);
final double cSk2Est = cSk2.getEstimate();
println("cSk2Est: " + cSk2Est);
assertEquals(cSk2Est, cSk1Est, 0.0);
//2nd call with identical valid sketch
inter.intersect(cSk2);
final CompactSketch interResultCSk1 = inter.getResult(false, null);
final double inter1est = interResultCSk1.getEstimate();
assertEquals(inter1est, cSk1Est, 0.0);
println("Inter1Est: " + inter1est);
//Put the intersection into memory
final byte[] byteArray = inter.toByteArray();
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
//Heapify
final Intersection inter2 = (Intersection) SetOperation.heapify(mem);
final CompactSketch heapifiedSk = inter2.getResult(false, null);
final double heapifiedEst = heapifiedSk.getEstimate();
assertEquals(heapifiedEst, cSk1Est, 0.0);
println("HeapifiedEst: "+heapifiedEst);
//Wrap
final Intersection inter3 = Sketches.wrapIntersection(mem);
final CompactSketch wrappedSk = inter3.getResult(false, null);
final double wrappedEst = wrappedSk.getEstimate();
assertEquals(wrappedEst, cSk1Est, 0.0);
println("WrappedEst: "+ wrappedEst);
inter.reset();
inter2.reset();
inter3.reset();
}
/**
* This proves that the hash of 7 is < 0.5. This fact will be used in other tests involving P.
*/
@Test
public void checkPreject() {
final UpdateSketch sk = UpdateSketch.builder().setP((float) .5).build();
sk.update(7);
assertEquals(sk.getRetainedEntries(), 0);
}
@Test
public void checkHeapifyVirginEmpty() {
final int lgK = 5;
final int k = 1<<lgK;
Intersection inter1, inter2;
UpdateSketch sk1;
inter1 = SetOperation.builder().buildIntersection(); //virgin heap
Memory srcMem = Memory.wrap(inter1.toByteArray());
inter2 = (Intersection) SetOperation.heapify(srcMem); //virgin heap, independent of inter1
assertFalse(inter1.hasResult());
assertFalse(inter2.hasResult());
//This constructs a sketch with 0 entries and theta < 1.0
sk1 = UpdateSketch.builder().setP((float) .5).setNominalEntries(k).build();
sk1.update(7); //will be rejected by P, see proof above.
//A virgin intersection (empty = false) intersected with a not-empty zero cache sketch
//remains empty = false!, but has a result.
inter1.intersect(sk1);
assertFalse(inter1.isEmpty());
assertTrue(inter1.hasResult());
//note that inter2 is independent
assertFalse(inter2.hasResult());
//test the path via toByteArray, heapify, now in a different state
srcMem = Memory.wrap(inter1.toByteArray());
inter2 = (Intersection) SetOperation.heapify(srcMem); //inter2 identical to inter1
assertFalse(inter2.isEmpty());
assertTrue(inter2.hasResult());
//test the compaction path
final CompactSketch comp = inter2.getResult(true, null);
assertEquals(comp.getRetainedEntries(false), 0);
assertFalse(comp.isEmpty());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadPreambleLongs() {
final Intersection inter1 = SetOperation.builder().buildIntersection(); //virgin
final byte[] byteArray = inter1.toByteArray();
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
//corrupt:
mem.putByte(PREAMBLE_LONGS_BYTE, (byte) 2); //RF not used = 0
SetOperation.heapify(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
final Intersection inter1 = SetOperation.builder().buildIntersection(); //virgin
final byte[] byteArray = inter1.toByteArray();
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
//corrupt:
mem.putByte(SER_VER_BYTE, (byte) 2);
SetOperation.heapify(mem);
}
@Test(expectedExceptions = ClassCastException.class)
public void checkFamilyID() {
final int k = 32;
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
final byte[] byteArray = union.toByteArray();
final Memory mem = Memory.wrap(byteArray);
@SuppressWarnings("unused")
final
Intersection inter1 = (Intersection) SetOperation.heapify(mem); //bad cast
//println(inter1.toString());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadEmptyState() {
final Intersection inter1 = SetOperation.builder().buildIntersection(); //virgin
final UpdateSketch sk = Sketches.updateSketchBuilder().build();
inter1.intersect(sk); //initializes to a true empty intersection.
final byte[] byteArray = inter1.toByteArray();
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
//corrupt:
mem.putInt(RETAINED_ENTRIES_INT, 1);
SetOperation.heapify(mem);
}
@Test
public void checkEmpty() {
final UpdateSketch usk = Sketches.updateSketchBuilder().build();
final Intersection inter = Sketches.setOperationBuilder().buildIntersection();
inter.intersect(usk);
assertTrue(inter.isEmpty());
assertEquals(inter.getRetainedEntries(), 0);
assertTrue(inter.getSeedHash() != 0);
assertEquals(inter.getThetaLong(), Long.MAX_VALUE);
final long[] longArr = inter.getCache(); //only applies to stateful
assertEquals(longArr.length, 0);
}
@Test
public void checkOne() {
final UpdateSketch usk = Sketches.updateSketchBuilder().build();
usk.update(1);
final Intersection inter = Sketches.setOperationBuilder().buildIntersection();
inter.intersect(usk);
assertFalse(inter.isEmpty());
assertEquals(inter.getRetainedEntries(), 1);
assertTrue(inter.getSeedHash() != 0);
assertEquals(inter.getThetaLong(), Long.MAX_VALUE);
final long[] longArr = inter.getCache(); //only applies to stateful
assertEquals(longArr.length, 32);
}
@Test
public void checkGetResult() {
final UpdateSketch sk = Sketches.updateSketchBuilder().build();
final Intersection inter = Sketches.setOperationBuilder().buildIntersection();
inter.intersect(sk);
final CompactSketch csk = inter.getResult();
assertEquals(csk.getCompactBytes(), 8);
}
@Test
public void checkFamily() {
final IntersectionImpl impl = IntersectionImpl.initNewHeapInstance(ThetaUtil.DEFAULT_UPDATE_SEED);
assertEquals(impl.getFamily(), Family.INTERSECTION);
}
@Test
public void checkPairIntersectSimple() {
final UpdateSketch skA = Sketches.updateSketchBuilder().build();
final UpdateSketch skB = Sketches.updateSketchBuilder().build();
final Intersection inter = Sketches.setOperationBuilder().buildIntersection();
final CompactSketch csk = inter.intersect(skA, skB);
assertEquals(csk.getCompactBytes(), 8);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,455 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/HeapAlphaSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.common.Family.ALPHA;
import static org.apache.datasketches.common.ResizeFactor.X1;
import static org.apache.datasketches.common.ResizeFactor.X2;
import static org.apache.datasketches.common.ResizeFactor.X8;
import static org.apache.datasketches.theta.PreambleUtil.FAMILY_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.FLAGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.LG_NOM_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.THETA_LONG;
import static org.apache.datasketches.theta.PreambleUtil.insertLgResizeFactor;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class HeapAlphaSketchTest {
private Family fam_ = ALPHA;
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
int k = 512;
int u = k;
long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setSeed(seed)
.setNominalEntries(k).build();
HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) {
sk1.update(i);
}
assertFalse(usk.isEmpty());
assertEquals(usk.getEstimate(), u, 0.0);
assertEquals(sk1.getRetainedEntries(false), u);
byte[] byteArray = usk.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(byteArray);
mem.putByte(SER_VER_BYTE, (byte) 0); //corrupt the SerVer byte
Sketch.heapify(mem, seed);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkConstructorKtooSmall() {
int k = 256;
UpdateSketch.builder().setFamily(fam_).setNominalEntries(k).build();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkAlphaIncompatibleWithMem() {
WritableMemory mem = WritableMemory.writableWrap(new byte[(512*16)+24]);
UpdateSketch.builder().setFamily(Family.ALPHA).setNominalEntries(512).build(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkIllegalSketchID_UpdateSketch() {
int k = 512;
int u = k;
long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setSeed(seed)
.setNominalEntries(k).build();
HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) {
usk.update(i);
}
assertFalse(usk.isEmpty());
assertEquals(usk.getEstimate(), u, 0.0);
assertEquals(sk1.getRetainedEntries(false), u);
byte[] byteArray = usk.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(byteArray);
mem.putByte(FAMILY_BYTE, (byte) 0); //corrupt the Sketch ID byte
//try to heapify the corruped mem
Sketch.heapify(mem, seed);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifySeedConflict() {
int k = 512;
long seed1 = 1021;
long seed2 = ThetaUtil.DEFAULT_UPDATE_SEED;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setSeed(seed1)
.setNominalEntries(k).build();
byte[] byteArray = usk.toByteArray();
Memory srcMem = Memory.wrap(byteArray);
Sketch.heapify(srcMem, seed2);
}
@Test
public void checkHeapifyByteArrayExact() {
int k = 512;
int u = k;
long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setSeed(seed)
.setNominalEntries(k).build();
for (int i=0; i<u; i++) {
usk.update(i);
}
int bytes = usk.getCurrentBytes();
byte[] byteArray = usk.toByteArray();
assertEquals(bytes, byteArray.length);
Memory srcMem = Memory.wrap(byteArray);
UpdateSketch usk2 = (UpdateSketch)Sketch.heapify(srcMem, seed);
assertEquals(usk2.getEstimate(), u, 0.0);
assertEquals(usk2.getLowerBound(2), u, 0.0);
assertEquals(usk2.getUpperBound(2), u, 0.0);
assertEquals(usk2.isEmpty(), false);
assertEquals(usk2.isEstimationMode(), false);
assertEquals(usk2.getClass().getSimpleName(), usk.getClass().getSimpleName());
usk2.toString(true, true, 8, true);
}
@Test
public void checkHeapifyByteArrayEstimating() {
int k = 4096;
int u = 2*k;
long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setSeed(seed)
.setNominalEntries(k).build();
for (int i=0; i<u; i++) {
usk.update(i);
}
double uskEst = usk.getEstimate();
double uskLB = usk.getLowerBound(2);
double uskUB = usk.getUpperBound(2);
assertEquals(usk.isEstimationMode(), true);
byte[] byteArray = usk.toByteArray();
Memory srcMem = Memory.wrap(byteArray);
UpdateSketch usk2 = (UpdateSketch)Sketch.heapify(srcMem, seed);
assertEquals(usk2.getEstimate(), uskEst);
assertEquals(usk2.getLowerBound(2), uskLB);
assertEquals(usk2.getUpperBound(2), uskUB);
assertEquals(usk2.isEmpty(), false);
assertEquals(usk2.isEstimationMode(), true);
assertEquals(usk2.getClass().getSimpleName(), usk.getClass().getSimpleName());
}
@Test
public void checkHeapifyMemoryEstimating() {
int k = 512;
int u = 2*k; //thus estimating
long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
//int maxBytes = (k << 4) + (Family.ALPHA.getLowPreLongs());
UpdateSketch sk1 = UpdateSketch.builder().setFamily(fam_).setSeed(seed)
.setNominalEntries(k).build();
for (int i=0; i<u; i++) {
sk1.update(i);
}
double sk1est = sk1.getEstimate();
double sk1lb = sk1.getLowerBound(2);
double sk1ub = sk1.getUpperBound(2);
assertTrue(sk1.isEstimationMode());
byte[] byteArray = sk1.toByteArray();
Memory mem = Memory.wrap(byteArray);
UpdateSketch sk2 = (UpdateSketch)Sketch.heapify(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
assertEquals(sk2.getEstimate(), sk1est);
assertEquals(sk2.getLowerBound(2), sk1lb);
assertEquals(sk2.getUpperBound(2), sk1ub);
assertEquals(sk2.isEmpty(), false);
assertTrue(sk2.isEstimationMode());
assertEquals(sk2.getClass().getSimpleName(), sk1.getClass().getSimpleName());
}
@Test
public void checkAlphaToCompactForms() {
int k = 512;
int u = 4*k; //thus estimating
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setNominalEntries(k).build();
HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks
assertEquals(usk.getClass().getSimpleName(), "HeapAlphaSketch");
for (int i=0; i<u; i++) {
usk.update(i);
}
sk1.rebuild(); //removes any dirty values
//Alpha is more accurate, and size is a statistical variable about k
// so cannot be directly compared to the compact forms
assertTrue(usk.isEstimationMode());
CompactSketch comp1, comp2, comp3, comp4;
comp1 = usk.compact(false, null);
//But we can compare the compact forms to each other
double comp1est = comp1.getEstimate();
double comp1lb = comp1.getLowerBound(2);
double comp1ub = comp1.getUpperBound(2);
int comp1bytes = comp1.getCompactBytes();
assertEquals(comp1bytes, comp1.getCurrentBytes());
int comp1curCount = comp1.getRetainedEntries(true);
assertEquals(comp1bytes, (comp1curCount << 3) + (Family.COMPACT.getMaxPreLongs() << 3));
assertEquals(comp1.isEmpty(), false);
assertTrue(comp1.isEstimationMode());
assertEquals(comp1.getClass().getSimpleName(), "HeapCompactSketch");
comp2 = usk.compact(true, null);
assertEquals(comp2.getEstimate(), comp1est);
assertEquals(comp2.getLowerBound(2), comp1lb);
assertEquals(comp2.getUpperBound(2), comp1ub);
assertEquals(comp2.isEmpty(), false);
assertTrue(comp2.isEstimationMode());
assertEquals(comp1bytes, comp2.getCompactBytes());
assertEquals(comp1curCount, comp2.getRetainedEntries(true));
assertEquals(comp2.getClass().getSimpleName(), "HeapCompactSketch");
int bytes = usk.getCompactBytes();
int alphaBytes = sk1.getRetainedEntries(true) * 8;
assertEquals(bytes, alphaBytes + (Family.COMPACT.getMaxPreLongs() << 3));
byte[] memArr2 = new byte[bytes];
WritableMemory mem2 = WritableMemory.writableWrap(memArr2);
comp3 = usk.compact(false, mem2);
assertEquals(comp3.getEstimate(), comp1est);
assertEquals(comp3.getLowerBound(2), comp1lb);
assertEquals(comp3.getUpperBound(2), comp1ub);
assertEquals(comp3.isEmpty(), false);
assertTrue(comp3.isEstimationMode());
assertEquals(comp1bytes, comp3.getCompactBytes());
assertEquals(comp1curCount, comp3.getRetainedEntries(true));
assertEquals(comp3.getClass().getSimpleName(), "DirectCompactSketch");
mem2.clear();
comp4 = usk.compact(true, mem2);
assertEquals(comp4.getEstimate(), comp1est);
assertEquals(comp4.getLowerBound(2), comp1lb);
assertEquals(comp4.getUpperBound(2), comp1ub);
assertEquals(comp4.isEmpty(), false);
assertTrue(comp4.isEstimationMode());
assertEquals(comp1bytes, comp4.getCompactBytes());
assertEquals(comp1curCount, comp4.getRetainedEntries(true));
assertEquals(comp4.getClass().getSimpleName(), "DirectCompactSketch");
}
@Test
public void checkAlphaToCompactEmptyForms() {
int k = 512;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setNominalEntries(k).build();
//empty
usk.toString(false, true, 0, false);
boolean estimating = false;
assertTrue(usk instanceof HeapAlphaSketch);
double uskEst = usk.getEstimate();
double uskLB = usk.getLowerBound(2);
double uskUB = usk.getUpperBound(2);
assertEquals(usk.isEstimationMode(), estimating);
int bytes = usk.getCompactBytes();
assertEquals(bytes, 8); //compact, empty and theta = 1.0
byte[] memArr2 = new byte[bytes];
WritableMemory mem2 = WritableMemory.writableWrap(memArr2);
CompactSketch csk2 = usk.compact(false, mem2);
assertEquals(csk2.getEstimate(), uskEst);
assertEquals(csk2.getLowerBound(2), uskLB);
assertEquals(csk2.getUpperBound(2), uskUB);
assertEquals(csk2.isEmpty(), true);
assertEquals(csk2.isEstimationMode(), estimating);
assertTrue(csk2.isOrdered());
CompactSketch csk3 = usk.compact(true, mem2);
csk3.toString(false, true, 0, false);
csk3.toString();
assertEquals(csk3.getEstimate(), uskEst);
assertEquals(csk3.getLowerBound(2), uskLB);
assertEquals(csk3.getUpperBound(2), uskUB);
assertEquals(csk3.isEmpty(), true);
assertEquals(csk3.isEstimationMode(), estimating);
assertTrue(csk3.isOrdered());
}
@Test
public void checkExactMode() {
int k = 4096;
int u = 4096;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setNominalEntries(k).build();
HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) {
usk.update(i);
}
assertEquals(usk.getEstimate(), u, 0.0);
assertEquals(sk1.getRetainedEntries(false), u);
}
@Test
public void checkEstMode() {
int k = 4096;
int u = 2*k;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setResizeFactor(ResizeFactor.X4)
.setNominalEntries(k).build();
HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) {
usk.update(i);
}
assertTrue(sk1.getRetainedEntries(false) > k);
}
@Test
public void checkSamplingMode() {
int k = 4096;
int u = k;
float p = (float)0.5;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setP(p)
.setNominalEntries(k).build();
HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks
for (int i = 0; i < u; i++ ) {
usk.update(i);
}
double p2 = sk1.getP();
double theta = sk1.getTheta();
assertTrue(theta <= p2);
double est = usk.getEstimate();
double kdbl = k;
assertEquals(kdbl, est, kdbl*.05);
double ub = usk.getUpperBound(1);
assertTrue(ub > est);
double lb = usk.getLowerBound(1);
assertTrue(lb < est);
}
@Test
public void checkErrorBounds() {
int k = 512;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setResizeFactor(X1)
.setNominalEntries(k).build();
//Exact mode
for (int i = 0; i < k; i++ ) {
usk.update(i);
}
double est = usk.getEstimate();
double lb = usk.getLowerBound(2);
double ub = usk.getUpperBound(2);
assertEquals(est, ub, 0.0);
assertEquals(est, lb, 0.0);
//Est mode
int u = 10*k;
for (int i = k; i < u; i++ ) {
usk.update(i);
usk.update(i); //test duplicate rejection
}
est = usk.getEstimate();
lb = usk.getLowerBound(2);
ub = usk.getUpperBound(2);
assertTrue(est <= ub);
assertTrue(est >= lb);
}
//Empty Tests
@Test
public void checkEmptyAndP() {
//virgin, p = 1.0
int k = 1024;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setNominalEntries(k).build();
HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
usk.update(1);
assertEquals(sk1.getRetainedEntries(true), 1);
assertFalse(usk.isEmpty());
//virgin, p = .001
UpdateSketch usk2 = UpdateSketch.builder().setFamily(fam_).setP((float)0.001)
.setNominalEntries(k).build();
sk1 = (HeapAlphaSketch)usk2;
assertTrue(usk2.isEmpty());
usk2.update(1); //will be rejected
assertEquals(sk1.getRetainedEntries(true), 0);
assertFalse(usk2.isEmpty());
double est = usk2.getEstimate();
//println("Est: "+est);
assertEquals(est, 0.0, 0.0); //because curCount = 0
double ub = usk2.getUpperBound(2); //huge because theta is tiny!
//println("UB: "+ub);
assertTrue(ub > 0.0);
double lb = usk2.getLowerBound(2);
assertTrue(lb <= est);
//println("LB: "+lb);
}
@Test
public void checkUpperAndLowerBounds() {
int k = 512;
int u = 2*k;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setResizeFactor(X2)
.setNominalEntries(k).build();
for (int i = 0; i < u; i++ ) {
usk.update(i);
}
double est = usk.getEstimate();
double ub = usk.getUpperBound(1);
double lb = usk.getLowerBound(1);
assertTrue(ub > est);
assertTrue(lb < est);
}
@Test
public void checkRebuild() {
int k = 512;
int u = 4*k;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setNominalEntries(k).build();
HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) {
usk.update(i);
}
assertFalse(usk.isEmpty());
assertTrue(usk.getEstimate() > 0.0);
assertNotEquals(sk1.getRetainedEntries(false), sk1.getRetainedEntries(true));
sk1.rebuild();
assertEquals(sk1.getRetainedEntries(false), sk1.getRetainedEntries(true));
sk1.rebuild();
assertEquals(sk1.getRetainedEntries(false), sk1.getRetainedEntries(true));
}
@Test
public void checkResetAndStartingSubMultiple() {
int k = 1024;
int u = 4*k;
UpdateSketch usk = UpdateSketch.builder().setFamily(fam_).setResizeFactor(X8)
.setNominalEntries(k).build();
HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i=0; i<u; i++) {
usk.update(i);
}
assertEquals(1 << sk1.getLgArrLongs(), 2*k);
sk1.reset();
ResizeFactor rf = sk1.getResizeFactor();
int subMul = ThetaUtil.startingSubMultiple(11, rf.lg(), 5);
assertEquals(sk1.getLgArrLongs(), subMul);
UpdateSketch usk2 = UpdateSketch.builder().setFamily(fam_)
.setResizeFactor(ResizeFactor.X1).setNominalEntries(k).build();
sk1 = (HeapAlphaSketch)usk2;
for (int i=0; i<u; i++) {
usk2.update(i);
}
assertEquals(1 << sk1.getLgArrLongs(), 2*k);
sk1.reset();
rf = sk1.getResizeFactor();
subMul = ThetaUtil.startingSubMultiple(11, rf.lg(), 5);
assertEquals(sk1.getLgArrLongs(), subMul);
assertNull(sk1.getMemory());
assertFalse(sk1.isOrdered());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkLBlimits0() {
int k = 512;
Sketch alpha = UpdateSketch.builder().setFamily(ALPHA).setNominalEntries(k).build();
alpha.getLowerBound(0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkUBlimits0() {
int k = 512;
Sketch alpha = UpdateSketch.builder().setFamily(ALPHA).setNominalEntries(k).build();
alpha.getUpperBound(0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkLBlimits4() {
int k = 512;
Sketch alpha = UpdateSketch.builder().setFamily(ALPHA).setNominalEntries(k).build();
alpha.getLowerBound(4);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkUBlimits4() {
int k = 512;
Sketch alpha = UpdateSketch.builder().setFamily(ALPHA).setNominalEntries(k).build();
alpha.getUpperBound(4);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadPreambleLongs() {
int k = 512;
Sketch alpha = UpdateSketch.builder().setFamily(ALPHA).setNominalEntries(k).build();
byte[] byteArray = alpha.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(byteArray);
//corrupt:
mem.putByte(PREAMBLE_LONGS_BYTE, (byte) 4);
Sketch.heapify(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkNegativeHashes() {
int k = 512;
UpdateSketch alpha = UpdateSketch.builder().setFamily(ALPHA).setNominalEntries(k).build();
alpha.hashUpdate(-1L);
}
@Test
public void checkMemDeSerExceptions() {
int k = 1024;
UpdateSketch sk1 = UpdateSketch.builder().setFamily(ALPHA).setNominalEntries(k).build();
sk1.update(1L); //forces preLongs to 3
byte[] bytearray1 = sk1.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(bytearray1);
long pre0 = mem.getLong(0);
tryBadMem(mem, PREAMBLE_LONGS_BYTE, 2); //Corrupt PreLongs
mem.putLong(0, pre0); //restore
tryBadMem(mem, SER_VER_BYTE, 2); //Corrupt SerVer
mem.putLong(0, pre0); //restore
tryBadMem(mem, FAMILY_BYTE, 2); //Corrupt Family
mem.putLong(0, pre0); //restore
tryBadMem(mem, FLAGS_BYTE, 2); //Corrupt READ_ONLY to true
mem.putLong(0, pre0); //restore
final long origThetaLong = mem.getLong(THETA_LONG);
try {
mem.putLong(THETA_LONG, Long.MAX_VALUE / 2); //Corrupt the theta value
HeapAlphaSketch.heapifyInstance(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
fail();
} catch (SketchesArgumentException e) {
//expected
}
mem.putLong(THETA_LONG, origThetaLong); //restore theta
byte[] byteArray2 = new byte[bytearray1.length -1];
WritableMemory mem2 = WritableMemory.writableWrap(byteArray2);
mem.copyTo(0, mem2, 0, mem2.getCapacity());
try {
HeapAlphaSketch.heapifyInstance(mem2, ThetaUtil.DEFAULT_UPDATE_SEED);
fail();
} catch (SketchesArgumentException e) {
//expected
}
// force ResizeFactor.X1, and allocated capacity too small
insertLgResizeFactor(mem, ResizeFactor.X1.lg());
UpdateSketch usk = HeapAlphaSketch.heapifyInstance(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
ResizeFactor rf = usk.getResizeFactor();
assertEquals(rf, ResizeFactor.X2);//ResizeFactor recovered to X2, which always works.
}
private static void tryBadMem(WritableMemory mem, int byteOffset, int byteValue) {
try {
mem.putByte(byteOffset, (byte) byteValue); //Corrupt
HeapAlphaSketch.heapifyInstance(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
fail();
} catch (SketchesArgumentException e) {
//expected
}
}
@Test
public void checkEnhancedHashInsertOnFullHashTable() {
final HeapAlphaSketch alpha = (HeapAlphaSketch) UpdateSketch.builder()
.setFamily(ALPHA).build();
final int n = 1 << alpha.getLgArrLongs();
final long[] hashTable = new long[n];
for (int i = 1; i <= n; ++i) {
alpha.enhancedHashInsert(hashTable, i);
}
try {
alpha.enhancedHashInsert(hashTable, n + 1);
fail();
} catch (SketchesArgumentException e) {
// expected
}
}
@Test
public void checkFamily() {
UpdateSketch sketch = Sketches.updateSketchBuilder().setFamily(ALPHA).build();
assertEquals(sketch.getFamily(), Family.ALPHA);
}
@SuppressWarnings("unused")
@Test(expectedExceptions = SketchesArgumentException.class)
public void corruptionLgNomLongs() {
final int k = 512;
UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k)
.setFamily(ALPHA).build();
for (int i = 0; i < k; i++) { sketch.update(i); }
byte[] byteArr = sketch.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
wmem.putByte(LG_NOM_LONGS_BYTE, (byte) 8); //corrupt LgNomLongs
UpdateSketch sk = Sketches.heapifyUpdateSketch(wmem);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.err.println(s); //disable here
}
}
| 2,456 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/SketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.common.Family.ALPHA;
import static org.apache.datasketches.common.Family.COMPACT;
import static org.apache.datasketches.common.Family.QUICKSELECT;
import static org.apache.datasketches.common.ResizeFactor.X1;
import static org.apache.datasketches.common.ResizeFactor.X2;
import static org.apache.datasketches.common.ResizeFactor.X4;
import static org.apache.datasketches.common.ResizeFactor.X8;
import static org.apache.datasketches.common.Util.*;
import static org.apache.datasketches.theta.BackwardConversions.convertSerVer3toSerVer1;
import static org.apache.datasketches.theta.BackwardConversions.convertSerVer3toSerVer2;
import static org.apache.datasketches.theta.CompactOperations.computeCompactPreLongs;
import static org.apache.datasketches.theta.PreambleUtil.COMPACT_FLAG_MASK;
import static org.apache.datasketches.theta.PreambleUtil.FLAGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.READ_ONLY_FLAG_MASK;
import static org.apache.datasketches.theta.Sketch.getMaxCompactSketchBytes;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class SketchTest {
@Test
public void checkGetMaxBytesWithEntries() {
assertEquals(getMaxCompactSketchBytes(10), (10*8) + (Family.COMPACT.getMaxPreLongs() << 3) );
}
@Test
public void checkGetCurrentBytes() {
int k = 64;
int lowQSPreLongs = Family.QUICKSELECT.getMinPreLongs();
int lowCompPreLongs = Family.COMPACT.getMinPreLongs();
UpdateSketch sketch = UpdateSketch.builder().setNominalEntries(k).build(); // QS Sketch
assertEquals(sketch.getCurrentPreambleLongs(), lowQSPreLongs);
assertEquals(sketch.getCompactPreambleLongs(), 1); //compact form
assertEquals(sketch.getCurrentDataLongs(), k*2);
assertEquals(sketch.getCurrentBytes(), (k*2*8) + (lowQSPreLongs << 3));
assertEquals(sketch.getCompactBytes(), lowCompPreLongs << 3);
CompactSketch compSk = sketch.compact(false, null);
assertEquals(compSk.getCompactBytes(), 8);
assertEquals(compSk.getCurrentBytes(), 8);
assertEquals(compSk.getCurrentDataLongs(), 0);
int compPreLongs = computeCompactPreLongs(sketch.isEmpty(), sketch.getRetainedEntries(true),
sketch.getThetaLong());
assertEquals(compPreLongs, 1);
for (int i=0; i<k; i++) {
sketch.update(i);
}
assertEquals(sketch.getCurrentPreambleLongs(), lowQSPreLongs);
assertEquals(sketch.getCompactPreambleLongs(), 2); //compact form
assertEquals(sketch.getCurrentDataLongs(), k*2);
assertEquals(sketch.getCurrentBytes(), (k*2*8) + (lowQSPreLongs << 3));
assertEquals(sketch.getCompactBytes(), (k*8) + (2*8)); //compact form //FAILS HERE
compPreLongs = computeCompactPreLongs(sketch.isEmpty(), sketch.getRetainedEntries(true),
sketch.getThetaLong());
assertEquals(compPreLongs, 2);
for (int i = k; i < (2*k); i++) {
sketch.update(i); //go estimation mode
}
int curCount = sketch.getRetainedEntries(true);
assertEquals(sketch.getCurrentPreambleLongs(), lowQSPreLongs);
assertEquals(sketch.getCompactPreambleLongs(), 3); //compact form
assertEquals(sketch.getCurrentDataLongs(), k*2);
assertEquals(sketch.getCurrentBytes(), (k*2*8) + (lowQSPreLongs << 3));
assertEquals(sketch.getCompactBytes(), (curCount*8) + (3*8)); //compact form
compPreLongs = computeCompactPreLongs(sketch.isEmpty(), sketch.getRetainedEntries(true),
sketch.getThetaLong());
assertEquals(compPreLongs, 3);
for (int i=0; i<3; i++) {
int maxCompBytes = Sketch.getMaxCompactSketchBytes(i);
if (i == 0) { assertEquals(maxCompBytes, 8); }
if (i == 1) { assertEquals(maxCompBytes, 16); }
if (i > 1) { assertEquals(maxCompBytes, 24 + (i * 8)); } //assumes maybe estimation mode
}
}
@Test
public void checkBuilder() {
int k = 2048;
int lgK = Integer.numberOfTrailingZeros(k);
long seed = 1021;
float p = (float)0.5;
ResizeFactor rf = X4;
Family fam = Family.ALPHA;
UpdateSketch sk1 = UpdateSketch.builder().setSeed(seed)
.setP(p).setResizeFactor(rf).setFamily(fam).setNominalEntries(k).build();
String nameS1 = sk1.getClass().getSimpleName();
assertEquals(nameS1, "HeapAlphaSketch");
assertEquals(sk1.getLgNomLongs(), lgK);
assertEquals(sk1.getSeed(), seed);
assertEquals(sk1.getP(), p);
//check reset of defaults
sk1 = UpdateSketch.builder().build();
nameS1 = sk1.getClass().getSimpleName();
assertEquals(nameS1, "HeapQuickSelectSketch");
assertEquals(sk1.getLgNomLongs(), Integer.numberOfTrailingZeros(ThetaUtil.DEFAULT_NOMINAL_ENTRIES));
assertEquals(sk1.getSeed(), ThetaUtil.DEFAULT_UPDATE_SEED);
assertEquals(sk1.getP(), (float)1.0);
assertEquals(sk1.getResizeFactor(), ResizeFactor.X8);
}
@Test
public void checkBuilderNonPowerOf2() {
int k = 1000;
UpdateSketch sk = UpdateSketch.builder().setNominalEntries(k).build();
assertEquals(sk.getLgNomLongs(), 10);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBuilderIllegalP() {
float p = (float)1.5;
UpdateSketch.builder().setP(p).build();
}
@Test
public void checkBuilderResizeFactor() {
ResizeFactor rf;
rf = X1;
assertEquals(rf.getValue(), 1);
assertEquals(rf.lg(), 0);
assertEquals(ResizeFactor.getRF(0), X1);
rf = X2;
assertEquals(rf.getValue(), 2);
assertEquals(rf.lg(), 1);
assertEquals(ResizeFactor.getRF(1), X2);
rf = X4;
assertEquals(rf.getValue(), 4);
assertEquals(rf.lg(), 2);
assertEquals(ResizeFactor.getRF(2), X4);
rf = X8;
assertEquals(rf.getValue(), 8);
assertEquals(rf.lg(), 3);
assertEquals(ResizeFactor.getRF(3), X8);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkWrapBadFamily() {
UpdateSketch sketch = UpdateSketch.builder().setFamily(Family.ALPHA).setNominalEntries(1024).build();
byte[] byteArr = sketch.toByteArray();
Memory srcMem = Memory.wrap(byteArr);
Sketch.wrap(srcMem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadFamily() {
UpdateSketch.builder().setFamily(Family.INTERSECTION).setNominalEntries(1024).build();
}
@SuppressWarnings("static-access")
@Test
public void checkSerVer() {
UpdateSketch sketch = UpdateSketch.builder().setNominalEntries(1024).build();
byte[] sketchArray = sketch.toByteArray();
Memory mem = Memory.wrap(sketchArray);
int serVer = Sketch.getSerializationVersion(mem);
assertEquals(serVer, 3);
WritableMemory wmem = WritableMemory.writableWrap(sketchArray);
UpdateSketch sk2 = UpdateSketch.wrap(wmem);
serVer = sk2.getSerializationVersion(wmem);
assertEquals(serVer, 3);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyAlphaCompactExcep() {
int k = 512;
Sketch sketch1 = UpdateSketch.builder().setFamily(ALPHA).setNominalEntries(k).build();
byte[] byteArray = sketch1.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(byteArray);
//corrupt:
mem.setBits(FLAGS_BYTE, (byte) COMPACT_FLAG_MASK);
Sketch.heapify(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyQSCompactExcep() {
int k = 512;
Sketch sketch1 = UpdateSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build();
byte[] byteArray = sketch1.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(byteArray);
//corrupt:
mem.setBits(FLAGS_BYTE, (byte) COMPACT_FLAG_MASK);
Sketch.heapify(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyNotCompactExcep() {
int k = 512;
UpdateSketch sketch1 = UpdateSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build();
int bytes = Sketch.getMaxCompactSketchBytes(0);
byte[] byteArray = new byte[bytes];
WritableMemory mem = WritableMemory.writableWrap(byteArray);
sketch1.compact(false, mem);
//corrupt:
mem.clearBits(FLAGS_BYTE, (byte) COMPACT_FLAG_MASK);
Sketch.heapify(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyFamilyExcep() {
int k = 512;
Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
byte[] byteArray = union.toByteArray();
Memory mem = Memory.wrap(byteArray);
//Improper use
Sketch.heapify(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkWrapAlphaCompactExcep() {
int k = 512;
Sketch sketch1 = UpdateSketch.builder().setFamily(ALPHA).setNominalEntries(k).build();
byte[] byteArray = sketch1.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(byteArray);
//corrupt:
mem.setBits(FLAGS_BYTE, (byte) COMPACT_FLAG_MASK);
Sketch.wrap(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkWrapQSCompactExcep() {
int k = 512;
Sketch sketch1 = UpdateSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build();
byte[] byteArray = sketch1.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(byteArray);
//corrupt:
mem.setBits(FLAGS_BYTE, (byte) COMPACT_FLAG_MASK);
Sketch.wrap(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkWrapNotCompactExcep() {
int k = 512;
UpdateSketch sketch1 = UpdateSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build();
int bytes = Sketch.getMaxCompactSketchBytes(0);
byte[] byteArray = new byte[bytes];
WritableMemory mem = WritableMemory.writableWrap(byteArray);
sketch1.compact(false, mem);
//corrupt:
mem.clearBits(FLAGS_BYTE, (byte) COMPACT_FLAG_MASK);
Sketch.wrap(mem);
}
@Test
public void checkValidSketchID() {
assertFalse(Sketch.isValidSketchID(0));
assertTrue(Sketch.isValidSketchID(ALPHA.getID()));
assertTrue(Sketch.isValidSketchID(QUICKSELECT.getID()));
assertTrue(Sketch.isValidSketchID(COMPACT.getID()));
}
@Test
public void checkWrapToHeapifyConversion1() {
int k = 512;
UpdateSketch sketch1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
sketch1.update(i);
}
double uest1 = sketch1.getEstimate();
CompactSketch csk = sketch1.compact();
Memory v1mem = convertSerVer3toSerVer1(csk);
Sketch csk2 = Sketch.wrap(v1mem);
assertFalse(csk2.isDirect());
assertFalse(csk2.hasMemory());
assertEquals(uest1, csk2.getEstimate(), 0.0);
Memory v2mem = convertSerVer3toSerVer2(csk, ThetaUtil.DEFAULT_UPDATE_SEED);
csk2 = Sketch.wrap(v2mem);
assertFalse(csk2.isDirect());
assertFalse(csk2.hasMemory());
assertEquals(uest1, csk2.getEstimate(), 0.0);
}
@Test
public void checkIsSameResource() {
int k = 16;
WritableMemory mem = WritableMemory.writableWrap(new byte[(k*16) + 24]);
WritableMemory cmem = WritableMemory.writableWrap(new byte[32]);
UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build(mem);
sketch.update(1);
sketch.update(2);
assertTrue(sketch.isSameResource(mem));
DirectCompactSketch dcos = (DirectCompactSketch) sketch.compact(true, cmem);
assertTrue(dcos.isSameResource(cmem));
assertTrue(dcos.isOrdered());
//never create 2 sketches with the same memory, so don't do as I do :)
DirectCompactSketch dcs = (DirectCompactSketch) sketch.compact(false, cmem);
assertTrue(dcs.isSameResource(cmem));
assertFalse(dcs.isOrdered());
Sketch sk = Sketches.updateSketchBuilder().setNominalEntries(k).build();
assertFalse(sk.isSameResource(mem));
}
@Test
public void checkCountLessThanTheta() {
int k = 512;
UpdateSketch sketch1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i = 0; i < (2*k); i++) { sketch1.update(i); }
double theta = sketch1.rebuild().getTheta();
final long thetaLong = (long) (LONG_MAX_VALUE_AS_DOUBLE * theta);
int count = sketch1.getCountLessThanThetaLong(thetaLong);
assertEquals(count, k);
}
private static WritableMemory createCompactSketchMemory(int k, int u) {
UpdateSketch usk = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i = 0; i < u; i++) { usk.update(i); }
int bytes = Sketch.getMaxCompactSketchBytes(usk.getRetainedEntries(true));
WritableMemory wmem = WritableMemory.allocate(bytes);
usk.compact(true, wmem);
return wmem;
}
@Test
public void checkCompactFlagsOnWrap() {
WritableMemory wmem = createCompactSketchMemory(16, 32);
Sketch sk = Sketch.wrap(wmem);
assertTrue(sk instanceof CompactSketch);
int flags = PreambleUtil.extractFlags(wmem);
int flagsNoCompact = flags & ~COMPACT_FLAG_MASK;
PreambleUtil.insertFlags(wmem, flagsNoCompact);
try {
sk = Sketch.wrap(wmem);
fail();
} catch (SketchesArgumentException e) { }
int flagsNoReadOnly = flags & ~READ_ONLY_FLAG_MASK;
PreambleUtil.insertFlags(wmem, flagsNoReadOnly);
try {
sk = Sketch.wrap(wmem);
fail();
} catch (SketchesArgumentException e) { }
PreambleUtil.insertFlags(wmem, flags); //repair to original
PreambleUtil.insertSerVer(wmem, 5);
try {
sk = Sketch.wrap(wmem);
fail();
} catch (SketchesArgumentException e) { }
}
@Test
public void checkCompactSizeAndFlagsOnHeapify() {
WritableMemory wmem = createCompactSketchMemory(16, 32);
Sketch sk = Sketch.heapify(wmem);
assertTrue(sk instanceof CompactSketch);
int flags = PreambleUtil.extractFlags(wmem);
int flagsNoCompact = flags & ~READ_ONLY_FLAG_MASK;
PreambleUtil.insertFlags(wmem, flagsNoCompact);
try {
sk = Sketch.heapify(wmem);
fail();
} catch (SketchesArgumentException e) { }
wmem = WritableMemory.allocate(7);
PreambleUtil.insertSerVer(wmem, 3);
//PreambleUtil.insertFamilyID(wmem, 3);
try {
sk = Sketch.heapify(wmem);
fail();
} catch (SketchesArgumentException e) { }
}
@Test
public void check2Methods() {
int k = 16;
Sketch sk = Sketches.updateSketchBuilder().setNominalEntries(k).build();
int bytes1 = sk.getCompactBytes();
int bytes2 = sk.getCurrentBytes();
assertEquals(bytes1, 8);
assertEquals(bytes2, 280); //32*8 + 24
int retEnt = sk.getRetainedEntries();
assertEquals(retEnt, 0);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,457 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/ExamplesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class ExamplesTest {
@Test
public void simpleCountingSketch() {
final int k = 4096;
final int u = 1000000;
final UpdateSketch sketch = UpdateSketch.builder().setNominalEntries(k).build();
for (int i = 0; i < u; i++) {
sketch.update(i);
}
println(sketch.toString());
}
/*
### HeapQuickSelectSketch SUMMARY:
Nominal Entries (k) : 4096
Estimate : 1002714.745231455
Upper Bound, 95% conf : 1027777.3354974985
Lower Bound, 95% conf : 978261.4472857157
p : 1.0
Theta (double) : 0.00654223948655085
Theta (long) : 60341508738660257
Theta (long, hex : 00d66048519437a1
EstMode? : true
Empty? : false
Resize Factor : 8
Array Size Entries : 8192
Retained Entries : 6560
Update Seed : 9001
Seed Hash : ffff93cc
### END SKETCH SUMMARY
*/
@Test
public void theta2dot0Examples() {
//Load source sketches
final UpdateSketchBuilder bldr = UpdateSketch.builder();
final UpdateSketch skA = bldr.build();
final UpdateSketch skB = bldr.build();
for (int i = 1; i <= 1000; i++) {
skA.update(i);
skB.update(i + 250);
}
//Union Stateless:
Union union = SetOperation.builder().buildUnion();
CompactSketch csk = union.union(skA, skB);
assert csk.getEstimate() == 1250;
//Union Stateful:
union = SetOperation.builder().buildUnion();
union.union(skA); //first call
union.union(skB); //2nd through nth calls
//...
csk = union.getResult();
assert csk.getEstimate() == 1250;
//Intersection Stateless:
Intersection inter = SetOperation.builder().buildIntersection();
csk = inter.intersect(skA, skB);
assert csk.getEstimate() == 750;
//Intersection Stateful:
inter = SetOperation.builder().buildIntersection();
inter.intersect(skA); //first call
inter.intersect(skB); //2nd through nth calls
//...
csk = inter.getResult();
assert csk.getEstimate() == 750;
//AnotB Stateless:
AnotB diff = SetOperation.builder().buildANotB();
csk = diff.aNotB(skA, skB);
assert csk.getEstimate() == 250;
//AnotB Stateful:
diff = SetOperation.builder().buildANotB();
diff.setA(skA); //first call
diff.notB(skB); //2nd through nth calls
//...
csk = diff.getResult(true);
assert csk.getEstimate() == 250;
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //enable/disable here
}
}
| 2,458 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/PairwiseSetOperationsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.testng.annotations.Test;
public class PairwiseSetOperationsTest {
// Intersection
@Test
public void checkIntersectionNoOverlap() {
int lgK = 9;
int k = 1<<lgK;
UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k; i++) { //<k so est is exact
usk1.update(i);
usk2.update(i + k);
}
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Intersection inter = Sketches.setOperationBuilder().buildIntersection();
Sketch rsk = inter.intersect(csk1, csk2);
assertEquals(rsk.getEstimate(), 0.0);
}
@Test
public void checkIntersectionFullOverlap() {
int lgK = 9;
int k = 1<<lgK;
UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
Intersection inter = Sketches.setOperationBuilder().buildIntersection();
for (int i=0; i<k; i++) { //<k so est is exact
usk1.update(i);
usk2.update(i);
}
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Sketch rsk = inter.intersect(csk1, csk2);
assertEquals(rsk.getEstimate(), k, 0.0);
}
@Test
public void checkIntersectionEarlyStop() {
int lgK = 10;
int k = 1<<lgK;
int u = 4*k;
long v = 0;
int trials = 10;
UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
Intersection inter = SetOperation.builder().buildIntersection();
for (int t = 0; t < trials; t++) {
for (int i=0; i<u; i++) {
usk1.update(i + v);
usk2.update(i + v + (u/2));
}
v += u + (u/2);
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Sketch rsk = inter.intersect(csk1, csk2);
double result1 = rsk.getEstimate();
inter.intersect(csk1);
inter.intersect(csk2);
CompactSketch csk3 = inter.getResult(true, null);
double result2 = csk3.getEstimate();
assertEquals(result1, result2, 0.0);
usk1.reset();
usk2.reset();
inter.reset();
}
}
// A and not B
@Test
public void checkAnotBNoOverlap() {
int lgK = 9;
int k = 1<<lgK;
UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
AnotB anotb = Sketches.setOperationBuilder().buildANotB();
for (int i=0; i<k; i++) {
usk1.update(i);
usk2.update(i + k);
}
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Sketch rsk = anotb.aNotB(csk1, csk2);
assertEquals(rsk.getEstimate(), k, 0.0);
}
@Test
public void checkAnotBFullOverlap() {
int lgK = 9;
int k = 1<<lgK;
UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
AnotB anotb = Sketches.setOperationBuilder().buildANotB();
for (int i=0; i<k; i++) {
usk1.update(i);
usk2.update(i);
}
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Sketch rsk = anotb.aNotB(csk1, csk2);
assertEquals(rsk.getEstimate(), 0.0, 0.0);
}
@Test
public void checkAnotBEarlyStop() {
int lgK = 10;
int k = 1<<lgK;
int u = 4*k;
long v = 0;
int trials = 10;
UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
AnotB aNotB = SetOperation.builder().buildANotB();
for (int t = 0; t < trials; t++) {
for (int i=0; i<u; i++) {
usk1.update(i + v);
usk2.update(i + v + (u/2));
}
v += u + (u/2);
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Sketch rsk = aNotB.aNotB(csk1, csk2);
double result1 = rsk.getEstimate();
CompactSketch csk3 = aNotB.aNotB(csk1, csk2);
double result2 = csk3.getEstimate();
assertEquals(result1, result2, 0.0);
usk1.reset();
usk2.reset();
}
}
//Union
@Test
public void checkUnionNoOverlap() {
int lgK = 9;
int k = 1<<lgK;
UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
for (int i=0; i<k; i++) {
usk1.update(i);
usk2.update(i + k);
}
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
union.union(csk1);
union.union(csk2);
Sketch stdSk = union.getResult(true, null);
Sketch rsk = union.union(csk1, csk2);
assertEquals(rsk.getEstimate(), stdSk.getEstimate(), 0.0);
}
@Test
public void checkUnionFullOverlap() {
int lgK = 9;
int k = 1<<lgK;
UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
for (int i=0; i<k; i++) {
usk1.update(i);
usk2.update(i);
}
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Sketch rsk = union.union(csk1, csk2);
assertEquals(rsk.getEstimate(), k, 0.0);
}
@Test
public void checkUnionEarlyStop() {
int lgK = 10;
int k = 1<<lgK;
int u = 4*k;
long v = 0;
int trials = 10;
UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
Union union = SetOperation.builder().setNominalEntries(2 * k).buildUnion();
for (int t = 0; t < trials; t++) {
for (int i=0; i<u; i++) {
usk1.update(i + v);
usk2.update(i + v + (u/2));
}
v += u + (u/2);
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Sketch pwSk = union.union(csk1, csk2);
double pwEst = pwSk.getEstimate();
union.union(csk1);
union.union(csk2);
CompactSketch stdSk = union.getResult(true, null);
double stdEst = stdSk.getEstimate();
assertEquals(pwEst, stdEst, 0.0);
usk1.reset();
usk2.reset();
union.reset();
}
}
@Test
public void checkUnionCutbackToK() {
int lgK = 10;
int k = 1<<lgK;
int u = (3 * k);
UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
for (int i=0; i < u; i++) {
usk1.update(i);
usk2.update(i + (2 * u));
}
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Sketch pwSk = union.union(csk1, csk2);
double pwEst = pwSk.getEstimate();
union.union(csk1);
union.union(csk2);
CompactSketch stdSk = union.getResult(true, null);
double stdEst = stdSk.getEstimate();
assertEquals(pwEst, stdEst, stdEst * .06);
usk1.reset();
usk2.reset();
union.reset();
}
@Test
public void checkNullRules() {
int k = 16;
UpdateSketch uskA = UpdateSketch.builder().setNominalEntries(k).build();
CompactSketch cskAempty = uskA.compact();
CompactSketch cskAnull = null;
AnotB aNotB = SetOperation.builder().buildANotB();
Intersection inter = SetOperation.builder().buildIntersection();
try {
checkIntersection(inter, cskAnull, cskAempty);
fail();
} catch (SketchesArgumentException e) { }
try {
checkIntersection(inter, cskAempty, cskAnull);
fail();
} catch (SketchesArgumentException e) { }
try {
checkIntersection(inter, cskAnull, cskAnull);
fail();
} catch (SketchesArgumentException e) { }
try {
checkAnotB(aNotB, cskAnull, cskAempty);
fail();
} catch (SketchesArgumentException e) { }
try {
checkAnotB(aNotB, cskAempty, cskAnull);
fail();
} catch (SketchesArgumentException e) { }
try {
checkAnotB(aNotB, cskAnull, cskAnull);
fail();
} catch (SketchesArgumentException e) { }
}
@Test
public void checkEmptyValidRules() {
int k = 16;
UpdateSketch uskA = UpdateSketch.builder().setNominalEntries(k).build();
UpdateSketch uskB = UpdateSketch.builder().setNominalEntries(k).build();
CompactSketch cskAempty = uskA.compact();
CompactSketch cskBempty = uskB.compact();
uskA.update(1);
CompactSketch cskA1 = uskA.compact();
Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
AnotB aNotB = SetOperation.builder().buildANotB();
Intersection inter = SetOperation.builder().buildIntersection();
checkSetOps(union, inter, aNotB, cskAempty, cskBempty); //Empty, Empty
checkSetOps(union, inter, aNotB, cskA1, cskBempty); //NotEmpty, Empty
checkSetOps(union, inter, aNotB, cskAempty, cskA1); //Empty, NotEmpty
}
private static void checkSetOps(Union union, Intersection inter, AnotB aNotB,
CompactSketch cskA, CompactSketch cskB) {
checkUnion(union, cskA, cskB);
checkIntersection(inter, cskA, cskB);
checkAnotB(aNotB, cskA, cskB);
}
private static void checkUnion(Union union, CompactSketch cskA, CompactSketch cskB) {
union.union(cskA);
union.union(cskB);
CompactSketch cskU = union.getResult();
CompactSketch cskP = union.union(cskA, cskB);
assertEquals(cskU.isEmpty(), cskP.isEmpty());
union.reset();
}
private static void checkIntersection(Intersection inter, CompactSketch cskA, CompactSketch cskB) {
inter.intersect(cskA);
inter.intersect(cskB);
CompactSketch cskI = inter.getResult();
CompactSketch cskP = inter.intersect(cskA, cskB);
assertEquals(cskI.isEmpty(), cskP.isEmpty());
inter.reset();
}
private static void checkAnotB(AnotB aNotB, CompactSketch cskA, CompactSketch cskB) {
CompactSketch cskD = aNotB.aNotB(cskA, cskB);
CompactSketch cskP = aNotB.aNotB(cskA, cskB);
assertEquals(cskD.isEmpty(), cskP.isEmpty());
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,459 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/ConcurrentDirectQuickSelectSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.theta.ConcurrentHeapQuickSelectSketchTest.waitForBgPropagationToComplete;
import static org.apache.datasketches.theta.PreambleUtil.FAMILY_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.LG_NOM_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.theta.ConcurrentHeapQuickSelectSketchTest.SharedLocal;
import org.apache.datasketches.thetacommon.HashOperations;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author eshcar
*/
public class ConcurrentDirectQuickSelectSketchTest {
private static final long SEED = ThetaUtil.DEFAULT_UPDATE_SEED;
@Test
public void checkDirectCompactConversion() {
int lgK = 9;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
assertTrue(sl.shared instanceof ConcurrentDirectQuickSelectSketch);
assertTrue(sl.shared.compact().isCompact());
}
@Test
public void checkHeapifyMemoryEstimating() {
int lgK = 9;
int k = 1 << lgK;
int u = 2*k;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared; //off-heap
UpdateSketch local = sl.local;
for (int i=0; i<u; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
assertEquals(shared.getClass().getSimpleName(), "ConcurrentDirectQuickSelectSketch");
assertEquals(local.getClass().getSimpleName(), "ConcurrentHeapThetaBuffer");
//This sharedHeap is not linked to the concurrent local buffer
UpdateSketch sharedHeap = Sketches.heapifyUpdateSketch(sl.wmem);
assertEquals(sharedHeap.getClass().getSimpleName(), "HeapQuickSelectSketch");
checkMemoryDirectProxyMethods(local, shared);
checkOtherProxyMethods(local, shared);
checkOtherProxyMethods(local, sharedHeap);
int curCount1 = shared.getRetainedEntries(true);
int curCount2 = sharedHeap.getRetainedEntries(true);
assertEquals(curCount1, curCount2);
long[] cache = sharedHeap.getCache();
long thetaLong = sharedHeap.getThetaLong();
int cacheCount = HashOperations.count(cache, thetaLong);
assertEquals(curCount1, cacheCount);
assertEquals(local.getCurrentPreambleLongs(), 3);
}
@Test
public void checkHeapifyByteArrayExact() {
int lgK = 9;
int k = 1 << lgK;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
for (int i=0; i< k; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
byte[] serArr = shared.toByteArray();
Memory srcMem = Memory.wrap(serArr);
Sketch recoveredShared = Sketch.heapify(srcMem);
//reconstruct to Native/Direct
final int bytes = Sketch.getMaxUpdateSketchBytes(k);
final WritableMemory wmem = WritableMemory.allocate(bytes);
shared = sl.bldr.buildSharedFromSketch((UpdateSketch)recoveredShared, wmem);
UpdateSketch local2 = sl.bldr.buildLocal(shared);
assertEquals(local2.getEstimate(), k, 0.0);
assertEquals(local2.getLowerBound(2), k, 0.0);
assertEquals(local2.getUpperBound(2), k, 0.0);
assertEquals(local2.isEmpty(), false);
assertEquals(local2.isEstimationMode(), false);
assertEquals(recoveredShared.getClass().getSimpleName(), "HeapQuickSelectSketch");
// Run toString just to make sure that we can pull out all of the relevant information.
// That is, this is being run for its side-effect of accessing things.
// If something is wonky, it will generate an exception and fail the test.
local2.toString(true, true, 8, true);
}
@Test
public void checkHeapifyByteArrayEstimating() {
int lgK = 12;
int k = 1 << lgK;
int u = 2*k;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
for (int i=0; i<u; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
double uskEst = local.getEstimate();
double uskLB = local.getLowerBound(2);
double uskUB = local.getUpperBound(2);
assertEquals(local.isEstimationMode(), true);
byte[] serArr = shared.toByteArray();
Memory srcMem = Memory.wrap(serArr);
Sketch recoveredShared = Sketch.heapify(srcMem);
//reconstruct to Native/Direct
final int bytes = Sketch.getMaxUpdateSketchBytes(k);
final WritableMemory wmem = WritableMemory.allocate(bytes);
shared = sl.bldr.buildSharedFromSketch((UpdateSketch)recoveredShared, wmem);
UpdateSketch local2 = sl.bldr.buildLocal(shared);
assertEquals(local2.getEstimate(), uskEst);
assertEquals(local2.getLowerBound(2), uskLB);
assertEquals(local2.getUpperBound(2), uskUB);
assertEquals(local2.isEmpty(), false);
assertEquals(local2.isEstimationMode(), true);
assertEquals(recoveredShared.getClass().getSimpleName(), "HeapQuickSelectSketch");
}
@Test
public void checkWrapMemoryEst() {
int lgK = 9;
int k = 1 << lgK;
int u = 2*k;
//boolean estimating = (u > k);
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
for (int i=0; i<u; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
double sk1est = local.getEstimate();
double sk1lb = local.getLowerBound(2);
double sk1ub = local.getUpperBound(2);
assertTrue(local.isEstimationMode());
Sketch local2 = Sketch.wrap(sl.wmem);
assertEquals(local2.getEstimate(), sk1est);
assertEquals(local2.getLowerBound(2), sk1lb);
assertEquals(local2.getUpperBound(2), sk1ub);
assertEquals(local2.isEmpty(), false);
assertTrue(local2.isEstimationMode());
}
@Test
public void checkDQStoCompactForms() {
int lgK = 9;
int k = 1 << lgK;
int u = 4*k;
//boolean estimating = (u > k);
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertEquals(local.getClass().getSimpleName(), "ConcurrentHeapThetaBuffer");
assertFalse(local.isDirect());
assertTrue(local.hasMemory());
for (int i=0; i<u; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
shared.rebuild(); //forces size back to k
//get baseline values
double localEst = local.getEstimate();
double localLB = local.getLowerBound(2);
double localUB = local.getUpperBound(2);
assertTrue(local.isEstimationMode());
CompactSketch csk;
csk = shared.compact(false, null);
assertEquals(csk.getEstimate(), localEst);
assertEquals(csk.getLowerBound(2), localLB);
assertEquals(csk.getUpperBound(2), localUB);
assertFalse(csk.isEmpty());
assertTrue(csk.isEstimationMode());
assertEquals(csk.getClass().getSimpleName(), "HeapCompactSketch");
csk = shared.compact(true, null);
assertEquals(csk.getEstimate(), localEst);
assertEquals(csk.getLowerBound(2), localLB);
assertEquals(csk.getUpperBound(2), localUB);
assertFalse(csk.isEmpty());
assertTrue(csk.isEstimationMode());
assertEquals(csk.getClass().getSimpleName(), "HeapCompactSketch");
int bytes = shared.getCompactBytes();
assertEquals(bytes, (k*8) + (Family.COMPACT.getMaxPreLongs() << 3));
byte[] memArr2 = new byte[bytes];
WritableMemory mem2 = WritableMemory.writableWrap(memArr2);
csk = shared.compact(false, mem2);
assertEquals(csk.getEstimate(), localEst);
assertEquals(csk.getLowerBound(2), localLB);
assertEquals(csk.getUpperBound(2), localUB);
assertFalse(csk.isEmpty());
assertTrue(csk.isEstimationMode());
assertEquals(csk.getClass().getSimpleName(), "DirectCompactSketch");
mem2.clear();
csk = shared.compact(true, mem2);
assertEquals(csk.getEstimate(), localEst);
assertEquals(csk.getLowerBound(2), localLB);
assertEquals(csk.getUpperBound(2), localUB);
assertFalse(csk.isEmpty());
assertTrue(csk.isEstimationMode());
assertEquals(csk.getClass().getSimpleName(), "DirectCompactSketch");
csk.toString(false, true, 0, false);
}
@Test
public void checkDQStoCompactEmptyForms() {
int lgK = 9;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
//empty
local.toString(false, true, 0, false); //exercise toString
assertEquals(local.getClass().getSimpleName(), "ConcurrentHeapThetaBuffer");
double localEst = local.getEstimate();
double localLB = local.getLowerBound(2);
double localUB = local.getUpperBound(2);
assertFalse(local.isEstimationMode());
int bytes = local.getCompactBytes(); //compact form
assertEquals(bytes, 8);
byte[] memArr2 = new byte[bytes];
WritableMemory mem2 = WritableMemory.writableWrap(memArr2);
CompactSketch csk2 = shared.compact(false, mem2);
assertEquals(csk2.getEstimate(), localEst);
assertEquals(csk2.getLowerBound(2), localLB);
assertEquals(csk2.getUpperBound(2), localUB);
assertTrue(csk2.isEmpty());
assertFalse(csk2.isEstimationMode());
assertTrue(csk2.isOrdered());
CompactSketch csk3 = shared.compact(true, mem2);
csk3.toString(false, true, 0, false);
csk3.toString();
assertEquals(csk3.getEstimate(), localEst);
assertEquals(csk3.getLowerBound(2), localLB);
assertEquals(csk3.getUpperBound(2), localUB);
assertTrue(csk3.isEmpty());
assertFalse(csk3.isEstimationMode());
assertTrue(csk2.isOrdered());
}
@Test
public void checkEstMode() {
int lgK = 12;
int k = 1 << lgK;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
int u = 3*k;
for (int i = 0; i< u; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
assertTrue(shared.getRetainedEntries(false) > k);
}
@Test
public void checkErrorBounds() {
int lgK = 9;
int k = 1 << lgK;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
//Exact mode
for (int i = 0; i < k; i++ ) { local.update(i); }
waitForBgPropagationToComplete(shared);
double est = local.getEstimate();
double lb = local.getLowerBound(2);
double ub = local.getUpperBound(2);
assertEquals(est, ub, 0.0);
assertEquals(est, lb, 0.0);
//Est mode
int u = 100*k;
for (int i = k; i < u; i++ ) {
local.update(i);
local.update(i); //test duplicate rejection
}
waitForBgPropagationToComplete(shared);
est = local.getEstimate();
lb = local.getLowerBound(2);
ub = local.getUpperBound(2);
assertTrue(est <= ub);
assertTrue(est >= lb);
}
@Test
public void checkUpperAndLowerBounds() {
int lgK = 9;
int k = 1 << lgK;
int u = 2*k;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
for (int i = 0; i < u; i++ ) { local.update(i); }
waitForBgPropagationToComplete(shared);
double est = local.getEstimate();
double ub = local.getUpperBound(1);
double lb = local.getLowerBound(1);
assertTrue(ub > est);
assertTrue(lb < est);
}
@Test
public void checkRebuild() {
int lgK = 9;
int k = 1 << lgK;
int u = 4*k;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
for (int i = 0; i< u; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
assertFalse(local.isEmpty());
assertTrue(local.getEstimate() > 0.0);
assertTrue(shared.getRetainedEntries(false) >= k);
shared.rebuild();
assertEquals(shared.getRetainedEntries(false), k);
assertEquals(shared.getRetainedEntries(true), k);
local.rebuild();
assertEquals(shared.getRetainedEntries(false), k);
assertEquals(shared.getRetainedEntries(true), k);
}
@Test
public void checkResetAndStartingSubMultiple() {
int lgK = 9;
int k = 1 << lgK;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
int u = 4*k;
for (int i = 0; i< u; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
assertFalse(local.isEmpty());
assertTrue(shared.getRetainedEntries(false) >= k);
assertTrue(local.getThetaLong() < Long.MAX_VALUE);
shared.reset();
local.reset();
assertTrue(local.isEmpty());
assertEquals(shared.getRetainedEntries(false), 0);
assertEquals(local.getEstimate(), 0.0, 0.0);
assertEquals(local.getThetaLong(), Long.MAX_VALUE);
}
@Test
public void checkExactModeMemoryArr() {
int lgK = 12;
int k = 1 << lgK;
int u = k;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
for (int i = 0; i< u; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
assertEquals(local.getEstimate(), u, 0.0);
assertEquals(shared.getRetainedEntries(false), u);
}
@Test
public void checkEstModeMemoryArr() {
int lgK = 12;
int k = 1 << lgK;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
int u = 3*k;
for (int i = 0; i< u; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
double est = local.getEstimate();
assertTrue((est < (u * 1.05)) && (est > (u * 0.95)));
assertTrue(shared.getRetainedEntries(false) >= k);
}
@Test
public void checkEstModeNativeMemory() {
int lgK = 12;
int k = 1 << lgK;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
int u = 3*k;
for (int i = 0; i< u; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
double est = local.getEstimate();
assertTrue((est < (u * 1.05)) && (est > (u * 0.95)));
assertTrue(shared.getRetainedEntries(false) >= k);
}
@Test
public void checkConstructReconstructFromMemory() {
int lgK = 12;
int k = 1 << lgK;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
int u = 3*k;
for (int i = 0; i< u; i++) { local.update(i); } //force estimation
waitForBgPropagationToComplete(shared);
double est1 = local.getEstimate();
int count1 = shared.getRetainedEntries(false);
assertTrue((est1 < (u * 1.05)) && (est1 > (u * 0.95)));
assertTrue(count1 >= k);
byte[] serArr;
double est2;
serArr = shared.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(serArr);
UpdateSketch recoveredShared = Sketches.wrapUpdateSketch(mem);
//reconstruct to Native/Direct
final int bytes = Sketch.getMaxUpdateSketchBytes(k);
final WritableMemory wmem = WritableMemory.allocate(bytes);
shared = sl.bldr.buildSharedFromSketch(recoveredShared, wmem);
UpdateSketch local2 = sl.bldr.buildLocal(shared);
est2 = local2.getEstimate();
assertEquals(est2, est1, 0.0);
}
@Test
public void checkNullMemory() {
UpdateSketchBuilder bldr = new UpdateSketchBuilder();
final UpdateSketch sk = bldr.build();
for (int i = 0; i < 1000; i++) { sk.update(i); }
final UpdateSketch shared = bldr.buildSharedFromSketch(sk, null);
assertEquals(shared.getRetainedEntries(true), 1000);
assertFalse(shared.hasMemory());
}
//checks Alex's bug where lgArrLongs > lgNomLongs +1.
@Test
public void checkResizeInBigMem() {
int lgK = 14;
int u = 1 << 20;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, SEED, useMem, true, 8); //mem is 8X larger than needed
UpdateSketch local = sl.local;
for (int i = 0; i < u; i++) { local.update(i); }
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkConstructorKtooSmall() {
int lgK = 3;
boolean useMem = true;
new SharedLocal(lgK, lgK, useMem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkConstructorMemTooSmall() {
int lgK = 4;
int k = 1 << lgK;
WritableMemory wmem = WritableMemory.allocate(k/2);
UpdateSketchBuilder bldr = new UpdateSketchBuilder();
bldr.setLogNominalEntries(lgK);
bldr.buildShared(wmem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyIllegalFamilyID_heapify() {
int lgK = 9;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
sl.wmem.putByte(FAMILY_BYTE, (byte) 0); //corrupt the Family ID byte
//try to heapify the corrupted mem
Sketch.heapify(sl.wmem); //catch in Sketch.constructHeapSketch
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadLgNomLongs() {
int lgK = 4;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
sl.wmem.putByte(LG_NOM_LONGS_BYTE, (byte) 3); //Corrupt LgNomLongs byte
DirectQuickSelectSketch.writableWrap(sl.wmem, ThetaUtil.DEFAULT_UPDATE_SEED);
}
@Test
public void checkBackgroundPropagation() {
int lgK = 4;
int k = 1 << lgK;
int u = 10*k;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
ConcurrentHeapThetaBuffer sk1 = (ConcurrentHeapThetaBuffer)local; //for internal checks
int i = 0;
for (; i< k; i++) {
local.update(i);
}
waitForBgPropagationToComplete(shared);
assertFalse(local.isEmpty());
assertTrue(local.getEstimate() > 0.0);
long theta1 = ((ConcurrentSharedThetaSketch)shared).getVolatileTheta();
for (; i< u; i++) {
local.update(i);
}
waitForBgPropagationToComplete(shared);
long theta2 = ((ConcurrentSharedThetaSketch)shared).getVolatileTheta();
int entries = shared.getRetainedEntries(false);
assertTrue((entries > k) || (theta2 < theta1),
"entries="+entries+" k="+k+" theta1="+theta1+" theta2="+theta2);
shared.rebuild();
assertEquals(shared.getRetainedEntries(false), k);
assertEquals(shared.getRetainedEntries(true), k);
sk1.rebuild();
assertEquals(shared.getRetainedEntries(false), k);
assertEquals(shared.getRetainedEntries(true), k);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
int lgK = 9;
int k = 1 << lgK;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
for (int i = 0; i< k; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
assertFalse(local.isEmpty());
assertEquals(local.getEstimate(), k, 0.0);
assertEquals(shared.getRetainedEntries(false), k);
sl.wmem.putByte(SER_VER_BYTE, (byte) 0); //corrupt the SerVer byte
Sketch.wrap(sl.wmem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkWrapIllegalFamilyID_wrap() {
int lgK = 9;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
sl.wmem.putByte(FAMILY_BYTE, (byte) 0); //corrupt the Sketch ID byte
//try to wrap the corrupted mem
Sketch.wrap(sl.wmem); //catch in Sketch.constructDirectSketch
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkWrapIllegalFamilyID_direct() {
int lgK = 9;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
sl.wmem.putByte(FAMILY_BYTE, (byte) 0); //corrupt the Sketch ID byte
//try to wrap the corrupted mem
DirectQuickSelectSketch.writableWrap(sl.wmem, ThetaUtil.DEFAULT_UPDATE_SEED);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifySeedConflict() {
int lgK = 9;
long seed1 = 1021;
long seed2 = ThetaUtil.DEFAULT_UPDATE_SEED;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, seed1, useMem, true, 1);
UpdateSketch shared = sl.shared;
Memory srcMem = Memory.wrap(shared.toByteArray());
Sketch.heapify(srcMem, seed2);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkCorruptLgNomLongs() {
int lgK = 4;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
sl.wmem.putByte(LG_NOM_LONGS_BYTE, (byte)2); //corrupt
Sketch.heapify(sl.wmem, ThetaUtil.DEFAULT_UPDATE_SEED);
}
@Test(expectedExceptions = UnsupportedOperationException.class)
public void checkIllegalHashUpdate() {
int lgK = 4;
boolean useMem = true;
SharedLocal sl = new SharedLocal(lgK, lgK, useMem);
UpdateSketch shared = sl.shared;
shared.hashUpdate(1);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
private static void checkMemoryDirectProxyMethods(Sketch local, Sketch shared) {
assertEquals(local.hasMemory(), shared.hasMemory());
assertEquals(local.isDirect(), shared.isDirect());
}
//Does not check hasMemory(), isDirect()
private static void checkOtherProxyMethods(Sketch local, Sketch shared) {
assertEquals(local.getCompactBytes(), shared.getCompactBytes());
assertEquals(local.getCurrentBytes(), shared.getCurrentBytes());
assertEquals(local.getEstimate(), shared.getEstimate());
assertEquals(local.getLowerBound(2), shared.getLowerBound(2));
assertEquals(local.getUpperBound(2), shared.getUpperBound(2));
assertEquals(local.isEmpty(), shared.isEmpty());
assertEquals(local.isEstimationMode(), shared.isEstimationMode());
}
}
| 2,460 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/PreambleUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.theta.PreambleUtil.clearEmpty;
import static org.apache.datasketches.theta.PreambleUtil.extractCurCount;
import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID;
import static org.apache.datasketches.theta.PreambleUtil.extractFlags;
import static org.apache.datasketches.theta.PreambleUtil.extractFlagsV1;
import static org.apache.datasketches.theta.PreambleUtil.extractLgArrLongs;
import static org.apache.datasketches.theta.PreambleUtil.extractLgNomLongs;
import static org.apache.datasketches.theta.PreambleUtil.extractLgResizeFactor;
import static org.apache.datasketches.theta.PreambleUtil.extractLgResizeRatioV1;
import static org.apache.datasketches.theta.PreambleUtil.extractP;
import static org.apache.datasketches.theta.PreambleUtil.extractPreLongs;
import static org.apache.datasketches.theta.PreambleUtil.extractSeedHash;
import static org.apache.datasketches.theta.PreambleUtil.extractSerVer;
import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong;
import static org.apache.datasketches.theta.PreambleUtil.extractUnionThetaLong;
import static org.apache.datasketches.theta.PreambleUtil.insertCurCount;
import static org.apache.datasketches.theta.PreambleUtil.insertFamilyID;
import static org.apache.datasketches.theta.PreambleUtil.insertFlags;
import static org.apache.datasketches.theta.PreambleUtil.insertLgArrLongs;
import static org.apache.datasketches.theta.PreambleUtil.insertLgNomLongs;
import static org.apache.datasketches.theta.PreambleUtil.insertLgResizeFactor;
import static org.apache.datasketches.theta.PreambleUtil.insertP;
import static org.apache.datasketches.theta.PreambleUtil.insertPreLongs;
import static org.apache.datasketches.theta.PreambleUtil.insertSeedHash;
import static org.apache.datasketches.theta.PreambleUtil.insertSerVer;
import static org.apache.datasketches.theta.PreambleUtil.insertThetaLong;
import static org.apache.datasketches.theta.PreambleUtil.insertUnionThetaLong;
import static org.apache.datasketches.theta.PreambleUtil.isEmptyFlag;
import static org.apache.datasketches.theta.PreambleUtil.setEmpty;
import static org.apache.datasketches.theta.SetOperation.getMaxUnionBytes;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class PreambleUtilTest {
@Test
public void checkToString() {
final int k = 4096;
final int u = 2*k;
final int bytes = (k << 4) + (Family.QUICKSELECT.getMinPreLongs() << 3);
final byte[] byteArray = new byte[bytes];
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
final UpdateSketch quick1 = UpdateSketch.builder().setNominalEntries(k).build(mem);
println(Sketch.toString(byteArray));
Assert.assertTrue(quick1.isEmpty());
for (int i = 0; i< u; i++) {
quick1.update(i);
}
println("U: "+quick1.getEstimate());
assertEquals(quick1.getEstimate(), u, .05*u);
assertTrue(quick1.getRetainedEntries(false) > k);
println(quick1.toString());
println(PreambleUtil.preambleToString(mem));
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(quick1);
println(PreambleUtil.preambleToString(uMem));
}
@Test
public void checkToStringWithPrelongsOf2() {
final int k = 16;
final int u = k;
final UpdateSketch quick1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i = 0; i< u; i++) {
quick1.update(i);
}
final byte[] bytes = quick1.compact().toByteArray();
println(Sketch.toString(bytes));
}
@Test
public void checkPreambleToStringExceptions() {
byte[] byteArr = new byte[7];
try { //check preLongs < 8 fails
Sketch.toString(byteArr);
fail("Did not throw SketchesArgumentException.");
} catch (final SketchesArgumentException e) {
//expected
}
byteArr = new byte[8];
byteArr[0] = (byte) 2; //needs min capacity of 16
try { //check preLongs == 2 fails
Sketch.toString(Memory.wrap(byteArr));
fail("Did not throw SketchesArgumentException.");
} catch (final SketchesArgumentException e) {
//expected
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSeedHashFromSeed() {
//In the first 64K values 50541 produces a seedHash of 0,
ThetaUtil.computeSeedHash(50541);
}
@Test
public void checkPreLongs() {
final UpdateSketch sketch = UpdateSketch.builder().setNominalEntries(16).build();
CompactSketch comp = sketch.compact(false, null);
byte[] byteArr = comp.toByteArray();
println(Sketch.toString(byteArr)); //PreLongs = 1
sketch.update(1);
comp = sketch.compact(false, null);
byteArr = comp.toByteArray();
println(Sketch.toString(byteArr)); //PreLongs = 2
for (int i=2; i<=32; i++) {
sketch.update(i);
}
comp = sketch.compact(false, null);
byteArr = comp.toByteArray();
println(Sketch.toString(Memory.wrap(byteArr))); //PreLongs = 3
}
@Test
public void checkInsertsAndExtracts() {
final byte[] arr = new byte[32];
final WritableMemory wmem = WritableMemory.writableWrap(arr);
int v = 0;
insertPreLongs(wmem, ++v);
assertEquals(extractPreLongs(wmem), v);
insertPreLongs(wmem, 0);
insertLgResizeFactor(wmem, 3); //limited to 2 bits
assertEquals(extractLgResizeFactor(wmem), 3);
insertLgResizeFactor(wmem, 0);
insertSerVer(wmem, ++v);
assertEquals(extractSerVer(wmem), v);
insertSerVer(wmem, 0);
insertFamilyID(wmem, ++v);
assertEquals(extractFamilyID(wmem), v);
insertFamilyID(wmem, 0);
insertLgNomLongs(wmem, ++v);
assertEquals(extractLgNomLongs(wmem), v);
insertLgNomLongs(wmem, 0);
insertLgArrLongs(wmem, ++v);
assertEquals(extractLgArrLongs(wmem), v);
insertLgArrLongs(wmem, 0);
insertFlags(wmem, 3);
assertEquals(extractFlags(wmem), 3);
assertEquals(extractLgResizeRatioV1(wmem), 3); //also at byte 5, limited to 2 bits
insertFlags(wmem, 0);
insertSeedHash(wmem, ++v);
assertEquals(extractSeedHash(wmem), v);
assertEquals(extractFlagsV1(wmem), v); //also at byte 6
insertSeedHash(wmem, 0);
insertCurCount(wmem, ++v);
assertEquals(extractCurCount(wmem), v);
insertCurCount(wmem, 0);
insertP(wmem, (float) 1.0);
assertEquals(extractP(wmem), (float) 1.0);
insertP(wmem, (float) 0.0);
insertThetaLong(wmem, ++v);
assertEquals(extractThetaLong(wmem), v);
insertThetaLong(wmem, 0L);
insertUnionThetaLong(wmem, ++v);
assertEquals(extractUnionThetaLong(wmem), v);
insertUnionThetaLong(wmem, 0L);
setEmpty(wmem);
assertTrue(isEmptyFlag(wmem));
clearEmpty(wmem);
assertFalse(isEmptyFlag(wmem));
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,461 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/DirectQuickSelectSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.common.Family.QUICKSELECT;
import static org.apache.datasketches.theta.PreambleUtil.BIG_ENDIAN_FLAG_MASK;
import static org.apache.datasketches.theta.PreambleUtil.COMPACT_FLAG_MASK;
import static org.apache.datasketches.theta.PreambleUtil.FAMILY_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.FLAGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.LG_ARR_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.LG_NOM_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.ORDERED_FLAG_MASK;
import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.READ_ONLY_FLAG_MASK;
import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.THETA_LONG;
import static org.apache.datasketches.theta.PreambleUtil.insertLgResizeFactor;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.Arrays;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesReadOnlyException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableHandle;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.HashOperations;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class DirectQuickSelectSketchTest {
@Test//(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
int k = 512;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< k; i++) { usk.update(i); }
assertFalse(usk.isEmpty());
assertEquals(usk.getEstimate(), k, 0.0);
assertEquals(sk1.getRetainedEntries(false), k);
mem.putByte(SER_VER_BYTE, (byte) 0); //corrupt the SerVer byte
Sketch.wrap(mem);
} catch (final Exception e) {
if (e instanceof SketchesArgumentException) {}
else { throw new RuntimeException(e); }
}
}
@Test//(expectedExceptions = SketchesArgumentException.class)
public void checkConstructorKtooSmall() {
int k = 8;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch.builder().setNominalEntries(k).build(mem);
} catch (final Exception e) {
if (e instanceof SketchesArgumentException) {}
else { throw new RuntimeException(e); }
}
}
@Test//(expectedExceptions = SketchesArgumentException.class)
public void checkConstructorMemTooSmall() {
int k = 16;
try (WritableHandle h = makeNativeMemory(k/2)) {
WritableMemory mem = h.getWritable();
UpdateSketch.builder().setNominalEntries(k).build(mem);
} catch (final Exception e) {
if (e instanceof SketchesArgumentException) {}
else { throw new RuntimeException(e); }
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyIllegalFamilyID_heapify() {
int k = 512;
int bytes = (k << 4) + (Family.QUICKSELECT.getMinPreLongs() << 3);
WritableMemory mem = WritableMemory.writableWrap(new byte[bytes]);
UpdateSketch.builder().setNominalEntries(k).build(mem);
mem.putByte(FAMILY_BYTE, (byte) 0); //corrupt the Family ID byte
//try to heapify the corrupted mem
Sketch.heapify(mem); //catch in Sketch.constructHeapSketch
}
@Test
public void checkHeapifyMemoryEstimating() {
int k = 512;
int u = 2*k; //thus estimating
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch sk1 = UpdateSketch.builder().setNominalEntries(k).build(mem);
for (int i=0; i<u; i++) { sk1.update(i); }
double sk1est = sk1.getEstimate();
double sk1lb = sk1.getLowerBound(2);
double sk1ub = sk1.getUpperBound(2);
assertTrue(sk1.isEstimationMode());
assertEquals(sk1.getClass().getSimpleName(), "DirectQuickSelectSketch");
int curCount1 = sk1.getRetainedEntries(true);
assertTrue(sk1.isDirect());
assertTrue(sk1.hasMemory());
assertFalse(sk1.isDirty());
assertTrue(sk1.hasMemory());
assertEquals(sk1.getCurrentPreambleLongs(), 3);
UpdateSketch sk2 = Sketches.heapifyUpdateSketch(mem);
assertEquals(sk2.getEstimate(), sk1est);
assertEquals(sk2.getLowerBound(2), sk1lb);
assertEquals(sk2.getUpperBound(2), sk1ub);
assertEquals(sk2.isEmpty(), false);
assertTrue(sk2.isEstimationMode());
assertEquals(sk2.getClass().getSimpleName(), "HeapQuickSelectSketch");
int curCount2 = sk2.getRetainedEntries(true);
long[] cache = sk2.getCache();
assertEquals(curCount1, curCount2);
long thetaLong = sk2.getThetaLong();
int cacheCount = HashOperations.count(cache, thetaLong);
assertEquals(curCount1, cacheCount);
assertFalse(sk2.isDirect());
assertFalse(sk2.hasMemory());
assertFalse(sk2.isDirty());
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkWrapIllegalFamilyID_wrap() {
int k = 512;
int maxBytes = (k << 4) + (Family.QUICKSELECT.getMinPreLongs() << 3);
WritableMemory mem = WritableMemory.writableWrap(new byte[maxBytes]);
UpdateSketch.builder().setNominalEntries(k).build(mem);
mem.putByte(FAMILY_BYTE, (byte) 0); //corrupt the Sketch ID byte
//try to wrap the corrupted mem
Sketch.wrap(mem); //catch in Sketch.constructDirectSketch
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkWrapIllegalFamilyID_direct() {
int k = 512;
int maxBytes = (k << 4) + (Family.QUICKSELECT.getMinPreLongs() << 3);
WritableMemory mem = WritableMemory.writableWrap(new byte[maxBytes]);
UpdateSketch.builder().setNominalEntries(k).build(mem);
mem.putByte(FAMILY_BYTE, (byte) 0); //corrupt the Sketch ID byte
//try to wrap the corrupted mem
DirectQuickSelectSketch.writableWrap(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
}
@Test //(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifySeedConflict() {
int k = 512;
long seed1 = 1021;
long seed2 = ThetaUtil.DEFAULT_UPDATE_SEED;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setSeed(seed1).setNominalEntries(k).build(mem);
byte[] byteArray = usk.toByteArray();
Memory srcMem = Memory.wrap(byteArray);
Sketch.heapify(srcMem, seed2);
} catch (final Exception e) {
if (e instanceof SketchesArgumentException) {}
else { throw new RuntimeException(e); }
}
}
@Test//(expectedExceptions = SketchesArgumentException.class)
public void checkCorruptLgNomLongs() {
int k = 16;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch.builder().setNominalEntries(k).build(mem);
mem.putByte(LG_NOM_LONGS_BYTE, (byte)2); //corrupt
Sketch.heapify(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
} catch (final Exception e) {
if (e instanceof SketchesArgumentException) {}
else { throw new RuntimeException(e); }
}
}
@Test
public void checkHeapifyByteArrayExact() {
int k = 512;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
for (int i=0; i< k; i++) { usk.update(i); }
int bytes = usk.getCurrentBytes();
byte[] byteArray = usk.toByteArray();
assertEquals(bytes, byteArray.length);
Memory srcMem = Memory.wrap(byteArray);
Sketch usk2 = Sketch.heapify(srcMem);
assertEquals(usk2.getEstimate(), k, 0.0);
assertEquals(usk2.getLowerBound(2), k, 0.0);
assertEquals(usk2.getUpperBound(2), k, 0.0);
assertEquals(usk2.isEmpty(), false);
assertEquals(usk2.isEstimationMode(), false);
assertEquals(usk2.getClass().getSimpleName(), "HeapQuickSelectSketch");
// Run toString just to make sure that we can pull out all of the relevant information.
// That is, this is being run for its side-effect of accessing things.
// If something is wonky, it will generate an exception and fail the test.
usk2.toString(true, true, 8, true);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkHeapifyByteArrayEstimating() {
int k = 4096;
int u = 2*k;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
for (int i=0; i<u; i++) { usk.update(i); }
double uskEst = usk.getEstimate();
double uskLB = usk.getLowerBound(2);
double uskUB = usk.getUpperBound(2);
assertEquals(usk.isEstimationMode(), true);
byte[] byteArray = usk.toByteArray();
Memory srcMem = Memory.wrap(byteArray);
Sketch usk2 = Sketch.heapify(srcMem);
assertEquals(usk2.getEstimate(), uskEst);
assertEquals(usk2.getLowerBound(2), uskLB);
assertEquals(usk2.getUpperBound(2), uskUB);
assertEquals(usk2.isEmpty(), false);
assertEquals(usk2.isEstimationMode(), true);
assertEquals(usk2.getClass().getSimpleName(), "HeapQuickSelectSketch");
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkWrapMemoryEst() {
int k = 512;
int u = 2*k; //thus estimating
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch sk1 = UpdateSketch.builder().setNominalEntries(k).build(mem);
for (int i=0; i<u; i++) { sk1.update(i); }
double sk1est = sk1.getEstimate();
double sk1lb = sk1.getLowerBound(2);
double sk1ub = sk1.getUpperBound(2);
assertTrue(sk1.isEstimationMode());
Sketch sk2 = Sketch.wrap(mem);
assertEquals(sk2.getEstimate(), sk1est);
assertEquals(sk2.getLowerBound(2), sk1lb);
assertEquals(sk2.getUpperBound(2), sk1ub);
assertEquals(sk2.isEmpty(), false);
assertTrue(sk2.isEstimationMode());
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkDQStoCompactForms() {
int k = 512;
int u = 4*k; //thus estimating
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks
assertEquals(usk.getClass().getSimpleName(), "DirectQuickSelectSketch");
assertTrue(usk.isDirect());
assertTrue(usk.hasMemory());
assertFalse(usk.isCompact());
assertFalse(usk.isOrdered());
for (int i=0; i<u; i++) { usk.update(i); }
sk1.rebuild(); //forces size back to k
//get baseline values
double uskEst = usk.getEstimate();
double uskLB = usk.getLowerBound(2);
double uskUB = usk.getUpperBound(2);
assertTrue(usk.isEstimationMode());
CompactSketch csk;
csk = usk.compact(false, null);
assertEquals(csk.getEstimate(), uskEst);
assertEquals(csk.getLowerBound(2), uskLB);
assertEquals(csk.getUpperBound(2), uskUB);
assertEquals(csk.isEmpty(), false);
assertTrue(csk.isEstimationMode());
assertEquals(csk.getClass().getSimpleName(), "HeapCompactSketch");
csk = usk.compact(true, null);
assertEquals(csk.getEstimate(), uskEst);
assertEquals(csk.getLowerBound(2), uskLB);
assertEquals(csk.getUpperBound(2), uskUB);
assertEquals(csk.isEmpty(), false);
assertTrue(csk.isEstimationMode());
assertEquals(csk.getClass().getSimpleName(), "HeapCompactSketch");
int bytes = usk.getCompactBytes();
assertEquals(bytes, (k*8) + (Family.COMPACT.getMaxPreLongs() << 3));
byte[] memArr2 = new byte[bytes];
WritableMemory mem2 = WritableMemory.writableWrap(memArr2);
csk = usk.compact(false, mem2);
assertEquals(csk.getEstimate(), uskEst);
assertEquals(csk.getLowerBound(2), uskLB);
assertEquals(csk.getUpperBound(2), uskUB);
assertEquals(csk.isEmpty(), false);
assertTrue(csk.isEstimationMode());
assertEquals(csk.getClass().getSimpleName(), "DirectCompactSketch");
mem2.clear();
csk = usk.compact(true, mem2);
assertEquals(csk.getEstimate(), uskEst);
assertEquals(csk.getLowerBound(2), uskLB);
assertEquals(csk.getUpperBound(2), uskUB);
assertEquals(csk.isEmpty(), false);
assertTrue(csk.isEstimationMode());
assertEquals(csk.getClass().getSimpleName(), "DirectCompactSketch");
csk.toString(false, true, 0, false);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkDQStoCompactEmptyForms() {
int k = 512;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
//empty
usk.toString(false, true, 0, false); //exercise toString
assertEquals(usk.getClass().getSimpleName(), "DirectQuickSelectSketch");
double uskEst = usk.getEstimate();
double uskLB = usk.getLowerBound(2);
double uskUB = usk.getUpperBound(2);
assertEquals(usk.isEstimationMode(), false);
int bytes = usk.getCompactBytes(); //compact form
assertEquals(bytes, 8);
byte[] memArr2 = new byte[bytes];
WritableMemory mem2 = WritableMemory.writableWrap(memArr2);
CompactSketch csk2 = usk.compact(false, mem2);
assertEquals(csk2.getEstimate(), uskEst);
assertEquals(csk2.getLowerBound(2), uskLB);
assertEquals(csk2.getUpperBound(2), uskUB);
assertEquals(csk2.isEmpty(), true);
assertEquals(csk2.isEstimationMode(), false);
assertEquals(csk2.getClass().getSimpleName(), "DirectCompactSketch");
CompactSketch csk3 = usk.compact(true, mem2);
csk3.toString(false, true, 0, false);
csk3.toString();
assertEquals(csk3.getEstimate(), uskEst);
assertEquals(csk3.getLowerBound(2), uskLB);
assertEquals(csk3.getUpperBound(2), uskUB);
assertEquals(csk3.isEmpty(), true);
assertEquals(csk3.isEstimationMode(), false);
assertEquals(csk3.getClass().getSimpleName(), "DirectCompactSketch");
} catch (final Exception e) {
//if (e instanceof SketchesArgumentException) {}
throw new RuntimeException(e);
}
}
@Test
public void checkEstMode() {
int k = 4096;
int u = 2*k;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) { usk.update(i); }
assertTrue(sk1.getRetainedEntries(false) > k);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkSamplingMode() {
int k = 4096;
float p = (float)0.5;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setP(p).setNominalEntries(k).build(mem);
DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks
for (int i = 0; i < k; i++ ) { usk.update(i); }
double p2 = sk1.getP();
double theta = sk1.getTheta();
assertTrue(theta <= p2);
double est = usk.getEstimate();
assertEquals(k, est, k *.05);
double ub = usk.getUpperBound(1);
assertTrue(ub > est);
double lb = usk.getLowerBound(1);
assertTrue(lb < est);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkErrorBounds() {
int k = 512;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
//Exact mode
for (int i = 0; i < k; i++ ) { usk.update(i); }
double est = usk.getEstimate();
double lb = usk.getLowerBound(2);
double ub = usk.getUpperBound(2);
assertEquals(est, ub, 0.0);
assertEquals(est, lb, 0.0);
//Est mode
int u = 100*k;
for (int i = k; i < u; i++ ) {
usk.update(i);
usk.update(i); //test duplicate rejection
}
est = usk.getEstimate();
lb = usk.getLowerBound(2);
ub = usk.getUpperBound(2);
assertTrue(est <= ub);
assertTrue(est >= lb);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
//Empty Tests
@Test
public void checkEmptyAndP() {
//virgin, p = 1.0
int k = 1024;
float p = (float)1.0;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setP(p).setNominalEntries(k).build(mem);
DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
usk.update(1);
assertEquals(sk1.getRetainedEntries(true), 1);
assertFalse(usk.isEmpty());
//virgin, p = .001
p = (float)0.001;
byte[] memArr2 = new byte[(int) mem.getCapacity()];
WritableMemory mem2 = WritableMemory.writableWrap(memArr2);
UpdateSketch usk2 = UpdateSketch.builder().setP(p).setNominalEntries(k).build(mem2);
sk1 = (DirectQuickSelectSketch)usk2;
assertTrue(usk2.isEmpty());
usk2.update(1); //will be rejected
assertEquals(sk1.getRetainedEntries(true), 0);
assertFalse(usk2.isEmpty());
double est = usk2.getEstimate();
//println("Est: "+est);
assertEquals(est, 0.0, 0.0); //because curCount = 0
double ub = usk2.getUpperBound(2); //huge because theta is tiny!
//println("UB: "+ub);
assertTrue(ub > 0.0);
double lb = usk2.getLowerBound(2);
assertTrue(lb <= est);
//println("LB: "+lb);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkUpperAndLowerBounds() {
int k = 512;
int u = 2*k;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
for (int i = 0; i < u; i++ ) { usk.update(i); }
double est = usk.getEstimate();
double ub = usk.getUpperBound(1);
double lb = usk.getLowerBound(1);
assertTrue(ub > est);
assertTrue(lb < est);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkRebuild() {
int k = 512;
int u = 4*k;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) { usk.update(i); }
assertFalse(usk.isEmpty());
assertTrue(usk.getEstimate() > 0.0);
assertTrue(sk1.getRetainedEntries(false) > k);
sk1.rebuild();
assertEquals(sk1.getRetainedEntries(false), k);
assertEquals(sk1.getRetainedEntries(true), k);
sk1.rebuild();
assertEquals(sk1.getRetainedEntries(false), k);
assertEquals(sk1.getRetainedEntries(true), k);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkResetAndStartingSubMultiple() {
int k = 512;
int u = 4*k;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) { usk.update(i); }
assertFalse(usk.isEmpty());
assertTrue(sk1.getRetainedEntries(false) > k);
assertTrue(sk1.getThetaLong() < Long.MAX_VALUE);
sk1.reset();
assertTrue(usk.isEmpty());
assertEquals(sk1.getRetainedEntries(false), 0);
assertEquals(usk.getEstimate(), 0.0, 0.0);
assertEquals(sk1.getThetaLong(), Long.MAX_VALUE);
assertNotNull(sk1.getMemory());
assertFalse(sk1.isOrdered());
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkExactModeMemoryArr() {
int k = 4096;
int u = 4096;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) { usk.update(i); }
assertEquals(usk.getEstimate(), u, 0.0);
assertEquals(sk1.getRetainedEntries(false), u);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkEstModeMemoryArr() {
int k = 4096;
int u = 2*k;
try (WritableHandle h = makeNativeMemory(k)) {
WritableMemory mem = h.getWritable();
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(mem);
DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) { usk.update(i); }
assertEquals(usk.getEstimate(), u, u*.05);
assertTrue(sk1.getRetainedEntries(false) > k);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkEstModeNativeMemory() {
int k = 4096;
int u = 2*k;
int memCapacity = (k << 4) + (Family.QUICKSELECT.getMinPreLongs() << 3);
try(WritableHandle memHandler = WritableMemory.allocateDirect(memCapacity)) {
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(memHandler.getWritable());
DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) { usk.update(i); }
double est = usk.getEstimate();
println(""+est);
assertEquals(usk.getEstimate(), u, u*.05);
assertTrue(sk1.getRetainedEntries(false) > k);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkConstructReconstructFromMemory() {
int k = 4096;
int u = 2*k;
try (WritableHandle h = makeNativeMemory(k)) {
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build(h.getWritable());
assertTrue(usk.isEmpty());
for (int i = 0; i< u; i++) { usk.update(i); } //force estimation
double est1 = usk.getEstimate();
int count1 = usk.getRetainedEntries(false);
assertEquals(est1, u, u*.05);
assertTrue(count1 >= k);
byte[] serArr;
double est2;
int count2;
serArr = usk.toByteArray();
WritableMemory mem2 = WritableMemory.writableWrap(serArr);
//reconstruct to Native/Direct
UpdateSketch usk2 = Sketches.wrapUpdateSketch(mem2);
est2 = usk2.getEstimate();
count2 = usk2.getRetainedEntries(false);
assertEquals(count2, count1);
assertEquals(est2, est1, 0.0);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test(expectedExceptions = SketchesReadOnlyException.class)
public void updateAfterReadOnlyWrap() {
UpdateSketch usk1 = UpdateSketch.builder().build();
UpdateSketch usk2 = (UpdateSketch) Sketch.wrap(Memory.wrap(usk1.toByteArray()));
usk2.update(0);
}
public void updateAfterWritableWrap() {
UpdateSketch usk1 = UpdateSketch.builder().build();
UpdateSketch usk2 = UpdateSketch.wrap(WritableMemory.writableWrap(usk1.toByteArray()));
usk2.update(0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkNegativeHashes() {
int k = 512;
UpdateSketch qs = UpdateSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build();
qs.hashUpdate(-1L);
}
@Test
public void checkConstructorSrcMemCorruptions() {
int k = 1024; //lgNomLongs = 10
int u = k; //exact mode, lgArrLongs = 11
int bytes = Sketches.getMaxUpdateSketchBytes(k);
byte[] arr1 = new byte[bytes];
WritableMemory mem1 = WritableMemory.writableWrap(arr1);
ResizeFactor rf = ResizeFactor.X1; //0
UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).setResizeFactor(rf).build(mem1);
for (int i=0; i<u; i++) { usk1.update(i); }
//println(PreambleUtil.toString(mem1));
@SuppressWarnings("unused")
UpdateSketch usk2;
mem1.putByte(FAMILY_BYTE, (byte) 3); //corrupt Family by setting to Compact
try {
usk2 = DirectQuickSelectSketch.writableWrap(mem1, ThetaUtil.DEFAULT_UPDATE_SEED);
fail("Expected SketchesArgumentException");
} catch (SketchesArgumentException e) {
//Pass
}
mem1.putByte(FAMILY_BYTE, (byte) 2); //fix Family
mem1.putByte(PREAMBLE_LONGS_BYTE, (byte) 1); //corrupt preLongs
try {
usk2 = DirectQuickSelectSketch.writableWrap(mem1, ThetaUtil.DEFAULT_UPDATE_SEED);
fail("Expected SketchesArgumentException");
} catch (SketchesArgumentException e) {
//pass
}
mem1.putByte(PREAMBLE_LONGS_BYTE, (byte) 3); //fix preLongs
mem1.putByte(SER_VER_BYTE, (byte) 2); //corrupt serVer
try {
usk2 = DirectQuickSelectSketch.writableWrap(mem1, ThetaUtil.DEFAULT_UPDATE_SEED);
fail("Expected SketchesArgumentException");
} catch (SketchesArgumentException e) {
//pass
}
mem1.putByte(SER_VER_BYTE, (byte) 3); //fix serVer
mem1.putLong(THETA_LONG, Long.MAX_VALUE >>> 1); //corrupt theta and
mem1.putByte(LG_ARR_LONGS_BYTE, (byte) 10); //corrupt lgArrLongs
try {
usk2 = DirectQuickSelectSketch.writableWrap(mem1, ThetaUtil.DEFAULT_UPDATE_SEED);
fail("Expected SketchesArgumentException");
} catch (SketchesArgumentException e) {
//pass
}
mem1.putLong(THETA_LONG, Long.MAX_VALUE); //fix theta and
mem1.putByte(LG_ARR_LONGS_BYTE, (byte) 11); //fix lgArrLongs
byte badFlags = (byte) (BIG_ENDIAN_FLAG_MASK | COMPACT_FLAG_MASK | READ_ONLY_FLAG_MASK | ORDERED_FLAG_MASK);
mem1.putByte(FLAGS_BYTE, badFlags);
try {
usk2 = DirectQuickSelectSketch.writableWrap(mem1, ThetaUtil.DEFAULT_UPDATE_SEED);
fail("Expected SketchesArgumentException");
} catch (SketchesArgumentException e) {
//pass
}
byte[] arr2 = Arrays.copyOfRange(arr1, 0, bytes-1); //corrupt length
WritableMemory mem2 = WritableMemory.writableWrap(arr2);
try {
usk2 = DirectQuickSelectSketch.writableWrap(mem2, ThetaUtil.DEFAULT_UPDATE_SEED);
fail("Expected SketchesArgumentException");
} catch (SketchesArgumentException e) {
//pass
}
}
@Test
public void checkCorruptRFWithInsufficientArray() {
int k = 1024; //lgNomLongs = 10
int bytes = Sketches.getMaxUpdateSketchBytes(k);
byte[] arr = new byte[bytes];
WritableMemory mem = WritableMemory.writableWrap(arr);
ResizeFactor rf = ResizeFactor.X8; // 3
UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).setResizeFactor(rf).build(mem);
usk.update(0);
insertLgResizeFactor(mem, 0); // corrupt RF: X1
UpdateSketch dqss = DirectQuickSelectSketch.writableWrap(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
assertEquals(dqss.getResizeFactor(), ResizeFactor.X2); // force-promote to X2
}
@Test
public void checkFamilyAndRF() {
int k = 16;
WritableMemory mem = WritableMemory.writableWrap(new byte[(k*16) +24]);
UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build(mem);
assertEquals(sketch.getFamily(), Family.QUICKSELECT);
assertEquals(sketch.getResizeFactor(), ResizeFactor.X8);
}
//checks Alex's bug where lgArrLongs > lgNomLongs +1.
@Test
public void checkResizeInBigMem() {
int k = 1 << 14;
int u = 1 << 20;
WritableMemory mem = WritableMemory.writableWrap(new byte[(8*k*16) +24]);
UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build(mem);
for (int i=0; i<u; i++) { sketch.update(i); }
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadLgNomLongs() {
int k = 16;
WritableMemory mem = WritableMemory.writableWrap(new byte[(k*16) +24]);
Sketches.updateSketchBuilder().setNominalEntries(k).build(mem);
mem.putByte(LG_NOM_LONGS_BYTE, (byte) 3); //Corrupt LgNomLongs byte
DirectQuickSelectSketch.writableWrap(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
}
@Test
public void checkMoveAndResize() {
int k = 1 << 12;
int u = 2 * k;
int bytes = Sketches.getMaxUpdateSketchBytes(k);
try (WritableHandle wdh = WritableMemory.allocateDirect(bytes/2)) { //will request
WritableMemory wmem = wdh.getWritable();
UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build(wmem);
assertTrue(sketch.isSameResource(wmem));
for (int i = 0; i < u; i++) { sketch.update(i); }
assertFalse(sketch.isSameResource(wmem));
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkReadOnlyRebuildResize() {
int k = 1 << 12;
int u = 2 * k;
int bytes = Sketches.getMaxUpdateSketchBytes(k);
try (WritableHandle wdh = WritableMemory.allocateDirect(bytes/2)) { //will request
WritableMemory wmem = wdh.getWritable();
UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build(wmem);
for (int i = 0; i < u; i++) { sketch.update(i); }
double est1 = sketch.getEstimate();
byte[] ser = sketch.toByteArray();
Memory mem = Memory.wrap(ser);
UpdateSketch roSketch = (UpdateSketch) Sketches.wrapSketch(mem);
double est2 = roSketch.getEstimate();
assertEquals(est2, est1);
try {
roSketch.rebuild();
fail();
} catch (SketchesReadOnlyException e) {
//expected
}
try {
roSketch.reset();
fail();
} catch (SketchesReadOnlyException e) {
//expected
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
private static final int getMaxBytes(int k) {
return (k << 4) + (Family.QUICKSELECT.getMinPreLongs() << 3);
}
private static WritableHandle makeNativeMemory(int k) {
return WritableMemory.allocateDirect(getMaxBytes(k));
}
}
| 2,462 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/CornerCaseThetaSetOperationsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import org.testng.annotations.Test;
//import static org.apache.datasketches.Util.DEFAULT_UPDATE_SEED;
//import static org.apache.datasketches.hash.MurmurHash3.hash;
public class CornerCaseThetaSetOperationsTest {
/* Hash Values
* 9223372036854775807 Theta = 1.0
*
* 6730918654704304314 hash(3L)[0] >>> 1 GT_MIDP
* 4611686018427387904 Theta for p = 0.5f = MIDP
*
* 1206007004353599230 hash(6L)[0] >>> 1 GT_LOWP_V
* 922337217429372928 Theta for p = 0.1f = LOWP
* 593872385995628096 hash(4L)[0] >>> 1 LT_LOWP_V
*/
private static final long GT_MIDP_V = 3L;
private static final float MIDP = 0.5f;
private static final long GT_LOWP_V = 6L;
private static final float LOWP = 0.1f;
private static final long LT_LOWP_V = 4L;
private static final double LOWP_THETA = LOWP;
private enum SkType {
EMPTY, // { 1.0, 0, T} Bin: 101 Oct: 05
EXACT, // { 1.0, >0, F} Bin: 110 Oct: 06, specify only value
ESTIMATION, // {<1.0, >0, F} Bin: 010 Oct: 02, specify only value
DEGENERATE // {<1.0, 0, F} Bin: 000 Oct: 0, specify p, value
}
//=================================
@Test
public void emptyEmpty() {
UpdateSketch thetaA = getSketch(SkType.EMPTY, 0, 0);
UpdateSketch thetaB = getSketch(SkType.EMPTY, 0, 0);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = true;
final double expectedAnotbTheta = 1.0;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = true;
final double expectedUnionTheta = 1.0;
final int expectedUnionCount = 0;
final boolean expectedUnionEmpty = true;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void emptyExact() {
UpdateSketch thetaA = getSketch(SkType.EMPTY, 0, 0);
UpdateSketch thetaB = getSketch(SkType.EXACT, 0, GT_MIDP_V);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = true;
final double expectedAnotbTheta = 1.0;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = true;
final double expectedUnionTheta = 1.0;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void emptyDegenerate() {
UpdateSketch thetaA = getSketch(SkType.EMPTY, 0, 0);
UpdateSketch thetaB = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = true;
final double expectedAnotbTheta = 1.0;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = true;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 0;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void emptyEstimation() {
UpdateSketch thetaA = getSketch(SkType.EMPTY, 0, 0);
UpdateSketch thetaB = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = true;
final double expectedAnotbTheta = 1.0;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = true;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
@Test
public void exactEmpty() {
UpdateSketch thetaA = getSketch(SkType.EXACT, 0, GT_MIDP_V);
UpdateSketch thetaB = getSketch(SkType.EMPTY, 0, 0);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = true;
final double expectedAnotbTheta = 1.0;
final int expectedAnotbCount = 1;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = 1.0;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void exactExact() {
UpdateSketch thetaA = getSketch(SkType.EXACT, 0, GT_MIDP_V);
UpdateSketch thetaB = getSketch(SkType.EXACT, 0, GT_MIDP_V);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 1;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = 1.0;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = true;
final double expectedUnionTheta = 1.0;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void exactDegenerate() {
UpdateSketch thetaA = getSketch(SkType.EXACT, 0, LT_LOWP_V);
UpdateSketch thetaB = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V); //entries = 0
final double expectedIntersectTheta = LOWP_THETA;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_THETA;
final int expectedAnotbCount = 1;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void exactEstimation() {
UpdateSketch thetaA = getSketch(SkType.EXACT, 0, LT_LOWP_V);
UpdateSketch thetaB = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V);
final double expectedIntersectTheta = LOWP_THETA;
final int expectedIntersectCount = 1;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_THETA;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
@Test
public void estimationEmpty() {
UpdateSketch thetaA = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V);
UpdateSketch thetaB = getSketch(SkType.EMPTY, 0, 0);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = true;
final double expectedAnotbTheta = LOWP_THETA;
final int expectedAnotbCount = 1;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void estimationExact() {
UpdateSketch thetaA = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V);
UpdateSketch thetaB = getSketch(SkType.EXACT, 0, LT_LOWP_V);
final double expectedIntersectTheta = LOWP_THETA;
final int expectedIntersectCount = 1;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_THETA;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void estimationDegenerate() {
UpdateSketch thetaA = getSketch(SkType.ESTIMATION, MIDP, LT_LOWP_V);
UpdateSketch thetaB = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V);
final double expectedIntersectTheta = LOWP_THETA;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_THETA;
final int expectedAnotbCount = 1;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void estimationEstimation() {
UpdateSketch thetaA = getSketch(SkType.ESTIMATION, MIDP, LT_LOWP_V);
UpdateSketch thetaB = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V);
final double expectedIntersectTheta = LOWP_THETA;
final int expectedIntersectCount = 1;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_THETA;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
@Test
public void degenerateEmpty() {
UpdateSketch thetaA = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V); //entries = 0
UpdateSketch thetaB = getSketch(SkType.EMPTY, 0, 0);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = true;
final double expectedAnotbTheta = LOWP_THETA;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 0;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void degenerateExact() {
UpdateSketch thetaA = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V); //entries = 0
UpdateSketch thetaB = getSketch(SkType.EXACT, 0, LT_LOWP_V);
final double expectedIntersectTheta = LOWP_THETA;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_THETA;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void degenerateDegenerate() {
UpdateSketch thetaA = getSketch(SkType.DEGENERATE, MIDP, GT_MIDP_V); //entries = 0
UpdateSketch thetaB = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V);
final double expectedIntersectTheta = LOWP_THETA;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_THETA;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 0;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void degenerateEstimation() {
UpdateSketch thetaA = getSketch(SkType.DEGENERATE, MIDP, GT_MIDP_V); //entries = 0
UpdateSketch thetaB = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V);
final double expectedIntersectTheta = LOWP_THETA;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_THETA;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
//=================================
private static void checks(
UpdateSketch thetaA,
UpdateSketch thetaB,
double expectedIntersectTheta,
int expectedIntersectCount,
boolean expectedIntersectEmpty,
double expectedAnotbTheta,
int expectedAnotbCount,
boolean expectedAnotbEmpty,
double expectedUnionTheta,
int expectedUnionCount,
boolean expectedUnionEmpty) {
CompactSketch csk;
Intersection inter = SetOperation.builder().buildIntersection();
AnotB anotb = SetOperation.builder().buildANotB();
Union union = new SetOperationBuilder().buildUnion();
//Intersection Stateless Theta, Theta Updatable
csk = inter.intersect(thetaA, thetaB);
checkResult("Intersect Stateless Theta, Theta", csk, expectedIntersectTheta, expectedIntersectCount,
expectedIntersectEmpty);
//Intersection Stateless Theta, Theta Compact
csk = inter.intersect(thetaA.compact(), thetaB.compact());
checkResult("Intersect Stateless Theta, Theta", csk, expectedIntersectTheta, expectedIntersectCount,
expectedIntersectEmpty);
//AnotB Stateless Theta, Theta Updatable
csk = anotb.aNotB(thetaA, thetaB);
checkResult("AnotB Stateless Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//AnotB Stateless Theta, Theta Compact
csk = anotb.aNotB(thetaA.compact(), thetaB.compact());
checkResult("AnotB Stateless Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//AnotB Stateful Theta, Theta Updatable
anotb.setA(thetaA);
anotb.notB(thetaB);
csk = anotb.getResult(true);
checkResult("AnotB Stateful Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//AnotB Stateful Theta, Theta Compact
anotb.setA(thetaA.compact());
anotb.notB(thetaB.compact());
csk = anotb.getResult(true);
checkResult("AnotB Stateful Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//Union Stateful Theta, Theta Updatable
union.union(thetaA);
union.union(thetaB);
csk = union.getResult();
union.reset();
checkResult("Union Stateless Theta, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
//Union Stateful Theta, Theta Compact
union.union(thetaA.compact());
union.union(thetaB.compact());
csk = union.getResult();
union.reset();
checkResult("Union Stateless Theta, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
private static void checkResult(
String comment,
CompactSketch csk,
double expectedTheta,
int expectedEntries,
boolean expectedEmpty) {
double actualTheta = csk.getTheta();
int actualEntries = csk.getRetainedEntries();
boolean actualEmpty = csk.isEmpty();
boolean thetaOk = actualTheta == expectedTheta;
boolean entriesOk = actualEntries == expectedEntries;
boolean emptyOk = actualEmpty == expectedEmpty;
if (!thetaOk || !entriesOk || !emptyOk) {
StringBuilder sb = new StringBuilder();
sb.append(comment + ": ");
if (!thetaOk) { sb.append("Theta: expected " + expectedTheta + ", got " + actualTheta + "; "); }
if (!entriesOk) { sb.append("Entries: expected " + expectedEntries + ", got " + actualEntries + "; "); }
if (!emptyOk) { sb.append("Empty: expected " + expectedEmpty + ", got " + actualEmpty + "."); }
throw new IllegalArgumentException(sb.toString());
}
}
private static UpdateSketch getSketch(SkType skType, float p, long value) {
UpdateSketchBuilder bldr = UpdateSketch.builder();
bldr.setLogNominalEntries(4);
UpdateSketch sk;
switch(skType) {
case EMPTY: { // { 1.0, 0, T} p and value are not used
sk = bldr.build();
break;
}
case EXACT: { // { 1.0, >0, F} p is not used
sk = bldr.build();
sk.update(value);
break;
}
case ESTIMATION: { // {<1.0, >0, F}
bldr.setP(p);
sk = bldr.build();
sk.update(value);
break;
}
case DEGENERATE: { // {<1.0, 0, F}
bldr.setP(p);
sk = bldr.build();
sk.update(value);
break;
}
default: { return null; } // should not happen
}
return sk;
}
// private static void println(Object o) {
// System.out.println(o.toString());
// }
//
// @Test
// public void printHash() {
// long seed = DEFAULT_UPDATE_SEED;
// long v = 6;
// long hash = (hash(v, seed)[0]) >>> 1;
// println(v + ", " + hash);
// }
//
// @Test
// public void printPAsLong() {
// float p = 0.5f;
// println("p = " + p + ", " + (long)(Long.MAX_VALUE * p));
// }
}
| 2,463 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/ThetaSketchCrossLanguageTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES;
import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES;
import static org.apache.datasketches.common.TestUtil.cppPath;
import static org.apache.datasketches.common.TestUtil.javaPath;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import org.apache.datasketches.memory.Memory;
import org.testng.annotations.Test;
/**
* Serialize binary sketches to be tested by C++ code.
* Test deserialization of binary sketches serialized by C++ code.
*/
public class ThetaSketchCrossLanguageTest {
@Test(groups = {GENERATE_JAVA_FILES})
public void generateBinariesForCompatibilityTesting() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000};
for (int n: nArr) {
final UpdateSketch sk = UpdateSketch.builder().build();
for (int i = 0; i < n; i++) sk.update(i);
Files.newOutputStream(javaPath.resolve("theta_n" + n + "_java.sk")).write(sk.compact().toByteArray());
}
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateBinariesForCompatibilityTestingNonEmptyNoEntries() throws IOException {
final UpdateSketch sk = UpdateSketch.builder().setP(0.01f).build();
sk.update(1);
assertFalse(sk.isEmpty());
assertEquals(sk.getRetainedEntries(), 0);
Files.newOutputStream(javaPath.resolve("theta_non_empty_no_entries_java.sk")).write(sk.compact().toByteArray());
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCpp() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("theta_n" + n + "_cpp.sk"));
final CompactSketch sketch = CompactSketch.wrap(Memory.wrap(bytes));
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
assertEquals(sketch.getEstimate(), n, n * 0.03);
assertTrue(sketch.isOrdered());
final HashIterator it = sketch.iterator();
long previous = 0;
while (it.next()) {
assertTrue(it.get() < sketch.getThetaLong());
assertTrue(it.get() > previous);
previous = it.get();
}
}
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCppCompressed() throws IOException {
final int[] nArr = {10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("theta_compressed_n" + n + "_cpp.sk"));
final CompactSketch sketch = CompactSketch.wrap(Memory.wrap(bytes));
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
assertEquals(sketch.getEstimate(), n, n * 0.03);
assertTrue(sketch.isOrdered());
final HashIterator it = sketch.iterator();
long previous = 0;
while (it.next()) {
assertTrue(it.get() < sketch.getThetaLong());
assertTrue(it.get() > previous);
previous = it.get();
}
}
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCppNonEmptyNoEntries() throws IOException {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("theta_non_empty_no_entries_cpp.sk"));
final CompactSketch sketch = CompactSketch.wrap(Memory.wrap(bytes));
assertFalse(sketch.isEmpty());
assertEquals(sketch.getRetainedEntries(), 0);
}
}
| 2,464 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/UnionImplTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.theta.BackwardConversions.convertSerVer3toSerVer1;
import static org.apache.datasketches.theta.BackwardConversions.convertSerVer3toSerVer2;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableHandle;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
public class UnionImplTest {
@Test
public void checkGetCurrentAndMaxBytes() {
final int lgK = 10;
final Union union = Sketches.setOperationBuilder().setLogNominalEntries(lgK).buildUnion();
assertEquals(union.getCurrentBytes(), 288);
assertEquals(union.getMaxUnionBytes(), 16416);
}
@Test
public void checkUpdateWithSketch() {
final int k = 16;
final WritableMemory mem = WritableMemory.writableWrap(new byte[k*8 + 24]);
final WritableMemory mem2 = WritableMemory.writableWrap(new byte[k*8 + 24]);
final UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i=0; i<k; i++) { sketch.update(i); }
final CompactSketch sketchInDirectOrd = sketch.compact(true, mem);
final CompactSketch sketchInDirectUnord = sketch.compact(false, mem2);
final CompactSketch sketchInHeap = sketch.compact(true, null);
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
union.union(sketchInDirectOrd);
union.union(sketchInHeap);
union.union(sketchInDirectUnord);
assertEquals(union.getResult().getEstimate(), k, 0.0);
}
@Test
public void checkUnorderedAndOrderedMemory() {
final int k = 16;
final WritableMemory mem = WritableMemory.writableWrap(new byte[k*8 + 24]);
final UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i = 0; i < k; i++) { sketch.update(i); }
final CompactSketch sketchInDirectOrd = sketch.compact(false, mem);
assertFalse(sketchInDirectOrd.isOrdered());
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
union.union(sketchInDirectOrd);
final double est1 = union.getResult().getEstimate();
sketch.compact(true, mem); //change the order as a side effect
assertTrue(sketchInDirectOrd.isOrdered());
union.union(sketchInDirectOrd);
final double est2 = union.getResult().getEstimate();
assertEquals(est1, est2);
assertEquals((int)est1, k);
}
@Test
public void checkUpdateWithMem() {
final int k = 16;
final WritableMemory skMem = WritableMemory.writableWrap(new byte[2*k*8 + 24]);
final WritableMemory dirOrdCskMem = WritableMemory.writableWrap(new byte[k*8 + 24]);
final WritableMemory dirUnordCskMem = WritableMemory.writableWrap(new byte[k*8 + 24]);
final UpdateSketch udSketch = UpdateSketch.builder().setNominalEntries(k).build(skMem);
for (int i = 0; i < k; i++) { udSketch.update(i); } //exact
udSketch.compact(true, dirOrdCskMem);
udSketch.compact(false, dirUnordCskMem);
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
union.union(skMem);
union.union(dirOrdCskMem);
union.union(dirUnordCskMem);
assertEquals(union.getResult().getEstimate(), k, 0.0);
}
@Test
public void checkUpdateWithMemV4Exact() {
int n = 1000;
UpdateSketch sk = Sketches.updateSketchBuilder().build();
for (int i = 0; i < n; i++) {
sk.update(i);
}
CompactSketch cs = sk.compact();
assertFalse(cs.isEstimationMode());
byte[] bytes = cs.toByteArrayCompressed();
final Union union = Sketches.setOperationBuilder().buildUnion();
union.union(Memory.wrap(bytes));
assertEquals(union.getResult().getEstimate(), n, 0.0);
}
@Test
public void checkFastWrap() {
final int k = 16;
final long seed = ThetaUtil.DEFAULT_UPDATE_SEED;
final int unionSize = Sketches.getMaxUnionBytes(k);
final WritableMemory srcMem = WritableMemory.writableWrap(new byte[unionSize]);
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion(srcMem);
for (int i = 0; i < k; i++) { union.update(i); } //exact
assertEquals(union.getResult().getEstimate(), k, 0.0);
final Union union2 = UnionImpl.fastWrap(srcMem, seed);
assertEquals(union2.getResult().getEstimate(), k, 0.0);
final Memory srcMemR = srcMem;
final Union union3 = UnionImpl.fastWrap(srcMemR, seed);
assertEquals(union3.getResult().getEstimate(), k, 0.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkCorruptFamilyException() {
final int k = 16;
final WritableMemory mem = WritableMemory.writableWrap(new byte[k*8 + 24]);
final UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
sketch.update(i);
}
sketch.compact(true, mem);
mem.putByte(PreambleUtil.FAMILY_BYTE, (byte)0); //corrupt family
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
union.union(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkVer2FamilyException() {
final int k = 16;
final UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
sketch.update(i);
}
final CompactSketch csk = sketch.compact(true, null);
final WritableMemory v2mem = (WritableMemory) convertSerVer3toSerVer2(csk, ThetaUtil.DEFAULT_UPDATE_SEED);
v2mem.putByte(PreambleUtil.FAMILY_BYTE, (byte)0); //corrupt family
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
union.union(v2mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkVer1FamilyException() {
final int k = 16;
final UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
sketch.update(i);
}
final CompactSketch csk = sketch.compact(true, null);
final WritableMemory v1mem = (WritableMemory) convertSerVer3toSerVer1(csk);
v1mem.putByte(PreambleUtil.FAMILY_BYTE, (byte)0); //corrupt family
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
union.union(v1mem);
}
@Test
public void checkVer2EmptyHandling() {
final int k = 16;
final UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build();
final Memory mem = convertSerVer3toSerVer2(sketch.compact(), ThetaUtil.DEFAULT_UPDATE_SEED);
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
union.union(mem);
}
@Test
public void checkMoveAndResize() {
final int k = 1 << 12;
final int u = 2 * k;
final int bytes = Sketches.getMaxUpdateSketchBytes(k);
try (WritableHandle wh = WritableMemory.allocateDirect(bytes/2);
WritableHandle wh2 = WritableMemory.allocateDirect(bytes/2) ) {
final WritableMemory wmem = wh.getWritable();
final UpdateSketch sketch = Sketches.updateSketchBuilder().setNominalEntries(k).build(wmem);
assertTrue(sketch.isSameResource(wmem));
final WritableMemory wmem2 = wh2.getWritable();
final Union union = SetOperation.builder().buildUnion(wmem2);
assertTrue(union.isSameResource(wmem2));
for (int i = 0; i < u; i++) { union.update(i); }
assertFalse(union.isSameResource(wmem));
final Union union2 = SetOperation.builder().buildUnion(); //on-heap union
assertFalse(union2.isSameResource(wmem2)); //obviously not
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkRestricted() {
final Union union = Sketches.setOperationBuilder().buildUnion();
assertTrue(union.isEmpty());
assertEquals(union.getThetaLong(), Long.MAX_VALUE);
assertEquals(union.getSeedHash(), ThetaUtil.computeSeedHash(ThetaUtil.DEFAULT_UPDATE_SEED));
assertEquals(union.getRetainedEntries(), 0);
assertEquals(union.getCache().length, 128); //only applies to stateful
}
@Test
public void checkUnionCompactOrderedSource() {
final int k = 1 << 12;
final UpdateSketch sk = Sketches.updateSketchBuilder().build();
for (int i = 0; i < k; i++) { sk.update(i); }
final double est1 = sk.getEstimate();
final int bytes = Sketches.getMaxCompactSketchBytes(sk.getRetainedEntries(true));
try (WritableHandle h = WritableMemory.allocateDirect(bytes)) {
final WritableMemory wmem = h.getWritable();
final CompactSketch csk = sk.compact(true, wmem); //ordered, direct
final Union union = Sketches.setOperationBuilder().buildUnion();
union.union(csk);
final double est2 = union.getResult().getEstimate();
assertEquals(est2, est1);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkCompactFlagCorruption() {
final int k = 1 << 12;
final int bytes = Sketch.getMaxUpdateSketchBytes(k);
final WritableMemory wmem1 = WritableMemory.allocate(bytes);
final UpdateSketch sk = Sketches.updateSketchBuilder().setNominalEntries(k).build(wmem1);
for (int i = 0; i < k; i++) { sk.update(i); }
sk.compact(true, wmem1); //corrupt the wmem1 to be a compact sketch
final Union union = SetOperation.builder().buildUnion();
union.union(sk); //update the union with the UpdateSketch object
final CompactSketch csk1 = union.getResult();
println(""+csk1.getEstimate());
}
@Test //checks for bug introduced in 1.0.0-incubating.
public void checkDirectUnionSingleItem() {
final int num = 2;
final UpdateSketch[] skArr = new UpdateSketch[num];
for (int i = 0; i < num; i++) {
skArr[i] = new UpdateSketchBuilder().build();
}
for (int i = 0; i < num/2; i++) {
skArr[i].update(i);
skArr[i + num/2].update(i);
skArr[i].update(i + num);
}
Union union = new SetOperationBuilder().buildUnion();
for (int i = 0; i < num; i++) {
union.union(skArr[i]);
}
CompactSketch csk = union.getResult();
assertEquals(csk.getEstimate(), 2.0);
//println(csk.toString(true, true, 1, true));
final Memory[] memArr = new Memory[num];
for (int i = 0; i < num; i++) {
memArr[i] = Memory.wrap(skArr[i].compact().toByteArray());
}
union = new SetOperationBuilder().buildUnion();
for (int i = 0; i < num; i++) {
union.union(memArr[i]);
}
csk = union.getResult();
assertEquals(csk.getEstimate(), 2.0);
//println(csk.toString(true, true, 1, true));
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param o value to print
*/
static void println(final Object o) {
//System.out.println(o.toString()); //disable here
}
}
| 2,465 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/SketchesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.theta.BackwardConversions.convertSerVer3toSerVer1;
import static org.apache.datasketches.theta.Sketches.getMaxCompactSketchBytes;
import static org.apache.datasketches.theta.Sketches.getMaxIntersectionBytes;
import static org.apache.datasketches.theta.Sketches.getMaxUnionBytes;
import static org.apache.datasketches.theta.Sketches.getMaxUpdateSketchBytes;
import static org.apache.datasketches.theta.Sketches.getSerializationVersion;
import static org.apache.datasketches.theta.Sketches.heapifySetOperation;
import static org.apache.datasketches.theta.Sketches.heapifySketch;
import static org.apache.datasketches.theta.Sketches.setOperationBuilder;
import static org.apache.datasketches.theta.Sketches.updateSketchBuilder;
import static org.apache.datasketches.theta.Sketches.wrapSetOperation;
import static org.apache.datasketches.theta.Sketches.wrapSketch;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class SketchesTest {
private static Memory getCompactSketchMemory(final int k, final int from, final int to) {
final UpdateSketch sk1 = updateSketchBuilder().setNominalEntries(k).build();
for (int i=from; i<to; i++) {
sk1.update(i);
}
final CompactSketch csk = sk1.compact(true, null);
final byte[] sk1bytes = csk.toByteArray();
final Memory mem = Memory.wrap(sk1bytes);
return mem;
}
private static Memory getMemoryFromCompactSketch(final CompactSketch csk) {
final byte[] sk1bytes = csk.toByteArray();
final Memory mem = Memory.wrap(sk1bytes);
return mem;
}
private static CompactSketch getCompactSketch(final int k, final int from, final int to) {
final UpdateSketch sk1 = updateSketchBuilder().setNominalEntries(k).build();
for (int i=from; i<to; i++) {
sk1.update(i);
}
return sk1.compact(true, null);
}
@Test
public void checkSketchMethods() {
final int k = 1024;
final Memory mem = getCompactSketchMemory(k, 0, k);
CompactSketch csk2 = (CompactSketch)heapifySketch(mem);
assertEquals((int)csk2.getEstimate(), k);
csk2 = (CompactSketch)heapifySketch(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
assertEquals((int)csk2.getEstimate(), k);
csk2 = (CompactSketch)wrapSketch(mem);
assertEquals((int)csk2.getEstimate(), k);
csk2 = (CompactSketch)wrapSketch(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
assertEquals((int)csk2.getEstimate(), k);
}
@Test
public void checkSetOpMethods() {
final int k = 1024;
final Memory mem1 = getCompactSketchMemory(k, 0, k);
final Memory mem2 = getCompactSketchMemory(k, k/2, 3*k/2);
final SetOperationBuilder bldr = setOperationBuilder();
final Union union = bldr.setNominalEntries(2 * k).buildUnion();
union.union(mem1);
CompactSketch cSk = union.getResult(true, null);
assertEquals((int)cSk.getEstimate(), k);
union.union(mem2);
cSk = union.getResult(true, null);
assertEquals((int)cSk.getEstimate(), 3*k/2);
final byte[] ubytes = union.toByteArray();
final WritableMemory uMem = WritableMemory.writableWrap(ubytes);
Union union2 = (Union)heapifySetOperation(uMem);
cSk = union2.getResult(true, null);
assertEquals((int)cSk.getEstimate(), 3*k/2);
union2 = (Union)heapifySetOperation(uMem, ThetaUtil.DEFAULT_UPDATE_SEED);
cSk = union2.getResult(true, null);
assertEquals((int)cSk.getEstimate(), 3*k/2);
union2 = (Union)wrapSetOperation(uMem);
cSk = union2.getResult(true, null);
assertEquals((int)cSk.getEstimate(), 3*k/2);
union2 = (Union)wrapSetOperation(uMem, ThetaUtil.DEFAULT_UPDATE_SEED);
cSk = union2.getResult(true, null);
assertEquals((int)cSk.getEstimate(), 3*k/2);
final int serVer = getSerializationVersion(uMem);
assertEquals(serVer, 3);
}
@Test
public void checkUtilMethods() {
final int k = 1024;
final int maxUnionBytes = getMaxUnionBytes(k);
assertEquals(2*k*8+32, maxUnionBytes);
final int maxInterBytes = getMaxIntersectionBytes(k);
assertEquals(2*k*8+24, maxInterBytes);
final int maxCompSkBytes = getMaxCompactSketchBytes(k+1);
assertEquals(24+(k+1)*8, maxCompSkBytes);
final int maxSkBytes = getMaxUpdateSketchBytes(k);
assertEquals(24+2*k*8, maxSkBytes);
}
@Test
public void checkStaticEstimators() {
final int k = 4096;
final int u = 4*k;
final CompactSketch csk = getCompactSketch(k, 0, u);
final Memory srcMem = getMemoryFromCompactSketch(csk);
final double est = Sketches.getEstimate(srcMem);
assertEquals(est, u, 0.05*u);
final double rse = 1.0/Math.sqrt(k);
final double ub = Sketches.getUpperBound(1, srcMem);
assertEquals(ub, est+rse, 0.05*u);
final double lb = Sketches.getLowerBound(1, srcMem);
assertEquals(lb, est-rse, 0.05*u);
final Memory memV1 = convertSerVer3toSerVer1(csk);
boolean empty = Sketches.getEmpty(memV1);
assertFalse(empty);
final CompactSketch csk2 = getCompactSketch(k, 0, 0);
final Memory emptyMemV3 = getMemoryFromCompactSketch(csk2);
assertEquals(Sketches.getRetainedEntries(emptyMemV3), 0);
assertEquals(Sketches.getThetaLong(emptyMemV3), Long.MAX_VALUE);
final Memory emptyMemV1 = convertSerVer3toSerVer1(csk2);
empty = Sketches.getEmpty(emptyMemV1);
assertTrue(empty);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSketchFamily() {
final Union union = setOperationBuilder().buildUnion();
final byte[] byteArr = union.toByteArray();
final Memory srcMem = Memory.wrap(byteArr);
Sketches.getEstimate(srcMem); //Union is not a Theta Sketch, it is an operation
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,466 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/ConcurrentHeapQuickSelectSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.theta.PreambleUtil.FAMILY_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.LG_NOM_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.Arrays;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author eshcar
*/
public class ConcurrentHeapQuickSelectSketchTest {
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
int lgK = 9;
int k = 1 << lgK;
int u = k;
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
for (int i = 0; i< u; i++) {
local.update(i);
}
waitForBgPropagationToComplete(shared);
assertFalse(local.isEmpty());
assertEquals(local.getEstimate(), u, 0.0);
assertEquals(shared.getRetainedEntries(false), u);
byte[] serArr = shared.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(serArr);
Sketch sk = Sketch.heapify(mem, sl.seed);
assertTrue(sk instanceof HeapQuickSelectSketch); //Intentional promotion to Parent
mem.putByte(SER_VER_BYTE, (byte) 0); //corrupt the SerVer byte
Sketch.heapify(mem, sl.seed);
}
@Test
public void checkPropagationNotOrdered() {
int lgK = 8;
int k = 1 << lgK;
int u = 200*k;
SharedLocal sl = new SharedLocal(lgK, 4, false, false);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertEquals((sl.bldr.getLocalLgNominalEntries()), 4);
assertTrue(local.isEmpty());
for (int i = 0; i < u; i++) {
local.update(i);
}
waitForBgPropagationToComplete(shared);
assertFalse(local.isEmpty());
assertTrue(shared.getRetainedEntries(true) <= u);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkIllegalSketchID_UpdateSketch() {
int lgK = 9;
int k = 1 << lgK;
int u = k;
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
assertTrue(shared instanceof ConcurrentHeapQuickSelectSketch);
for (int i = 0; i< u; i++) {
local.update(i);
}
assertTrue(shared.compact().isCompact());
assertFalse(local.isEmpty());
assertEquals(local.getEstimate(), u, 0.0);
assertEquals(shared.getRetainedEntries(false), u);
byte[] byteArray = shared.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(byteArray);
mem.putByte(FAMILY_BYTE, (byte) 0); //corrupt the Sketch ID byte
//try to heapify the corruped mem
Sketch.heapify(mem, sl.seed);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifySeedConflict() {
int lgK = 9;
long seed = 1021;
long seed2 = ThetaUtil.DEFAULT_UPDATE_SEED;
SharedLocal sl = new SharedLocal(lgK, lgK, seed);
byte[] byteArray = sl.shared.toByteArray();
Memory srcMem = Memory.wrap(byteArray);
Sketch.heapify(srcMem, seed2);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyCorruptLgNomLongs() {
int lgK = 4;
SharedLocal sl = new SharedLocal(lgK);
byte[] serArr = sl.shared.toByteArray();
WritableMemory srcMem = WritableMemory.writableWrap(serArr);
srcMem.putByte(LG_NOM_LONGS_BYTE, (byte)2); //corrupt
Sketch.heapify(srcMem, ThetaUtil.DEFAULT_UPDATE_SEED);
}
@Test(expectedExceptions = UnsupportedOperationException.class)
public void checkIllegalHashUpdate() {
int lgK = 4;
SharedLocal sl = new SharedLocal(lgK);
sl.shared.hashUpdate(1);
}
@Test
public void checkHeapifyByteArrayExact() {
int lgK = 9;
int k = 1 << lgK;
int u = k;
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
for (int i=0; i<u; i++) {
local.update(i);
}
waitForBgPropagationToComplete(shared);
byte[] serArr = shared.toByteArray();
Memory srcMem = Memory.wrap(serArr);
Sketch recoveredShared = Sketches.heapifyUpdateSketch(srcMem);
//reconstruct to Native/Direct
final int bytes = Sketch.getMaxUpdateSketchBytes(k);
final WritableMemory wmem = WritableMemory.allocate(bytes);
shared = sl.bldr.buildSharedFromSketch((UpdateSketch)recoveredShared, wmem);
UpdateSketch local2 = sl.bldr.buildLocal(shared);
assertEquals(local2.getEstimate(), u, 0.0);
assertEquals(local2.getLowerBound(2), u, 0.0);
assertEquals(local2.getUpperBound(2), u, 0.0);
assertFalse(local2.isEmpty());
assertFalse(local2.isEstimationMode());
assertEquals(local2.getResizeFactor(), local.getResizeFactor());
local2.toString(true, true, 8, true);
}
@Test
public void checkHeapifyByteArrayEstimating() {
int lgK = 12;
int k = 1 << lgK;
int u = 2*k;
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch local = sl.local;
UpdateSketch shared = sl.shared;
for (int i=0; i<u; i++) {
local.update(i);
}
waitForBgPropagationToComplete(shared);
double localEst = local.getEstimate();
double localLB = local.getLowerBound(2);
double localUB = local.getUpperBound(2);
assertTrue(local.isEstimationMode());
byte[] serArr = shared.toByteArray();
Memory srcMem = Memory.wrap(serArr);
UpdateSketch recoveredShared = UpdateSketch.heapify(srcMem, sl.seed);
final int bytes = Sketch.getMaxUpdateSketchBytes(k);
final WritableMemory wmem = WritableMemory.allocate(bytes);
shared = sl.bldr.buildSharedFromSketch(recoveredShared, wmem);
UpdateSketch local2 = sl.bldr.buildLocal(shared);
assertEquals(local2.getEstimate(), localEst);
assertEquals(local2.getLowerBound(2), localLB);
assertEquals(local2.getUpperBound(2), localUB);
assertFalse(local2.isEmpty());
assertTrue(local2.isEstimationMode());
assertEquals(local2.getResizeFactor(), local.getResizeFactor());
}
@Test
public void checkHeapifyMemoryEstimating() {
int lgK = 9;
int k = 1 << lgK;
int u = 2*k; //thus estimating
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch local = sl.local;
UpdateSketch shared = sl.shared;
for (int i=0; i<u; i++) {
local.update(i);
}
waitForBgPropagationToComplete(shared);
double localEst = local.getEstimate();
double localLB = local.getLowerBound(2);
double localUB = local.getUpperBound(2);
assertTrue(local.isEstimationMode());
assertFalse(local.isDirect());
assertFalse(local.hasMemory());
byte[] serArr = shared.toByteArray();
Memory srcMem = Memory.wrap(serArr);
UpdateSketch recoveredShared = UpdateSketch.heapify(srcMem, ThetaUtil.DEFAULT_UPDATE_SEED);
final int bytes = Sketch.getMaxUpdateSketchBytes(k);
final WritableMemory wmem = WritableMemory.allocate(bytes);
shared = sl.bldr.buildSharedFromSketch(recoveredShared, wmem);
UpdateSketch local2 = sl.bldr.buildLocal(shared);
assertEquals(local2.getEstimate(), localEst);
assertEquals(local2.getLowerBound(2), localLB);
assertEquals(local2.getUpperBound(2), localUB);
assertEquals(local2.isEmpty(), false);
assertTrue(local2.isEstimationMode());
}
@Test
public void checkHQStoCompactForms() {
int lgK = 9;
int k = 1 << lgK;
int u = 4*k; //thus estimating
int maxBytes = (k << 4) + (Family.QUICKSELECT.getMinPreLongs() << 3);
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertEquals(local.getClass().getSimpleName(), "ConcurrentHeapThetaBuffer");
assertFalse(local.isDirect());
assertFalse(local.hasMemory());
for (int i=0; i<u; i++) {
local.update(i);
}
waitForBgPropagationToComplete(shared);
shared.rebuild(); //forces size back to k
//get baseline values
double localEst = local.getEstimate();
double localLB = local.getLowerBound(2);
double localUB = local.getUpperBound(2);
int sharedBytes = shared.getCurrentBytes();
int sharedCompBytes = shared.getCompactBytes();
assertEquals(sharedBytes, maxBytes);
assertTrue(local.isEstimationMode());
CompactSketch comp1, comp2, comp3, comp4;
comp1 = shared.compact(false, null);
assertEquals(comp1.getEstimate(), localEst);
assertEquals(comp1.getLowerBound(2), localLB);
assertEquals(comp1.getUpperBound(2), localUB);
assertEquals(comp1.isEmpty(), false);
assertTrue(comp1.isEstimationMode());
assertEquals(comp1.getCompactBytes(), sharedCompBytes);
assertEquals(comp1.getClass().getSimpleName(), "HeapCompactSketch");
comp2 = shared.compact(true, null);
assertEquals(comp2.getEstimate(), localEst);
assertEquals(comp2.getLowerBound(2), localLB);
assertEquals(comp2.getUpperBound(2), localUB);
assertEquals(comp2.isEmpty(), false);
assertTrue(comp2.isEstimationMode());
assertEquals(comp2.getCompactBytes(), sharedCompBytes);
assertEquals(comp2.getClass().getSimpleName(), "HeapCompactSketch");
byte[] memArr2 = new byte[sharedCompBytes];
WritableMemory mem2 = WritableMemory.writableWrap(memArr2); //allocate mem for compact form
comp3 = shared.compact(false, mem2); //load the mem2
assertEquals(comp3.getEstimate(), localEst);
assertEquals(comp3.getLowerBound(2), localLB);
assertEquals(comp3.getUpperBound(2), localUB);
assertEquals(comp3.isEmpty(), false);
assertTrue(comp3.isEstimationMode());
assertEquals(comp3.getCompactBytes(), sharedCompBytes);
assertEquals(comp3.getClass().getSimpleName(), "DirectCompactSketch");
mem2.clear();
comp4 = shared.compact(true, mem2);
assertEquals(comp4.getEstimate(), localEst);
assertEquals(comp4.getLowerBound(2), localLB);
assertEquals(comp4.getUpperBound(2), localUB);
assertEquals(comp4.isEmpty(), false);
assertTrue(comp4.isEstimationMode());
assertEquals(comp4.getCompactBytes(), sharedCompBytes);
assertEquals(comp4.getClass().getSimpleName(), "DirectCompactSketch");
comp4.toString(false, true, 0, false);
}
@Test
public void checkHQStoCompactEmptyForms() {
int lgK = 9;
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
println("lgArr: "+ local.getLgArrLongs());
//empty
local.toString(false, true, 0, false);
boolean estimating = false;
assertTrue(local instanceof ConcurrentHeapThetaBuffer);
double localEst = local.getEstimate();
double localLB = local.getLowerBound(2);
double localUB = local.getUpperBound(2);
//int currentUSBytes = local.getCurrentBytes(false);
//assertEquals(currentUSBytes, (32*8) + 24); // clumsy, but a function of RF and TCF
int compBytes = local.getCompactBytes(); //compact form
assertEquals(compBytes, 8);
assertEquals(local.isEstimationMode(), estimating);
byte[] arr2 = new byte[compBytes];
WritableMemory mem2 = WritableMemory.writableWrap(arr2);
CompactSketch csk2 = shared.compact(false, mem2);
assertEquals(csk2.getEstimate(), localEst);
assertEquals(csk2.getLowerBound(2), localLB);
assertEquals(csk2.getUpperBound(2), localUB);
assertEquals(csk2.isEmpty(), true);
assertEquals(csk2.isEstimationMode(), estimating);
assertTrue(csk2.isOrdered());
CompactSketch csk3 = shared.compact(true, mem2);
csk3.toString(false, true, 0, false);
csk3.toString();
assertEquals(csk3.getEstimate(), localEst);
assertEquals(csk3.getLowerBound(2), localLB);
assertEquals(csk3.getUpperBound(2), localUB);
assertEquals(csk3.isEmpty(), true);
assertEquals(csk3.isEstimationMode(), estimating);
assertTrue(csk3.isOrdered());
}
@Test
public void checkExactMode() {
int lgK = 12;
int u = 1 << lgK;
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
for (int i = 0; i< u; i++) {
local.update(i);
}
waitForBgPropagationToComplete(shared);
assertEquals(local.getEstimate(), u, 0.0);
assertEquals(shared.getRetainedEntries(false), u);
}
@Test
public void checkEstMode() {
int lgK = 12;
int k = 1 << lgK;
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
int u = 3*k;
for (int i = 0; i< u; i++) {
local.update(i);
}
waitForBgPropagationToComplete(shared);
final int retained = shared.getRetainedEntries(false);
assertTrue(retained > k);
// it could be exactly k, but in this case must be greater
}
@Test
public void checkErrorBounds() {
int lgK = 9;
int k = 1 << lgK;
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch local = sl.local;
UpdateSketch shared = sl.shared;
//Exact mode
//int limit = (int)ConcurrentSharedThetaSketch.computeExactLimit(lim, 0); //? ask Eshcar
for (int i = 0; i < k; i++ ) {
local.update(i);
}
double est = local.getEstimate();
double lb = local.getLowerBound(2);
double ub = local.getUpperBound(2);
assertEquals(est, ub, 0.0);
assertEquals(est, lb, 0.0);
//Est mode
int u = 2 * k;
for (int i = k; i < u; i++ ) {
local.update(i);
local.update(i); //test duplicate rejection
}
waitForBgPropagationToComplete(shared);
est = local.getEstimate();
lb = local.getLowerBound(2);
ub = local.getUpperBound(2);
assertTrue(est <= ub);
assertTrue(est >= lb);
}
@Test
public void checkRebuild() {
int lgK = 4;
int k = 1 << lgK;
SharedLocal sl = new SharedLocal(lgK);
//must build shared first
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
int t = ((ConcurrentHeapThetaBuffer)local).getHashTableThreshold();
for (int i = 0; i< t; i++) {
local.update(i);
}
waitForBgPropagationToComplete(shared);
assertFalse(local.isEmpty());
assertTrue(local.getEstimate() > 0.0);
assertTrue(shared.getRetainedEntries(false) > k);
shared.rebuild();
assertEquals(shared.getRetainedEntries(false), k);
assertEquals(shared.getRetainedEntries(true), k);
shared.rebuild();
assertEquals(shared.getRetainedEntries(false), k);
assertEquals(shared.getRetainedEntries(true), k);
}
@Test
public void checkBuilder() {
int lgK = 4;
SharedLocal sl = new SharedLocal(lgK);
assertEquals(sl.bldr.getLocalLgNominalEntries(), lgK);
assertEquals(sl.bldr.getLgNominalEntries(), lgK);
println(sl.bldr.toString());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBuilderSmallNominal() {
int lgK = 2; //too small
new SharedLocal(lgK);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkNegativeHashes() {
int lgK = 9;
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch local = sl.local;
local.hashUpdate(-1L);
}
@Test
public void checkResetAndStartingSubMultiple() {
int lgK = 9;
int k = 1 << lgK;
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch shared = sl.shared;
UpdateSketch local = sl.local;
assertTrue(local.isEmpty());
int u = 3*k;
for (int i = 0; i< u; i++) { local.update(i); }
waitForBgPropagationToComplete(shared);
assertFalse(local.isEmpty());
assertTrue(shared.getRetainedEntries(false) >= k);
assertTrue(local.getThetaLong() < Long.MAX_VALUE);
shared.reset();
local.reset();
assertTrue(local.isEmpty());
assertEquals(shared.getRetainedEntries(false), 0);
assertEquals(local.getEstimate(), 0.0, 0.0);
assertEquals(local.getThetaLong(), Long.MAX_VALUE);
}
@Test
public void checkDQStoCompactEmptyForms() {
int lgK = 9;
SharedLocal sl = new SharedLocal(lgK);
UpdateSketch local = sl.local;
UpdateSketch shared = sl.shared;
//empty
local.toString(false, true, 0, false); //exercise toString
assertTrue(local instanceof ConcurrentHeapThetaBuffer);
double localEst = local.getEstimate();
double localLB = local.getLowerBound(2);
double uskUB = local.getUpperBound(2);
assertFalse(local.isEstimationMode());
int bytes = local.getCompactBytes();
assertEquals(bytes, 8);
byte[] memArr2 = new byte[bytes];
WritableMemory mem2 = WritableMemory.writableWrap(memArr2);
CompactSketch csk2 = shared.compact(false, mem2);
assertEquals(csk2.getEstimate(), localEst);
assertEquals(csk2.getLowerBound(2), localLB);
assertEquals(csk2.getUpperBound(2), uskUB);
assertTrue(csk2.isEmpty());
assertFalse(csk2.isEstimationMode());
assertTrue(csk2.isOrdered());
CompactSketch csk3 = shared.compact(true, mem2);
csk3.toString(false, true, 0, false);
csk3.toString();
assertEquals(csk3.getEstimate(), localEst);
assertEquals(csk3.getLowerBound(2), localLB);
assertEquals(csk3.getUpperBound(2), uskUB);
assertTrue(csk3.isEmpty());
assertFalse(csk3.isEstimationMode());
assertTrue(csk2.isOrdered());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMinReqBytes() {
int lgK = 4;
int k = 1 << lgK;
SharedLocal sl = new SharedLocal(lgK);
for (int i = 0; i < (4 * k); i++) { sl.local.update(i); }
waitForBgPropagationToComplete(sl.shared);
byte[] byteArray = sl.shared.toByteArray();
byte[] badBytes = Arrays.copyOfRange(byteArray, 0, 24); //corrupt no. bytes
Memory mem = Memory.wrap(badBytes);
Sketch.heapify(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkThetaAndLgArrLongs() {
int lgK = 4;
int k = 1 << lgK;
SharedLocal sl = new SharedLocal(lgK);
for (int i = 0; i < k; i++) { sl.local.update(i); }
waitForBgPropagationToComplete(sl.shared);
byte[] badArray = sl.shared.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(badArray);
PreambleUtil.insertLgArrLongs(mem, 4); //corrupt
PreambleUtil.insertThetaLong(mem, Long.MAX_VALUE / 2); //corrupt
Sketch.heapify(mem);
}
@Test
public void checkFamily() {
SharedLocal sl = new SharedLocal();
UpdateSketch local = sl.local;
assertEquals(local.getFamily(), Family.QUICKSELECT);
}
@Test
public void checkBackgroundPropagation() {
int lgK = 4;
int k = 1 << lgK;
int u = 5*k;
SharedLocal sl = new SharedLocal(lgK);
assertTrue(sl.local.isEmpty());
int i = 0;
for (; i < k; i++) { sl.local.update(i); } //exact
waitForBgPropagationToComplete(sl.shared);
assertFalse(sl.local.isEmpty());
assertTrue(sl.local.getEstimate() > 0.0);
long theta1 = sl.sharedIf.getVolatileTheta();
for (; i < u; i++) { sl.local.update(i); } //continue, make it estimating
waitForBgPropagationToComplete(sl.shared);
long theta2 = sl.sharedIf.getVolatileTheta();
int entries = sl.shared.getRetainedEntries(false);
assertTrue((entries > k) || (theta2 < theta1),
"entries= " + entries + " k= " + k + " theta1= " + theta1 + " theta2= " + theta2);
sl.shared.rebuild();
assertEquals(sl.shared.getRetainedEntries(false), k);
assertEquals(sl.shared.getRetainedEntries(true), k);
sl.local.rebuild();
assertEquals(sl.shared.getRetainedEntries(false), k);
assertEquals(sl.shared.getRetainedEntries(true), k);
}
@Test
public void checkBuilderExceptions() {
UpdateSketchBuilder bldr = new UpdateSketchBuilder();
try {
bldr.setNominalEntries(8);
fail();
} catch (SketchesArgumentException e) { }
try {
bldr.setLocalNominalEntries(8);
fail();
} catch (SketchesArgumentException e) { }
try {
bldr.setLocalLogNominalEntries(3);
fail();
} catch (SketchesArgumentException e) { }
bldr.setNumPoolThreads(4);
assertEquals(bldr.getNumPoolThreads(), 4);
bldr.setMaxConcurrencyError(0.04);
assertEquals(bldr.getMaxConcurrencyError(), 0.04);
bldr.setMaxNumLocalThreads(4);
assertEquals(bldr.getMaxNumLocalThreads(), 4);
}
@Test(expectedExceptions = UnsupportedOperationException.class)
public void checkToByteArray() {
SharedLocal sl = new SharedLocal();
sl.local.toByteArray();
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
static class SharedLocal {
static final long DefaultSeed = ThetaUtil.DEFAULT_UPDATE_SEED;
final UpdateSketch shared;
final ConcurrentSharedThetaSketch sharedIf;
final UpdateSketch local;
final int sharedLgK;
final int localLgK;
final long seed;
final WritableMemory wmem;
final UpdateSketchBuilder bldr = new UpdateSketchBuilder();
SharedLocal() {
this(9, 9, DefaultSeed, false, true, 1);
}
SharedLocal(int lgK) {
this(lgK, lgK, DefaultSeed, false, true, 1);
}
SharedLocal(int sharedLgK, int localLgK) {
this(sharedLgK, localLgK, DefaultSeed, false, true, 1);
}
SharedLocal(int sharedLgK, int localLgK, long seed) {
this(sharedLgK, localLgK, seed, false, true, 1);
}
SharedLocal(int sharedLgK, int localLgK, boolean useMem) {
this(sharedLgK, localLgK, DefaultSeed, useMem, true, 1);
}
SharedLocal(int sharedLgK, int localLgK, boolean useMem, boolean ordered) {
this(sharedLgK, localLgK, DefaultSeed, useMem, ordered, 1);
}
SharedLocal(int sharedLgK, int localLgK, long seed, boolean useMem, boolean ordered, int memMult) {
this.sharedLgK = sharedLgK;
this.localLgK = localLgK;
this.seed = seed;
if (useMem) {
int bytes = (((4 << sharedLgK) * memMult) + (Family.QUICKSELECT.getMaxPreLongs())) << 3;
wmem = WritableMemory.allocate(bytes);
} else {
wmem = null;
}
bldr.setLogNominalEntries(sharedLgK);
bldr.setLocalLogNominalEntries(localLgK);
bldr.setPropagateOrderedCompact(ordered);
bldr.setSeed(this.seed);
shared = bldr.buildShared(wmem);
local = bldr.buildLocal(shared);
sharedIf = (ConcurrentSharedThetaSketch) shared;
}
}
static void waitForBgPropagationToComplete(UpdateSketch shared) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
ConcurrentSharedThetaSketch csts = (ConcurrentSharedThetaSketch)shared;
csts.awaitBgPropagationTermination();
ConcurrentPropagationService.resetExecutorService(Thread.currentThread().getId());
csts.initBgPropagationService();
}
}
| 2,467 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/DirectUnionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.datasketches.theta.BackwardConversions.convertSerVer3toSerVer1;
import static org.apache.datasketches.theta.BackwardConversions.convertSerVer3toSerVer2;
import static org.apache.datasketches.theta.HeapUnionTest.testAllCompactForms;
import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.apache.datasketches.theta.SetOperation.getMaxUnionBytes;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.Arrays;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class DirectUnionTest {
@Test
public void checkExactUnionNoOverlap() {
final int lgK = 9; //512
final int k = 1 << lgK;
final int u = k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u/2; i++) {
usk1.update(i); //256
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //256 no overlap
}
assertEquals(u, usk1.getEstimate() + usk2.getEstimate(), 0.0); //exact, no overlap
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(usk1); //update with heap UpdateSketch
union.union(usk2); //update with heap UpdateSketch
testAllCompactForms(union, u, 0.0);
}
@Test
public void checkEstUnionNoOverlap() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u/2; i++) {
usk1.update(i); //2*k
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2*k no overlap
}
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(usk1); //update with heap UpdateSketch
union.union(usk2); //update with heap UpdateSketch
testAllCompactForms(union, u, 0.05);
}
@Test
public void checkExactUnionWithOverlap() {
final int lgK = 9; //512
final int k = 1 << lgK;
final int u = k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u/2; i++) {
usk1.update(i); //256
}
for (int i=0; i<u ; i++) {
usk2.update(i); //512, 256 overlapped
}
assertEquals(u, usk1.getEstimate() + usk2.getEstimate()/2, 0.0); //exact, overlapped
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(usk1); //update with heap UpdateSketch
union.union(usk2); //update with heap UpdateSketch
testAllCompactForms(union, u, 0.0);
}
@Test
public void checkHeapifyExact() {
final int lgK = 9; //512
final int k = 1 << lgK;
final int u = k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u/2; i++) {
usk1.update(i); //256
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //256 no overlap
}
assertEquals(u, usk1.getEstimate() + usk2.getEstimate(), 0.0); //exact, no overlap
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(usk1); //update with heap UpdateSketch
union.union(usk2); //update with heap UpdateSketch
testAllCompactForms(union, u, 0.0);
final Union union2 = (Union)SetOperation.heapify(WritableMemory.writableWrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.0);
}
//these parallel the checkHeapifyExact, etc.
@Test
public void checkWrapExact() {
final int lgK = 9; //512
final int k = 1 << lgK;
final int u = k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u/2; i++) {
usk1.update(i); //256
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //256 no overlap
}
assertEquals(u, usk1.getEstimate() + usk2.getEstimate(), 0.0); //exact, no overlap
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(usk1); //update with heap UpdateSketch
union.union(usk2); //update with heap UpdateSketch
testAllCompactForms(union, u, 0.0);
final Union union2 = Sketches.wrapUnion(WritableMemory.writableWrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.0);
}
@Test
public void checkWrapEstNoOverlap() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); //2k estimating
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(2 * k).build(); //2k exact
for (int i=0; i<u/2; i++) {
usk1.update(i); //2k
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2k no overlap, exact
}
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(usk1); //update with heap UpdateSketch
union.union(usk2); //update with heap UpdateSketch, early stop not possible
testAllCompactForms(union, u, 0.05);
final Union union2 = Sketches.wrapUnion(WritableMemory.writableWrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.05);
}
@Test
public void checkWrapEstNoOverlapOrderedIn() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); //2k estimating
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(2 * k).build(); //2k exact for early stop test
for (int i=0; i<u/2; i++) {
usk1.update(i); //2k estimating
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2k no overlap, exact, will force early stop
}
final CompactSketch cosk2 = usk2.compact(true, null);
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(usk1); //update with heap UpdateSketch
union.union(cosk2); //update with heap Compact, Ordered input, early stop
UpdateSketch emptySketch = UpdateSketch.builder().setNominalEntries(k).build();
union.union(emptySketch); //updates with empty
emptySketch = null;
union.union(emptySketch); //updates with null
testAllCompactForms(union, u, 0.05);
final Union union2 = Sketches.wrapUnion(WritableMemory.writableWrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.05);
union2.reset();
assertEquals(union2.getResult(true, null).getEstimate(), 0.0, 0.0);
}
@Test
public void checkWrapEstNoOverlapOrderedDirectIn() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); //2k estimating
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(2 * k).build(); //2k exact for early stop test
for (int i=0; i<u/2; i++) {
usk1.update(i); //2k estimating
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2k no overlap, exact, will force early stop
}
final WritableMemory cskMem2 = WritableMemory.writableWrap(new byte[usk2.getCompactBytes()]);
final CompactSketch cosk2 = usk2.compact(true, cskMem2); //ordered, loads the cskMem2 as ordered
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(usk1); //updates with heap UpdateSketch
union.union(cosk2); //updates with direct CompactSketch, ordered, use early stop
UpdateSketch emptySketch = UpdateSketch.builder().setNominalEntries(k).build();
union.union(emptySketch); //updates with empty sketch
emptySketch = null;
union.union(emptySketch); //updates with null sketch
testAllCompactForms(union, u, 0.05);
final Union union2 = Sketches.wrapUnion(WritableMemory.writableWrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.05);
union2.reset();
assertEquals(union2.getResult(true, null).getEstimate(), 0.0, 0.0);
}
@Test
public void checkWrapEstNoOverlapOrderedMemIn() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); //2k estimating
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(2 * k).build(); //2k exact for early stop test
for (int i=0; i<u/2; i++) {
usk1.update(i); //2k estimating
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2k no overlap, exact, will force early stop
}
final WritableMemory cskMem2 = WritableMemory.writableWrap(new byte[usk2.getCompactBytes()]);
usk2.compact(true, cskMem2); //ordered, loads the cskMem2 as ordered
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(usk1); //updates with heap UpdateSketch
union.union(cskMem2); //updates with direct CompactSketch, ordered, use early stop
UpdateSketch emptySketch = UpdateSketch.builder().setNominalEntries(k).build();
union.union(emptySketch); //updates with empty sketch
emptySketch = null;
union.union(emptySketch); //updates with null sketch
testAllCompactForms(union, u, 0.05);
final Union union2 = Sketches.wrapUnion(WritableMemory.writableWrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.05);
union2.reset();
assertEquals(union2.getResult(true, null).getEstimate(), 0.0, 0.0);
}
@Test
public void checkWrapEstNoOverlapUnorderedMemIn() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); //2k estimating
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(2 * k).build(); //2k exact for early stop test
for (int i=0; i<u/2; i++) {
usk1.update(i); //2k estimating
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2k no overlap, exact, will force early stop
}
final WritableMemory cskMem2 = WritableMemory.writableWrap(new byte[usk2.getCompactBytes()]);
usk2.compact(false, cskMem2); //unordered, loads the cskMem2 as unordered
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(usk1); //updates with heap UpdateSketch
union.union(cskMem2); //updates with direct CompactSketch, ordered, use early stop
UpdateSketch emptySketch = UpdateSketch.builder().setNominalEntries(k).build();
union.union(emptySketch); //updates with empty sketch
emptySketch = null;
union.union(emptySketch); //updates with null sketch
testAllCompactForms(union, u, 0.05);
final Union union2 = Sketches.wrapUnion(WritableMemory.writableWrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.05);
union2.reset();
assertEquals(union2.getResult(true, null).getEstimate(), 0.0, 0.0);
}
@Test
public void checkMultiUnion() {
final int lgK = 13; //8192
final int k = 1 << lgK;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk3 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk4 = UpdateSketch.builder().setNominalEntries(k).build();
int v=0;
int u = 1000000;
for (int i=0; i<u; i++) {
usk1.update(i+v);
}
v += u;
u = 26797;
for (int i=0; i<u; i++) {
usk2.update(i+v);
}
v += u;
for (int i=0; i<u; i++) {
usk3.update(i+v);
}
v += u;
for (int i=0; i<u; i++) {
usk4.update(i+v);
}
v += u;
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(usk1); //updates with heap UpdateSketch
union.union(usk2); //updates with heap UpdateSketch
union.union(usk3); //updates with heap UpdateSketch
union.union(usk4); //updates with heap UpdateSketch
final CompactSketch csk = union.getResult(true, null);
final double est = csk.getEstimate();
assertEquals(est, v, .01*v);
}
@Test
public void checkDirectMemoryIn() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u1 = 2*k;
final int u2 = 1024; //smaller exact sketch forces early stop
final int totU = u1+u2;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u1; i++) {
usk1.update(i); //2*k
}
for (int i=u1; i<totU; i++) {
usk2.update(i); //2*k + 1024 no overlap
}
final Memory skMem1 = Memory.wrap(usk1.compact(false, null).toByteArray());
final Memory skMem2 = Memory.wrap(usk2.compact(true, null).toByteArray());
final CompactSketch csk1 = (CompactSketch)Sketch.wrap(skMem1);
final CompactSketch csk2 = (CompactSketch)Sketch.wrap(skMem2);
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(csk1);
union.union(csk2);
final CompactSketch cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), totU, .05*k);
}
@Test
public void checkSerVer1Handling() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u1 = 2*k;
final int u2 = 1024; //smaller exact sketch forces early stop
final int totU = u1+u2;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u1; i++) {
usk1.update(i); //2*k
}
for (int i=u1; i<totU; i++) {
usk2.update(i); //2*k + 1024 no overlap
}
final Memory v1mem1 = convertSerVer3toSerVer1(usk1.compact(true, null));
final Memory v1mem2 = convertSerVer3toSerVer1(usk2.compact(true, null));
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(v1mem1);
union.union(v1mem2);
final CompactSketch cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), totU, .05*k);
}
@Test
public void checkSerVer2Handling() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u1 = 2*k;
final int u2 = 1024; //smaller exact sketch forces early stop
final int totU = u1+u2;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u1; i++) {
usk1.update(i); //2*k
}
for (int i=u1; i<totU; i++) {
usk2.update(i); //2*k + 1024 no overlap
}
final Memory v2mem1 = convertSerVer3toSerVer2(usk1.compact(true, null), ThetaUtil.DEFAULT_UPDATE_SEED);
final Memory v2mem2 = convertSerVer3toSerVer2(usk2.compact(true, null), ThetaUtil.DEFAULT_UPDATE_SEED);
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(v2mem1);
union.union(v2mem2);
final CompactSketch cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), totU, .05*k);
}
@Test
public void checkUpdateMemorySpecialCases() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final CompactSketch usk1c = usk1.compact(true, null);
WritableMemory v3mem1 = WritableMemory.writableWrap(usk1c.toByteArray());
final Memory v1mem1 = convertSerVer3toSerVer1(usk1c);
WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(v1mem1);
CompactSketch cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), 0.0, 0.0);
final Memory v2mem1 = convertSerVer3toSerVer2(usk1c, ThetaUtil.DEFAULT_UPDATE_SEED);
uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(v2mem1);
cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), 0.0, 0.0);
uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(v3mem1);
cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), 0.0, 0.0);
uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
v3mem1 = null;
union.union(v3mem1);
cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), 0.0, 0.0);
}
@Test
public void checkUpdateMemorySpecialCases2() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 2*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u; i++)
{
usk1.update(i); //force prelongs to 3
}
final CompactSketch usk1c = usk1.compact(true, null);
final WritableMemory v3mem1 = WritableMemory.writableWrap(usk1c.toByteArray());
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(v3mem1);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMemBadSerVer() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
usk1.update(1);
usk1.update(2);
final CompactSketch usk1c = usk1.compact(true, null);
final WritableMemory v3mem1 = WritableMemory.writableWrap(usk1c.toByteArray());
//corrupt SerVer
v3mem1.putByte(SER_VER_BYTE, (byte)0);
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(v3mem1);
}
@Test
public void checkEmptySerVer2and3() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final CompactSketch usk1c = usk1.compact(true, null);
final byte[] skArr = usk1c.toByteArray();
final byte[] skArr2 = Arrays.copyOf(skArr, skArr.length * 2);
final WritableMemory v3mem1 = WritableMemory.writableWrap(skArr2);
WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(v3mem1);
final Memory v2mem1 = convertSerVer3toSerVer2(usk1c, ThetaUtil.DEFAULT_UPDATE_SEED);
final WritableMemory v2mem2 = WritableMemory.writableWrap(new byte[16]);
v2mem1.copyTo(0, v2mem2, 0, 8);
uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.union(v2mem2);
}
//Special DirectUnion cases
@Test //Himanshu's issue
public void checkDirectWrap() {
final int nomEntries = 16;
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(nomEntries)]);
SetOperation.builder().setNominalEntries(nomEntries).buildUnion(uMem);
final UpdateSketch sk1 = UpdateSketch.builder().setNominalEntries(nomEntries).build();
sk1.update("a");
sk1.update("b");
final UpdateSketch sk2 = UpdateSketch.builder().setNominalEntries(nomEntries).build();
sk2.update("c");
sk2.update("d");
Union union = Sketches.wrapUnion(uMem);
union.union(sk1);
union = Sketches.wrapUnion(uMem);
union.union(sk2);
final CompactSketch sketch = union.getResult(true, null);
assertEquals(4.0, sketch.getEstimate(), 0.0);
}
@Test
public void checkEmptyUnionCompactResult() {
final int k = 64;
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
final WritableMemory mem = WritableMemory.writableWrap(new byte[Sketch.getMaxCompactSketchBytes(0)]);
final CompactSketch csk = union.getResult(false, mem); //DirectCompactSketch
assertTrue(csk.isEmpty());
}
@Test
public void checkEmptyUnionCompactOrderedResult() {
final int k = 64;
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
final WritableMemory mem = WritableMemory.writableWrap(new byte[Sketch.getMaxCompactSketchBytes(0)]);
final CompactSketch csk = union.getResult(true, mem); //DirectCompactSketch
assertTrue(csk.isEmpty());
}
@Test
public void checkUnionMemToString() {
final int k = 64;
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]); //union memory
SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
}
@Test
public void checkGetResult() {
final int k = 1024;
final UpdateSketch sk = Sketches.updateSketchBuilder().build();
final int memBytes = getMaxUnionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion(iMem);
union.union(sk);
final CompactSketch csk = union.getResult();
assertEquals(csk.getCompactBytes(), 8);
}
@Test
public void checkPrimitiveUpdates() {
final int k = 32;
final WritableMemory uMem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion(uMem);
union.update(1L);
union.update(1.5); //#1 double
union.update(0.0);
union.update(-0.0);
String s = null;
union.update(s); //null string
s = "";
union.update(s); //empty string
s = "String";
union.update(s); //#2 actual string
byte[] byteArr = null;
union.update(byteArr); //null byte[]
byteArr = new byte[0];
union.update(byteArr); //empty byte[]
byteArr = "Byte Array".getBytes(UTF_8);
union.update(byteArr); //#3 actual byte[]
int[] intArr = null;
union.update(intArr); //null int[]
intArr = new int[0];
union.update(intArr); //empty int[]
final int[] intArr2 = { 1, 2, 3, 4, 5 };
union.update(intArr2); //#4 actual int[]
long[] longArr = null;
union.update(longArr); //null long[]
longArr = new long[0];
union.update(longArr); //empty long[]
final long[] longArr2 = { 6, 7, 8, 9 };
union.update(longArr2); //#5 actual long[]
final CompactSketch comp = union.getResult();
final double est = comp.getEstimate();
final boolean empty = comp.isEmpty();
assertEquals(est, 7.0, 0.0);
assertFalse(empty);
}
@Test
public void checkGetFamily() {
final int k = 16;
final WritableMemory mem = WritableMemory.writableWrap(new byte[k*16 +32]);
final SetOperation setOp = new SetOperationBuilder().setNominalEntries(k).build(Family.UNION, mem);
assertEquals(setOp.getFamily(), Family.UNION);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkPreambleLongsCorruption() {
final int k = 16;
final WritableMemory mem = WritableMemory.writableWrap(new byte[k*16 +32]);
final SetOperation setOp = new SetOperationBuilder().setNominalEntries(k).build(Family.UNION, mem);
println(setOp.toString());
final int familyID = PreambleUtil.extractFamilyID(mem);
final int preLongs = PreambleUtil.extractPreLongs(mem);
assertEquals(familyID, Family.UNION.getID());
assertEquals(preLongs, Family.UNION.getMaxPreLongs());
PreambleUtil.insertPreLongs(mem, 3); //Corrupt with 3; correct value is 4
DirectQuickSelectSketch.writableWrap(mem, ThetaUtil.DEFAULT_UPDATE_SEED);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkSizeTooSmall() {
final int k = 16;
final WritableMemory mem = WritableMemory.writableWrap(new byte[k*16 +32]); //initialized
final SetOperation setOp = new SetOperationBuilder().setNominalEntries(k).build(Family.UNION, mem);
println(setOp.toString());
final WritableMemory mem2 = WritableMemory.writableWrap(new byte[32]); //for just preamble
mem.copyTo(0, mem2, 0, 32); //too small
DirectQuickSelectSketch.writableWrap(mem2, ThetaUtil.DEFAULT_UPDATE_SEED);
}
@Test
public void checkForDruidBug() {
final int k = 16384;
final UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build();
for (int i = 0; i < 100000; i++) {
usk.update(Integer.toString(i));
}
usk.rebuild(); //optional but created the symptom
final Sketch s = usk.compact();
//create empty target union in off-heap mem
final WritableMemory mem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]);
final Union union1 = SetOperation.builder().setNominalEntries(k).buildUnion(mem);
union1.union(s);
final CompactSketch csk = union1.getResult();
assertTrue(csk.getTheta() < 0.2);
assertEquals(csk.getRetainedEntries(true), 16384);
final double est = csk.getEstimate();
assertTrue(est > 98663.0);
assertTrue(est < 101530.0);
}
@Test
public void checkForDruidBug2() { //update union with just sketch memory reference
final int k = 16384;
final UpdateSketch usk = UpdateSketch.builder().setNominalEntries(k).build();
for (int i = 0; i < 100000; i++) {
usk.update(Integer.toString(i));
}
usk.rebuild(); //optional but created the symptom
final WritableMemory memIn = WritableMemory.allocate(usk.getCompactBytes());
usk.compact(true, memIn); //side effect of loading the memIn
//create empty target union in off-heap mem
final WritableMemory mem = WritableMemory.writableWrap(new byte[getMaxUnionBytes(k)]);
final Union union1 = SetOperation.builder().setNominalEntries(k).buildUnion(mem);
union1.union(memIn);
final CompactSketch csk = union1.getResult();
assertTrue(csk.getTheta() < 0.2);
assertEquals(csk.getRetainedEntries(true), 16384);
final double est = csk.getEstimate();
assertTrue(est > 98663.0);
assertTrue(est < 101530.0);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //Disable here
}
}
| 2,468 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/AnotBimplTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class AnotBimplTest {
@Test
public void checkExactAnotB_AvalidNoOverlap() {
final int k = 512;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k/2; i++) {
usk1.update(i);
}
for (int i=k/2; i<k; i++) {
usk2.update(i);
}
final AnotB aNb = SetOperation.builder().buildANotB();
assertTrue(aNb.isEmpty()); //only applies to stateful
assertTrue(aNb.getCache().length == 0); //only applies to stateful
assertEquals(aNb.getThetaLong(), Long.MAX_VALUE); //only applies to stateful
assertEquals(aNb.getSeedHash(), ThetaUtil.computeSeedHash(ThetaUtil.DEFAULT_UPDATE_SEED));
aNb.setA(usk1);
aNb.notB(usk2);
assertEquals(aNb.getRetainedEntries(), k/2);
CompactSketch rsk1;
rsk1 = aNb.getResult(false, null, true); //not ordered, reset
assertEquals(rsk1.getEstimate(), k/2.0);
aNb.setA(usk1);
aNb.notB(usk2);
rsk1 = aNb.getResult(true, null, true); //ordered, reset
assertEquals(rsk1.getEstimate(), k/2.0);
final int bytes = rsk1.getCurrentBytes();
final WritableMemory wmem = WritableMemory.allocate(bytes);
aNb.setA(usk1);
aNb.notB(usk2);
rsk1 = aNb.getResult(false, wmem, true); //unordered, reset
assertEquals(rsk1.getEstimate(), k/2.0);
aNb.setA(usk1);
aNb.notB(usk2);
rsk1 = aNb.getResult(true, wmem, true); //ordered, reset
assertEquals(rsk1.getEstimate(), k/2.0);
}
@Test
public void checkCombinations() {
final int k = 512;
final UpdateSketch aNull = null;
final UpdateSketch bNull = null;
final UpdateSketch aEmpty = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch bEmpty = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch aHT = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
aHT.update(i);
}
final CompactSketch aC = aHT.compact(false, null);
final CompactSketch aO = aHT.compact(true, null);
final UpdateSketch bHT = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=k/2; i<k+k/2; i++) {
bHT.update(i); //overlap is k/2
}
final CompactSketch bC = bHT.compact(false, null);
final CompactSketch bO = bHT.compact(true, null);
CompactSketch result;
AnotB aNb;
final boolean ordered = true;
aNb = SetOperation.builder().buildANotB();
try { aNb.setA(aNull); fail();} catch (final SketchesArgumentException e) {}
aNb.notB(bNull); //ok
try { aNb.aNotB(aNull, bNull); fail(); } catch (final SketchesArgumentException e) {}
try { aNb.aNotB(aNull, bEmpty); fail(); } catch (final SketchesArgumentException e) {}
try { aNb.aNotB(aEmpty, bNull); fail(); } catch (final SketchesArgumentException e) {}
result = aNb.aNotB(aEmpty, bEmpty, !ordered, null);
assertEquals(result.getEstimate(), 0.0);
assertTrue(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aEmpty, bC, !ordered, null);
assertEquals(result.getEstimate(), 0.0);
assertTrue(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aEmpty, bO, !ordered, null);
assertEquals(result.getEstimate(), 0.0);
assertTrue(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aEmpty, bHT, !ordered, null);
assertEquals(result.getEstimate(), 0.0);
assertTrue(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aC, bEmpty, !ordered, null);
assertEquals(result.getEstimate(), k);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aC, bC, !ordered, null);
assertEquals(result.getEstimate(), k / 2.0);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aC, bO, !ordered, null);
assertEquals(result.getEstimate(), k / 2.0);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aC, bHT, !ordered, null);
assertEquals(result.getEstimate(), k / 2.0);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aO, bEmpty, !ordered, null);
assertEquals(result.getEstimate(), k);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aO, bC, !ordered, null);
assertEquals(result.getEstimate(), k / 2.0);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aO, bO, !ordered, null);
assertEquals(result.getEstimate(), k / 2.0);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aO, bHT, !ordered, null);
assertEquals(result.getEstimate(), k / 2.0);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aHT, bEmpty, !ordered, null);
assertEquals(result.getEstimate(), k);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aHT, bC, !ordered, null);
assertEquals(result.getEstimate(), k / 2.0);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aHT, bO, !ordered, null);
assertEquals(result.getEstimate(), k / 2.0);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
result = aNb.aNotB(aHT, bHT, !ordered, null);
assertEquals(result.getEstimate(), k / 2.0);
assertFalse(result.isEmpty());
assertEquals(result.getThetaLong(), Long.MAX_VALUE);
}
@Test
public void checkAnotBnotC() {
final int k = 1024;
final boolean ordered = true;
final UpdateSketch aU = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k; i++) { aU.update(i); } //All 1024
final UpdateSketch bU = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k/2; i++) { bU.update(i); } //first 512
final UpdateSketch cU = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=k/2; i<3*k/4; i++) { cU.update(i); } //third 256
final int memBytes = Sketch.getMaxUpdateSketchBytes(k);
CompactSketch result1, result2, result3;
final WritableMemory wmem1 = WritableMemory.allocate(memBytes);
final WritableMemory wmem2 = WritableMemory.allocate(memBytes);
final WritableMemory wmem3 = WritableMemory.allocate(memBytes);
final AnotB aNb = SetOperation.builder().buildANotB();
//Note: stateful and stateless operations can be interleaved, they are independent.
aNb.setA(aU); //stateful
result1 = aNb.aNotB(aU, bU, ordered, wmem1); //stateless
aNb.notB(bU); //stateful
result2 = aNb.aNotB(result1, cU, ordered, wmem2); //stateless
aNb.notB(cU); //stateful
final double est2 = result2.getEstimate(); //stateless result
println("est: "+est2);
assertEquals(est2, k/4.0, 0.0);
result3 = aNb.getResult(ordered, wmem3, true); //stateful result, then reset
final double est3 = result3.getEstimate();
assertEquals(est3, k/4.0, 0.0);
}
@Test
public void checkAnotBnotC_sameMemory() {
final int k = 1024;
final boolean ordered = true;
final UpdateSketch a = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k; i++) { a.update(i); } //All 1024
final UpdateSketch b = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k/2; i++) { b.update(i); } //first 512
final UpdateSketch c = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=k/2; i<3*k/4; i++) { c.update(i); } //third 256
final int memBytes = Sketch.getMaxCompactSketchBytes(a.getRetainedEntries(true));
final WritableMemory mem = WritableMemory.allocate(memBytes);
CompactSketch result1, result2;
final AnotB aNb = SetOperation.builder().buildANotB();
//Note: stateful and stateless operations can be interleaved, they are independent.
aNb.setA(a); //stateful
result1 = aNb.aNotB(a, b, ordered, mem); //stateless
aNb.notB(b); //stateful
result1 = aNb.aNotB(result1, c, ordered, mem); //stateless
aNb.notB(c); //stateful
result2 = aNb.getResult(ordered, mem, true); //stateful result, then reset
final double est1 = result1.getEstimate(); //check stateless result
println("est: "+est1);
assertEquals(est1, k/4.0, 0.0);
final double est2 = result2.getEstimate(); //check stateful result
assertEquals(est2, k/4.0, 0.0);
}
@Test
public void checkAnotBsimple() {
final UpdateSketch skA = Sketches.updateSketchBuilder().build();
final UpdateSketch skB = Sketches.updateSketchBuilder().build();
final AnotB aNotB = Sketches.setOperationBuilder().buildANotB();
final CompactSketch csk = aNotB.aNotB(skA, skB);
assertEquals(csk.getCurrentBytes(), 8);
}
@Test
public void checkGetResult() {
final UpdateSketch skA = Sketches.updateSketchBuilder().build();
final UpdateSketch skB = Sketches.updateSketchBuilder().build();
final AnotB aNotB = Sketches.setOperationBuilder().buildANotB();
final CompactSketch csk = aNotB.aNotB(skA, skB);
assertEquals(csk.getCurrentBytes(), 8);
}
@Test
public void checkGetFamily() {
//cheap trick
final AnotBimpl anotb = new AnotBimpl(ThetaUtil.DEFAULT_UPDATE_SEED);
assertEquals(anotb.getFamily(), Family.A_NOT_B);
}
@Test
public void checkGetMaxBytes() {
final int bytes = Sketches.getMaxAnotBResultBytes(10);
assertEquals(bytes, 16 * 15 + 24);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,469 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/HeapUnionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.datasketches.theta.BackwardConversions.convertSerVer3toSerVer1;
import static org.apache.datasketches.theta.BackwardConversions.convertSerVer3toSerVer2;
import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import java.util.Arrays;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class HeapUnionTest {
@Test
public void checkExactUnionNoOverlap() {
final int lgK = 9; //512
final int k = 1 << lgK;
final int u = k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u/2; i++) {
usk1.update(i); //256
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //256 no overlap
}
assertEquals(u, usk1.getEstimate() + usk2.getEstimate(), 0.0); //exact, no overlap
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(usk1); //update with heap UpdateSketch
union.union(usk2); //update with heap UpdateSketch
testAllCompactForms(union, u, 0.0);
}
@Test
public void checkEstUnionNoOverlap() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u/2; i++) {
usk1.update(i); //2*k
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2*k no overlap
}
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(usk1); //update with heap UpdateSketch
union.union(usk2); //update with heap UpdateSketch
testAllCompactForms(union, u, 0.05);
}
@Test
public void checkExactUnionWithOverlap() {
final int lgK = 9; //512
final int k = 1 << lgK;
final int u = k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u/2; i++) {
usk1.update(i); //256
}
for (int i=0; i<u ; i++) {
usk2.update(i); //512, 256 overlapped
}
assertEquals(u, usk1.getEstimate() + usk2.getEstimate()/2, 0.0); //exact, overlapped
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(usk1); //update with heap UpdateSketch
union.union(usk2); //update with heap UpdateSketch
testAllCompactForms(union, u, 0.0);
}
@Test
public void checkHeapifyExact() {
final int lgK = 9; //512
final int k = 1 << lgK;
final int u = k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u/2; i++) {
usk1.update(i); //256
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //256 no overlap
}
assertEquals(u, usk1.getEstimate() + usk2.getEstimate(), 0.0); //exact, no overlap
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(usk1); //update with heap UpdateSketch
union.union(usk2); //update with heap UpdateSketch
testAllCompactForms(union, u, 0.0);
final Union union2 = (Union)SetOperation.heapify(Memory.wrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.0);
}
@Test
public void checkHeapifyEstNoOverlap() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); //2k estimating
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(2 * k).build(); //2k exact
for (int i=0; i<u/2; i++) {
usk1.update(i); //2k
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2k no overlap, exact
}
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(usk1); //update with heap UpdateSketch
union.union(usk2); //update with heap UpdateSketch, early stop not possible
testAllCompactForms(union, u, 0.05);
final Union union2 = (Union)SetOperation.heapify(Memory.wrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.05);
}
@Test
public void checkHeapifyEstNoOverlapOrderedIn() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); //2k estimating
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(2 * k).build(); //2k exact for early stop test
for (int i=0; i<u/2; i++) {
usk1.update(i); //2k
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2k no overlap, exact, will force early stop
}
final CompactSketch cosk2 = usk2.compact(true, null);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(usk1); //update with heap UpdateSketch
union.union(cosk2); //update with heap Compact, Ordered input, early stop
UpdateSketch emptySketch = UpdateSketch.builder().setNominalEntries(k).build();
union.union(emptySketch); //updates with empty
emptySketch = null;
union.union(emptySketch); //updates with null
testAllCompactForms(union, u, 0.05);
final Union union2 = (Union)SetOperation.heapify(Memory.wrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.05);
union2.reset();
assertEquals(union2.getResult(true, null).getEstimate(), 0.0, 0.0);
}
@Test
public void checkWrapEstNoOverlapOrderedDirectIn() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); //2k estimating
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(2 * k).build(); //2k exact for early stop test
for (int i=0; i<u/2; i++) {
usk1.update(i); //2k estimating
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2k no overlap, exact, will force early stop
}
final WritableMemory cskMem2 = WritableMemory.writableWrap(new byte[usk2.getCompactBytes()]);
final CompactSketch cosk2 = usk2.compact(true, cskMem2); //ordered, loads the cskMem2 as ordered
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(usk1); //updates with heap UpdateSketch
union.union(cosk2); //updates with direct CompactSketch, ordered, use early stop
UpdateSketch emptySketch = UpdateSketch.builder().setNominalEntries(k).build();
union.union(emptySketch); //updates with empty sketch
emptySketch = null;
union.union(emptySketch); //updates with null sketch
testAllCompactForms(union, u, 0.05);
final Union union2 = (Union)SetOperation.heapify(Memory.wrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.05);
union2.reset();
assertEquals(union2.getResult(true, null).getEstimate(), 0.0, 0.0);
}
@Test
public void checkHeapifyEstNoOverlapOrderedMemIn() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); //2k estimating
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(2 * k).build(); //2k exact for early stop test
for (int i=0; i<u/2; i++) {
usk1.update(i); //2k estimating
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2k no overlap, exact, will force early stop
}
final WritableMemory cskMem2 = WritableMemory.writableWrap(new byte[usk2.getCompactBytes()]);
usk2.compact(true, cskMem2); //ordered, loads the cskMem2 as ordered
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(usk1); //updates with heap UpdateSketch
union.union(cskMem2); //updates with direct CompactSketch, ordered, use early stop
UpdateSketch emptySketch = UpdateSketch.builder().setNominalEntries(k).build();
union.union(emptySketch); //updates with empty sketch
emptySketch = null;
union.union(emptySketch); //updates with null sketch
testAllCompactForms(union, u, 0.05);
final Union union2 = (Union)SetOperation.heapify(Memory.wrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.05);
union2.reset();
assertEquals(union2.getResult(true, null).getEstimate(), 0.0, 0.0);
}
@Test
public void checkHeapifyEstNoOverlapUnorderedMemIn() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); //2k estimating
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(2 * k).build(); //2k exact for early stop test
for (int i=0; i<u/2; i++) {
usk1.update(i); //2k estimating
}
for (int i=u/2; i<u; i++) {
usk2.update(i); //2k no overlap, exact, will force early stop
}
final WritableMemory cskMem2 = WritableMemory.writableWrap(new byte[usk2.getCompactBytes()]);
usk2.compact(false, cskMem2); //unordered, loads the cskMem2 as unordered
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(usk1); //updates with heap UpdateSketch
union.union(cskMem2); //updates with direct CompactSketch, ordered, use early stop
UpdateSketch emptySketch = UpdateSketch.builder().setNominalEntries(k).build();
union.union(emptySketch); //updates with empty sketch
emptySketch = null;
union.union(emptySketch); //updates with null sketch
testAllCompactForms(union, u, 0.05);
final Union union2 = (Union)SetOperation.heapify(Memory.wrap(union.toByteArray()));
testAllCompactForms(union2, u, 0.05);
union2.reset();
assertEquals(union2.getResult(true, null).getEstimate(), 0.0, 0.0);
}
@Test
public void checkMultiUnion() {
final int lgK = 13; //8192
final int k = 1 << lgK;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk3 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk4 = UpdateSketch.builder().setNominalEntries(k).build();
int v=0;
int u = 1000000;
for (int i=0; i<u; i++) {
usk1.update(i+v);
}
v += u;
u = 26797;
for (int i=0; i<u; i++) {
usk2.update(i+v);
}
v += u;
for (int i=0; i<u; i++) {
usk3.update(i+v);
}
v += u;
for (int i=0; i<u; i++) {
usk4.update(i+v);
}
v += u;
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(usk1); //updates with heap UpdateSketch
union.union(usk2); //updates with heap UpdateSketch
union.union(usk3); //updates with heap UpdateSketch
union.union(usk4); //updates with heap UpdateSketch
final CompactSketch csk = union.getResult(true, null);
final double est = csk.getEstimate();
assertEquals(est, v, .01*v);
}
@Test
public void checkDirectMemoryIn() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u1 = 2*k;
final int u2 = 1024; //smaller exact sketch forces early stop
final int totU = u1+u2;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u1; i++) {
usk1.update(i); //2*k
}
for (int i=u1; i<totU; i++) {
usk2.update(i); //2*k + 1024 no overlap
}
final WritableMemory skMem1 = WritableMemory.writableWrap(usk1.compact(false, null).toByteArray());
final WritableMemory skMem2 = WritableMemory.writableWrap(usk2.compact(true, null).toByteArray());
final CompactSketch csk1 = (CompactSketch)Sketch.wrap(skMem1);
final CompactSketch csk2 = (CompactSketch)Sketch.wrap(skMem2);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(csk1);
union.union(csk2);
final CompactSketch cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), totU, .05*k);
}
@Test
public void checkSerVer1Handling() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u1 = 2*k;
final int u2 = 1024; //smaller exact sketch forces early stop
final int totU = u1+u2;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u1; i++) {
usk1.update(i); //2*k
}
for (int i=u1; i<totU; i++) {
usk2.update(i); //2*k + 1024 no overlap
}
final Memory v1mem1 = convertSerVer3toSerVer1(usk1.compact(true, null));
final Memory v1mem2 = convertSerVer3toSerVer1(usk2.compact(true, null));
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(v1mem1);
union.union(v1mem2);
final CompactSketch cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), totU, .05*k);
}
@Test
public void checkSerVer2Handling() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u1 = 2*k;
final int u2 = 1024; //smaller exact sketch forces early stop
final int totU = u1+u2;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u1; i++) {
usk1.update(i); //2*k
}
for (int i=u1; i<totU; i++) {
usk2.update(i); //2*k + 1024 no overlap
}
final Memory v2mem1 = convertSerVer3toSerVer2(usk1.compact(true, null), ThetaUtil.DEFAULT_UPDATE_SEED);
final Memory v2mem2 = convertSerVer3toSerVer2(usk2.compact(true, null), ThetaUtil.DEFAULT_UPDATE_SEED);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(v2mem1);
union.union(v2mem2);
final CompactSketch cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), totU, .05*k);
}
@Test
public void checkUpdateMemorySpecialCases() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final CompactSketch usk1c = usk1.compact(true, null);
WritableMemory v3mem1 = WritableMemory.writableWrap(usk1c.toByteArray());
final Memory v1mem1 = convertSerVer3toSerVer1(usk1.compact(true, null));
Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(v1mem1);
CompactSketch cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), 0.0, 0.0);
final Memory v2mem1 = convertSerVer3toSerVer2(usk1.compact(true, null), ThetaUtil.DEFAULT_UPDATE_SEED);
union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(v2mem1);
cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), 0.0, 0.0);
union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(v3mem1);
cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), 0.0, 0.0);
union = SetOperation.builder().setNominalEntries(k).buildUnion();
v3mem1 = null;
union.union(v3mem1);
cOut = union.getResult(true, null);
assertEquals(cOut.getEstimate(), 0.0, 0.0);
}
@Test
public void checkUpdateMemorySpecialCases2() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final int u = 2*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u; i++)
{
usk1.update(i); //force prelongs to 3
}
final CompactSketch usk1c = usk1.compact(true, null);
final WritableMemory v3mem1 = WritableMemory.writableWrap(usk1c.toByteArray());
//println(PreambleUtil.toString(v3mem1));
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(v3mem1);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMemBadSerVer() {
final int lgK = 12; //4096
final int k = 1 << lgK;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
usk1.update(1);
usk1.update(2);
final CompactSketch usk1c = usk1.compact(true, null);
final WritableMemory v3mem1 = WritableMemory.writableWrap(usk1c.toByteArray());
//corrupt SerVer
v3mem1.putByte(SER_VER_BYTE, (byte)0);
final Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(v3mem1);
}
@Test
public void checkEmptySerVer2and3() {
final UpdateSketch usk1 = UpdateSketch.builder().build();
final CompactSketch usk1c = usk1.compact(true, null);
final byte[] skArr = usk1c.toByteArray();
final byte[] skArr2 = Arrays.copyOf(skArr, skArr.length * 2);
final WritableMemory v3mem1 = WritableMemory.writableWrap(skArr2);
Union union = SetOperation.builder().buildUnion();
union.union(v3mem1);
final Memory v2mem1 = convertSerVer3toSerVer2(usk1c, ThetaUtil.DEFAULT_UPDATE_SEED);
final WritableMemory v2mem2 = WritableMemory.writableWrap(new byte[16]);
v2mem1.copyTo(0, v2mem2, 0, 8);
union = SetOperation.builder().buildUnion();
union.union(v2mem2);
}
@Test
public void checkGetResult() {
final int k = 1024;
final UpdateSketch sk = Sketches.updateSketchBuilder().build();
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
union.union(sk);
final CompactSketch csk = union.getResult();
assertEquals(csk.getCompactBytes(), 8);
}
@Test
public void checkTrimToK() {
final int hiK = 1024;
final int loK = 512;
final UpdateSketch hiSk = Sketches.updateSketchBuilder().setNominalEntries(hiK).build();
for (int i = 0; i < 3749; i++) { hiSk.update(i); } //count = 1920
final UpdateSketch loSk = Sketches.updateSketchBuilder().setNominalEntries(loK).build();
for (int i = 0; i < 1783; i++) { loSk.update(i + 10000); } //count = 960
final Union union = Sketches.setOperationBuilder().setNominalEntries(hiK).buildUnion();
CompactSketch csk = union.union(hiSk, loSk);
println(csk.toString());
assertEquals(csk.getRetainedEntries(), 1024);
}
@Test
public void checkPrimitiveUpdates() {
final int k = 32;
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
union.update(1L); //#1 long
union.update(1.5); //#2 double
union.update(0.0);
union.update(-0.0); //#3 double
String s = null;
union.update(s); //null string
s = "";
union.update(s); //empty string
s = "String";
union.update(s); //#4 actual string
byte[] byteArr = null;
union.update(byteArr); //null byte[]
byteArr = new byte[0];
union.update(byteArr); //empty byte[]
byteArr = "Byte Array".getBytes(UTF_8);
union.update(byteArr); //#5 actual byte[]
char[] charArr = null;
union.update(charArr); //null char[]
charArr = new char[0];
union.update(charArr); //empty char[]
charArr = "String".toCharArray();
union.update(charArr); //#6 actual char[]
int[] intArr = null;
union.update(intArr); //null int[]
intArr = new int[0];
union.update(intArr); //empty int[]
final int[] intArr2 = { 1, 2, 3, 4, 5 };
union.update(intArr2); //#7 actual int[]
long[] longArr = null;
union.update(longArr); //null long[]
longArr = new long[0];
union.update(longArr); //empty long[]
final long[] longArr2 = { 6, 7, 8, 9 };
union.update(longArr2); //#8 actual long[]
final CompactSketch comp = union.getResult();
final double est = comp.getEstimate();
final boolean empty = comp.isEmpty();
assertEquals(est, 8.0, 0.0);
assertFalse(empty);
}
//used by DirectUnionTest as well
public static void testAllCompactForms(final Union union, final double expected, final double toll) {
double compEst1, compEst2;
compEst1 = union.getResult(false, null).getEstimate(); //not ordered, no mem
assertEquals(compEst1, expected, toll*expected);
final CompactSketch comp2 = union.getResult(true, null); //ordered, no mem
compEst2 = comp2.getEstimate();
assertEquals(compEst2, compEst1, 0.0);
final WritableMemory mem = WritableMemory.writableWrap(new byte[comp2.getCurrentBytes()]);
compEst2 = union.getResult(false, mem).getEstimate(); //not ordered, mem
assertEquals(compEst2, compEst1, 0.0);
compEst2 = union.getResult(true, mem).getEstimate(); //ordered, mem
assertEquals(compEst2, compEst1, 0.0);
}
@Test
public void checkGetFamily() {
final SetOperation setOp = new SetOperationBuilder().build(Family.UNION);
assertEquals(setOp.getFamily(), Family.UNION);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //Disable here
}
}
| 2,470 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/UpdateSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.insertLgArrLongs;
import static org.apache.datasketches.theta.PreambleUtil.insertLgNomLongs;
import static org.apache.datasketches.theta.PreambleUtil.insertLgResizeFactor;
import static org.apache.datasketches.theta.UpdateSketch.isResizeFactorIncorrect;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.MemoryRequestServer;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class UpdateSketchTest {
@Test
public void checkOtherUpdates() {
int k = 512;
UpdateSketch sk1 = UpdateSketch.builder().setNominalEntries(k).build();
sk1.update(1L); //#1 long
sk1.update(1.5); //#2 double
sk1.update(0.0);
sk1.update(-0.0); //#3 double
String s = null;
sk1.update(s); //null string
s = "";
sk1.update(s); //empty string
s = "String";
sk1.update(s); //#4 actual string
byte[] byteArr = null;
sk1.update(byteArr); //null byte[]
byteArr = new byte[0];
sk1.update(byteArr); //empty byte[]
byteArr = "Byte Array".getBytes(UTF_8);
sk1.update(byteArr); //#5 actual byte[]
char[] charArr = null;
sk1.update(charArr); //null char[]
charArr = new char[0];
sk1.update(charArr); //empty char[]
charArr = "String".toCharArray();
sk1.update(charArr); //#6 actual char[]
int[] intArr = null;
sk1.update(intArr); //null int[]
intArr = new int[0];
sk1.update(intArr); //empty int[]
int[] intArr2 = { 1, 2, 3, 4, 5 };
sk1.update(intArr2); //#7 actual int[]
long[] longArr = null;
sk1.update(longArr); //null long[]
longArr = new long[0];
sk1.update(longArr); //empty long[]
long[] longArr2 = { 6, 7, 8, 9 };
sk1.update(longArr2); //#8 actual long[]
double est = sk1.getEstimate();
assertEquals(est, 8.0, 0.0);
}
@Test
public void checkStartingSubMultiple() {
int lgSubMul;
lgSubMul = ThetaUtil.startingSubMultiple(10, ResizeFactor.X1.lg(), 5);
assertEquals(lgSubMul, 10);
lgSubMul = ThetaUtil.startingSubMultiple(10, ResizeFactor.X2.lg(), 5);
assertEquals(lgSubMul, 5);
lgSubMul = ThetaUtil.startingSubMultiple(10, ResizeFactor.X4.lg(), 5);
assertEquals(lgSubMul, 6);
lgSubMul = ThetaUtil.startingSubMultiple(10, ResizeFactor.X8.lg(), 5);
assertEquals(lgSubMul, 7);
lgSubMul = ThetaUtil.startingSubMultiple(4, ResizeFactor.X1.lg(), 5);
assertEquals(lgSubMul, 5);
}
@Test
public void checkBuilder() {
UpdateSketchBuilder bldr = UpdateSketch.builder();
long seed = 12345L;
bldr.setSeed(seed);
assertEquals(bldr.getSeed(), seed);
float p = (float)0.5;
bldr.setP(p);
assertEquals(bldr.getP(), p);
ResizeFactor rf = ResizeFactor.X4;
bldr.setResizeFactor(rf);
assertEquals(bldr.getResizeFactor(), rf);
Family fam = Family.ALPHA;
bldr.setFamily(fam);
assertEquals(bldr.getFamily(), fam);
int lgK = 10;
int k = 1 << lgK;
bldr.setNominalEntries(k);
assertEquals(bldr.getLgNominalEntries(), lgK);
MemoryRequestServer mrs = new DefaultMemoryRequestServer();
bldr.setMemoryRequestServer(mrs);
assertEquals(bldr.getMemoryRequestServer(), mrs);
println(bldr.toString());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBuilderNomEntries() {
UpdateSketchBuilder bldr = UpdateSketch.builder();
int k = 1 << 27;
bldr.setNominalEntries(k);
}
@Test
public void checkCompact() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
CompactSketch csk = sk.compact();
assertEquals(csk.getCompactBytes(), 8);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkIncompatibleFamily() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
sk.update(1);
WritableMemory wmem = WritableMemory.writableWrap(sk.compact().toByteArray());
UpdateSketch.wrap(wmem, ThetaUtil.DEFAULT_UPDATE_SEED);
}
@Test
public void checkCorruption() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
sk.update(1);
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
try {
wmem.putByte(SER_VER_BYTE, (byte) 2);
UpdateSketch.wrap(wmem, ThetaUtil.DEFAULT_UPDATE_SEED);
fail();
} catch (SketchesArgumentException e) { }
try {
wmem.putByte(SER_VER_BYTE, (byte) 3);
wmem.putByte(PREAMBLE_LONGS_BYTE, (byte) 2);
UpdateSketch.wrap(wmem, ThetaUtil.DEFAULT_UPDATE_SEED);
fail();
} catch (SketchesArgumentException e) { }
}
@Test
public void checkIsResizeFactorIncorrect() {
WritableMemory wmem = WritableMemory.allocate(8);
insertLgNomLongs(wmem, 26);
for (int lgK = 4; lgK <= 26; lgK++) {
insertLgNomLongs(wmem, lgK);
int lgT = lgK + 1;
for (int lgA = 5; lgA <= lgT; lgA++) {
insertLgArrLongs(wmem, lgA);
for (int lgR = 0; lgR <= 3; lgR++) {
insertLgResizeFactor(wmem, lgR);
boolean lgRbad = isResizeFactorIncorrect(wmem, lgK, lgA);
boolean rf123 = (lgR > 0) && !(((lgT - lgA) % lgR) == 0);
boolean rf0 = (lgR == 0) && (lgA != lgT);
assertTrue((lgRbad == rf0) || (lgRbad == rf123));
}
}
}
}
@SuppressWarnings("unused")
@Test
public void checkCompactOpsMemoryToCompact() {
WritableMemory skwmem, cskwmem1, cskwmem2, cskwmem3;
CompactSketch csk1, csk2, csk3;
int lgK = 6;
UpdateSketch sk = Sketches.updateSketchBuilder().setLogNominalEntries(lgK).build();
int n = 1 << (lgK + 1);
for (int i = 2; i < n; i++) { sk.update(i); }
int cbytes = sk.getCompactBytes();
byte[] byteArr = sk.toByteArray();
skwmem = WritableMemory.writableWrap(byteArr);
cskwmem1 = WritableMemory.allocate(cbytes);
cskwmem2 = WritableMemory.allocate(cbytes);
cskwmem3 = WritableMemory.allocate(cbytes);
csk1 = sk.compact(true, cskwmem1);
csk2 = CompactOperations.memoryToCompact(skwmem, true, cskwmem2);
csk3 = CompactOperations.memoryToCompact(cskwmem1, true, cskwmem3);
assertTrue(cskwmem1.equals(cskwmem2));
assertTrue(cskwmem1.equals(cskwmem3));
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,471 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/DirectIntersectionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.apache.datasketches.theta.SetOperation.CONST_PREAMBLE_LONGS;
import static org.apache.datasketches.theta.SetOperation.getMaxIntersectionBytes;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesReadOnlyException;
import org.apache.datasketches.common.SketchesStateException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class DirectIntersectionTest {
private static final int PREBYTES = CONST_PREAMBLE_LONGS << 3; //24
@Test
public void checkExactIntersectionNoOverlap() {
final int lgK = 9;
final int k = 1<<lgK;
Intersection inter;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k/2; i++) {
usk1.update(i);
}
for (int i=k/2; i<k; i++) {
usk2.update(i);
}
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(usk1);
inter.intersect(usk2);
final long[] cache = inter.getCache(); //only applies to stateful
assertEquals(cache.length, 32);
CompactSketch rsk1;
final boolean ordered = true;
assertTrue(inter.hasResult());
rsk1 = inter.getResult(!ordered, null);
assertEquals(rsk1.getEstimate(), 0.0);
rsk1 = inter.getResult(ordered, null);
assertEquals(rsk1.getEstimate(), 0.0);
final int bytes = rsk1.getCompactBytes();
final byte[] byteArray = new byte[bytes];
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
rsk1 = inter.getResult(!ordered, mem);
assertEquals(rsk1.getEstimate(), 0.0);
//executed twice to fully exercise the internal state machine
rsk1 = inter.getResult(ordered, mem);
assertEquals(rsk1.getEstimate(), 0.0);
}
@Test
public void checkExactIntersectionFullOverlap() {
final int lgK = 9;
final int k = 1<<lgK;
Intersection inter;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
usk1.update(i);
}
for (int i=0; i<k; i++) {
usk2.update(i);
}
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(usk1);
inter.intersect(usk2);
CompactSketch rsk1;
final boolean ordered = true;
rsk1 = inter.getResult(!ordered, null);
assertEquals(rsk1.getEstimate(), k);
rsk1 = inter.getResult(ordered, null);
assertEquals(rsk1.getEstimate(), k);
final int bytes = rsk1.getCompactBytes();
final byte[] byteArray = new byte[bytes];
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
rsk1 = inter.getResult(!ordered, mem); //executed twice to fully exercise the internal state machine
assertEquals(rsk1.getEstimate(), k);
rsk1 = inter.getResult(ordered, mem);
assertEquals(rsk1.getEstimate(), k);
}
@Test
public void checkIntersectionEarlyStop() {
final int lgK = 10;
final int k = 1<<lgK;
final int u = 4*k;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u; i++) {
usk1.update(i);
}
for (int i=u/2; i<u + u/2; i++) {
usk2.update(i);
}
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
final CompactSketch csk1 = usk1.compact(true, null);
final CompactSketch csk2 = usk2.compact(true, null);
final Intersection inter =
SetOperation.builder().buildIntersection(iMem);
inter.intersect(csk1);
inter.intersect(csk2);
final CompactSketch rsk1 = inter.getResult(true, null);
println(""+rsk1.getEstimate());
}
//Calling getResult on a virgin Intersect is illegal
@Test(expectedExceptions = SketchesStateException.class)
public void checkNoCall() {
final int lgK = 9;
final int k = 1<<lgK;
Intersection inter;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
inter = SetOperation.builder().buildIntersection(iMem);
assertFalse(inter.hasResult());
inter.getResult(false, null);
}
@Test
public void checkIntersectionNull() {
final int lgK = 9;
final int k = 1<<lgK;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
final Intersection inter = SetOperation.builder().buildIntersection(iMem);
final UpdateSketch sk = null;
try { inter.intersect(sk); fail(); }
catch (final SketchesArgumentException e) { }
try { inter.intersect(sk, sk); fail(); }
catch (final SketchesArgumentException e) { }
}
@Test
public void check1stCall() {
final int lgK = 9;
final int k = 1<<lgK;
Intersection inter;
UpdateSketch sk;
CompactSketch rsk1;
double est;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
//1st call = empty
sk = UpdateSketch.builder().setNominalEntries(k).build(); //empty
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(sk);
rsk1 = inter.getResult(false, null);
est = rsk1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est); // = 0
//1st call = valid and not empty
sk = UpdateSketch.builder().setNominalEntries(k).build();
sk.update(1);
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(sk);
rsk1 = inter.getResult(false, null);
est = rsk1.getEstimate();
assertEquals(est, 1.0, 0.0);
println("Est: "+est); // = 1
}
@Test
public void check2ndCallAfterEmpty() {
final int lgK = 9;
final int k = 1<<lgK;
Intersection inter;
UpdateSketch sk1, sk2;
CompactSketch comp1;
double est;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
//1st call = empty
sk1 = UpdateSketch.builder().build(); //empty
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(sk1);
//2nd call = empty
sk2 = UpdateSketch.builder().build(); //empty
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = empty
sk1 = UpdateSketch.builder().build(); //empty
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(sk1);
//2nd call = valid and not empty
sk2 = UpdateSketch.builder().build();
sk2.update(1);
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
}
@Test
public void check2ndCallAfterValid() {
final int lgK = 9;
final int k = 1<<lgK;
Intersection inter;
UpdateSketch sk1, sk2;
CompactSketch comp1;
double est;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
//1st call = valid
sk1 = UpdateSketch.builder().build();
sk1.update(1);
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(sk1);
//2nd call = empty
sk2 = UpdateSketch.builder().build(); //empty
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = valid
sk1 = UpdateSketch.builder().build();
sk1.update(1);
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(sk1);
//2nd call = valid intersecting
sk2 = UpdateSketch.builder().build(); //empty
sk2.update(1);
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 1.0, 0.0);
println("Est: "+est);
//1st call = valid
sk1 = UpdateSketch.builder().build();
sk1.update(1);
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(sk1);
//2nd call = valid not intersecting
sk2 = UpdateSketch.builder().build(); //empty
sk2.update(2);
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
}
@Test
public void checkEstimatingIntersect() {
final int lgK = 9;
final int k = 1<<lgK;
Intersection inter;
UpdateSketch sk1, sk2;
CompactSketch comp1;
double est;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
//1st call = valid
sk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<2*k; i++)
{
sk1.update(i); //est mode
}
println("sk1: "+sk1.getEstimate());
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(sk1);
//2nd call = valid intersecting
sk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<2*k; i++)
{
sk2.update(i); //est mode
}
println("sk2: "+sk2.getEstimate());
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertTrue(est > k);
println("Est: "+est);
}
@SuppressWarnings("unused")
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkOverflow() {
final int lgK = 9; //512
final int k = 1<<lgK;
Intersection inter;
UpdateSketch sk1;
final UpdateSketch sk2;
final CompactSketch comp1;
final double est;
final int reqBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[reqBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
//1st call = valid
sk1 = UpdateSketch.builder().setNominalEntries(2 * k).build(); // bigger sketch
for (int i=0; i<4*k; i++)
{
sk1.update(i); //force est mode
}
println("sk1est: "+sk1.getEstimate());
println("sk1cnt: "+sk1.getRetainedEntries(true));
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(sk1);
}
@Test
public void checkHeapify() {
final int lgK = 9;
final int k = 1<<lgK;
Intersection inter;
UpdateSketch sk1, sk2;
CompactSketch comp1, comp2;
double est, est2;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
//1st call = valid
sk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<2*k; i++)
{
sk1.update(i); //est mode
}
println("sk1: "+sk1.getEstimate());
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(sk1);
//2nd call = valid intersecting
sk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<2*k; i++)
{
sk2.update(i); //est mode
}
println("sk2: "+sk2.getEstimate());
inter.intersect(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertTrue(est > k);
println("Est: "+est);
final byte[] byteArray = inter.toByteArray();
final Memory mem = Memory.wrap(byteArray);
final Intersection inter2 = (Intersection) SetOperation.heapify(mem);
comp2 = inter2.getResult(false, null);
est2 = comp2.getEstimate();
println("Est2: "+est2);
}
/**
* This proves that the hash of 7 is < 0.5. This fact will be used in other tests involving P.
*/
@Test
public void checkPreject() {
final UpdateSketch sk = UpdateSketch.builder().setP((float) .5).build();
sk.update(7);
assertEquals(sk.getRetainedEntries(), 0);
}
@Test
public void checkWrapVirginEmpty() {
final int lgK = 5;
final int k = 1 << lgK;
Intersection inter1, inter2;
UpdateSketch sk1;
final int memBytes = getMaxIntersectionBytes(k);
WritableMemory iMem = WritableMemory.writableWrap(new byte[memBytes]);
inter1 = SetOperation.builder().buildIntersection(iMem); //virgin off-heap
inter2 = Sketches.wrapIntersection(iMem); //virgin off-heap, identical to inter1
//both in virgin state, empty = false
//note: both inter1 and inter2 are tied to the same memory,
// so an intersect to one also affects the other. Don't do what I do!
assertFalse(inter1.hasResult());
assertFalse(inter2.hasResult());
//This constructs a sketch with 0 entries and theta < 1.0
sk1 = UpdateSketch.builder().setP((float) .5).setNominalEntries(k).build();
sk1.update(7); //will be rejected by P, see proof above.
//A virgin intersection (empty = false) intersected with a not-empty zero cache sketch
//remains empty = false!
inter1.intersect(sk1);
assertFalse(inter1.isEmpty());
assertTrue(inter1.hasResult());
//note that inter2 is not independent
assertFalse(inter2.isEmpty());
assertTrue(inter2.hasResult());
//test the path via toByteArray, wrap, now in a different state
iMem = WritableMemory.writableWrap(inter1.toByteArray());
inter2 = Sketches.wrapIntersection((Memory)iMem);
assertTrue(inter2.hasResult()); //still true
//test the compaction path
final CompactSketch comp = inter2.getResult(true, null);
assertEquals(comp.getRetainedEntries(false), 0);
assertFalse(comp.isEmpty());
}
@Test
public void checkWrapNullEmpty2() {
final int lgK = 5;
final int k = 1<<lgK;
Intersection inter1, inter2;
UpdateSketch sk1;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
inter1 = SetOperation.builder().buildIntersection(iMem); //virgin
inter2 = Sketches.wrapIntersection(iMem);
//both in virgin state, empty = false
assertFalse(inter1.hasResult());
assertFalse(inter2.hasResult());
sk1 = UpdateSketch.builder().setP((float) .005).setFamily(Family.QUICKSELECT).setNominalEntries(k).build();
sk1.update(1); //very unlikely to go into cache due to p.
//A virgin intersection (empty = false) intersected with a not-empty zero cache sketch
//remains empty = false.
inter1.intersect(sk1);
inter2 = Sketches.wrapIntersection(iMem);
assertTrue(inter1.hasResult());
assertTrue(inter2.hasResult());
final CompactSketch comp = inter2.getResult(true, null);
assertEquals(comp.getRetainedEntries(false), 0);
assertFalse(comp.isEmpty());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkSizeLowerLimit() {
final int k = 8;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
SetOperation.builder().buildIntersection(iMem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkSizedTooSmall() {
final int lgK = 5;
final int k = 1<<lgK;
final int u = 4*k;
final int memBytes = getMaxIntersectionBytes(k/2);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<u; i++) {
usk1.update(i);
}
final CompactSketch csk1 = usk1.compact(true, null);
final Intersection inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(csk1);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadPreambleLongs() {
final int k = 32;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
final Intersection inter1 = SetOperation.builder().buildIntersection(iMem); //virgin
final byte[] byteArray = inter1.toByteArray();
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
//corrupt:
mem.putByte(PREAMBLE_LONGS_BYTE, (byte) 2);//RF not used = 0
Sketches.wrapIntersection(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
final int k = 32;
Intersection inter1;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
inter1 = SetOperation.builder().buildIntersection(iMem); //virgin
final byte[] byteArray = inter1.toByteArray();
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
//corrupt:
mem.putByte(SER_VER_BYTE, (byte) 2);
Sketches.wrapIntersection(mem); //throws in SetOperations
}
@Test(expectedExceptions = ClassCastException.class)
public void checkFamilyID() {
final int k = 32;
Union union;
union = SetOperation.builder().setNominalEntries(k).buildUnion();
final byte[] byteArray = union.toByteArray();
final WritableMemory mem = WritableMemory.writableWrap(byteArray);
Sketches.wrapIntersection(mem);
}
@Test
public void checkWrap() {
final int lgK = 9;
final int k = 1<<lgK;
Intersection inter, inter2, inter3;
UpdateSketch sk1, sk2;
CompactSketch resultComp1, resultComp2;
double est, est2;
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr1 = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr1);
//1st call = valid
sk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<2*k; i++)
{
sk1.update(i); //est mode
}
final CompactSketch compSkIn1 = sk1.compact(true, null);
println("compSkIn1: "+compSkIn1.getEstimate());
inter = SetOperation.builder().buildIntersection(iMem);
inter.intersect(compSkIn1);
final byte[] memArr2 = inter.toByteArray();
final WritableMemory srcMem = WritableMemory.writableWrap(memArr2);
inter2 = Sketches.wrapIntersection(srcMem);
//2nd call = valid intersecting
sk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<2*k; i++)
{
sk2.update(i); //est mode
}
final CompactSketch compSkIn2 = sk2.compact(true, null);
println("sk2: "+compSkIn2.getEstimate());
inter2.intersect(compSkIn2);
resultComp1 = inter2.getResult(false, null);
est = resultComp1.getEstimate();
assertTrue(est > k);
println("Est: "+est);
final byte[] memArr3 = inter2.toByteArray();
final WritableMemory srcMem2 = WritableMemory.writableWrap(memArr3);
inter3 = Sketches.wrapIntersection(srcMem2);
resultComp2 = inter3.getResult(false, null);
est2 = resultComp2.getEstimate();
println("Est2: "+est2);
inter.reset();
inter2.reset();
inter3.reset();
}
@Test
public void checkDefaultMinSize() {
final int k = 32;
final WritableMemory mem = WritableMemory.writableWrap(new byte[k*8 + PREBYTES]);
IntersectionImpl.initNewDirectInstance(ThetaUtil.DEFAULT_UPDATE_SEED, mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkExceptionMinSize() {
final int k = 16;
final WritableMemory mem = WritableMemory.writableWrap(new byte[k*8 + PREBYTES]);
IntersectionImpl.initNewDirectInstance(ThetaUtil.DEFAULT_UPDATE_SEED, mem);
}
@Test
public void checkGetResult() {
final int k = 1024;
final UpdateSketch sk = Sketches.updateSketchBuilder().build();
final int memBytes = getMaxIntersectionBytes(k);
final byte[] memArr = new byte[memBytes];
final WritableMemory iMem = WritableMemory.writableWrap(memArr);
final Intersection inter = Sketches.setOperationBuilder().buildIntersection(iMem);
inter.intersect(sk);
final CompactSketch csk = inter.getResult();
assertEquals(csk.getCompactBytes(), 8);
}
@Test
public void checkFamily() {
//cheap trick
final int k = 16;
final WritableMemory mem = WritableMemory.writableWrap(new byte[k*16 + PREBYTES]);
final IntersectionImpl impl = IntersectionImpl.initNewDirectInstance(ThetaUtil.DEFAULT_UPDATE_SEED, mem);
assertEquals(impl.getFamily(), Family.INTERSECTION);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkExceptions1() {
final int k = 16;
final WritableMemory mem = WritableMemory.writableWrap(new byte[k*16 + PREBYTES]);
IntersectionImpl.initNewDirectInstance(ThetaUtil.DEFAULT_UPDATE_SEED, mem);
//corrupt SerVer
mem.putByte(PreambleUtil.SER_VER_BYTE, (byte) 2);
IntersectionImpl.wrapInstance(mem, ThetaUtil.DEFAULT_UPDATE_SEED, false);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkExceptions2() {
final int k = 16;
final WritableMemory mem = WritableMemory.writableWrap(new byte[k*16 + PREBYTES]);
IntersectionImpl.initNewDirectInstance(ThetaUtil.DEFAULT_UPDATE_SEED, mem);
//mem now has non-empty intersection
//corrupt empty and CurCount
mem.setBits(PreambleUtil.FLAGS_BYTE, (byte) PreambleUtil.EMPTY_FLAG_MASK);
mem.putInt(PreambleUtil.RETAINED_ENTRIES_INT, 2);
IntersectionImpl.wrapInstance(mem, ThetaUtil.DEFAULT_UPDATE_SEED, false);
}
//Check Alex's bug intersecting 2 direct full sketches with only overlap of 2
//
@Test
public void checkOverlappedDirect() {
final int k = 1 << 4;
final int memBytes = 2*k*16 +PREBYTES; //plenty of room
final UpdateSketch sk1 = Sketches.updateSketchBuilder().setNominalEntries(k).build();
final UpdateSketch sk2 = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
sk1.update(i);
sk2.update(k-2 +i); //overlap by 2
}
final WritableMemory memIn1 = WritableMemory.writableWrap(new byte[memBytes]);
final WritableMemory memIn2 = WritableMemory.writableWrap(new byte[memBytes]);
final WritableMemory memInter = WritableMemory.writableWrap(new byte[memBytes]);
final WritableMemory memComp = WritableMemory.writableWrap(new byte[memBytes]);
final CompactSketch csk1 = sk1.compact(true, memIn1);
final CompactSketch csk2 = sk2.compact(true, memIn2);
final Intersection inter = Sketches.setOperationBuilder().buildIntersection(memInter);
inter.intersect(csk1);
inter.intersect(csk2);
final CompactSketch cskOut = inter.getResult(true, memComp);
assertEquals(cskOut.getEstimate(), 2.0, 0.0);
final Intersection interRO = (Intersection) SetOperation.wrap((Memory)memInter);
try {
interRO.intersect(sk1, sk2);
fail();
} catch (final SketchesReadOnlyException e) { }
try {
interRO.reset();
fail();
} catch (final SketchesReadOnlyException e) { }
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,472 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/IteratorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.memory.WritableMemory;
/**
* @author Lee Rhodes
*/
public class IteratorTest {
@Test
public void checkDirectCompactSketch() {
int k = 16;
int maxBytes = Sketch.getMaxUpdateSketchBytes(k);
WritableMemory wmem = WritableMemory.allocate(maxBytes);
UpdateSketch sk1 = Sketches.updateSketchBuilder().setNominalEntries(k).build(wmem);
println(sk1.getClass().getSimpleName());
for (int i = 0; i < (k/2); i++) { sk1.update(i); }
HashIterator itr1 = sk1.iterator();
int count = 0;
while (itr1.next()) {
println(++count + "\t" + Long.toHexString(itr1.get()));
}
assertEquals(count, k/2);
println("");
Sketch sk2 = sk1.compact();
println(sk2.getClass().getSimpleName());
HashIterator itr2 = sk2.iterator();
count = 0;
while (itr2.next()) {
println(++count + "\t" + Long.toHexString(itr2.get()));
}
assertEquals(count, k/2);
println("");
Sketch sk3 = sk1.compact(false, WritableMemory.allocate(maxBytes));
println(sk3.getClass().getSimpleName());
HashIterator itr3 = sk3.iterator();
count = 0;
while (itr3.next()) {
println(++count + "\t" + Long.toHexString(itr3.get()));
}
assertEquals(count, k/2);
}
@Test
public void checkHeapAlphaSketch() {
int k = 512;
int u = 8;
UpdateSketch sk1 = Sketches.updateSketchBuilder().setNominalEntries(k).setFamily(Family.ALPHA)
.build();
println(sk1.getClass().getSimpleName());
for (int i = 0; i < u; i++) { sk1.update(i); }
HashIterator itr1 = sk1.iterator();
int count = 0;
while (itr1.next()) {
println(++count + "\t" + Long.toHexString(itr1.get()));
}
assertEquals(count, u);
}
@Test
public void checkHeapQSSketch() {
int k = 16;
int u = 8;
UpdateSketch sk1 = Sketches.updateSketchBuilder().setNominalEntries(k)
.build();
println(sk1.getClass().getSimpleName());
for (int i = 0; i < u; i++) { sk1.update(i); }
HashIterator itr1 = sk1.iterator();
int count = 0;
while (itr1.next()) {
println(++count + "\t" + Long.toHexString(itr1.get()));
}
assertEquals(count, u);
}
@Test
public void checkSingleItemSketch() {
int k = 16;
int u = 1;
UpdateSketch sk1 = Sketches.updateSketchBuilder().setNominalEntries(k)
.build();
for (int i = 0; i < u; i++) { sk1.update(i); }
CompactSketch csk = sk1.compact();
println(csk.getClass().getSimpleName());
HashIterator itr1 = csk.iterator();
int count = 0;
while (itr1.next()) {
println(++count + "\t" + Long.toHexString(itr1.get()));
}
assertEquals(count, u);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,473 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/EmptyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.theta.PreambleUtil.COMPACT_FLAG_MASK;
import static org.apache.datasketches.theta.PreambleUtil.ORDERED_FLAG_MASK;
import static org.apache.datasketches.theta.PreambleUtil.READ_ONLY_FLAG_MASK;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
/**
* Empty essentially means that the sketch has never seen data.
*
* @author Lee Rhodes
*/
public class EmptyTest {
@Test
public void checkEmpty() {
final UpdateSketch sk1 = Sketches.updateSketchBuilder().build();
final UpdateSketch sk2 = Sketches.updateSketchBuilder().build();
final Intersection inter = Sketches.setOperationBuilder().buildIntersection();
final int u = 100;
for (int i = 0; i < u; i++) { //disjoint
sk1.update(i);
sk2.update(i + u);
}
inter.intersect(sk1);
inter.intersect(sk2);
final CompactSketch csk = inter.getResult();
//The intersection of two disjoint, exact-mode sketches is empty, T == 1.0.
println(csk.toString());
assertTrue(csk.isEmpty());
final AnotB aNotB = Sketches.setOperationBuilder().buildANotB();
final CompactSketch csk2 = aNotB.aNotB(csk, sk1);
//The AnotB of an empty, T == 1.0 sketch with another exact-mode sketch is empty, T == 1.0
assertTrue(csk2.isEmpty());
}
@Test
public void checkNotEmpty() {
final UpdateSketch sk1 = Sketches.updateSketchBuilder().build();
final UpdateSketch sk2 = Sketches.updateSketchBuilder().build();
final Intersection inter = Sketches.setOperationBuilder().buildIntersection();
final int u = 10000; //estimating
for (int i = 0; i < u; i++) { //disjoint
sk1.update(i);
sk2.update(i + u);
}
inter.intersect(sk1);
inter.intersect(sk2);
final CompactSketch csk = inter.getResult();
println(csk.toString());
//The intersection of two disjoint, est-mode sketches is not-empty, T < 1.0.
assertFalse(csk.isEmpty());
AnotB aNotB = Sketches.setOperationBuilder().buildANotB();
final CompactSketch csk2 = aNotB.aNotB(csk, sk1); //empty, T < 1.0; with est-mode sketch
println(csk2.toString());
//The AnotB of an empty, T < 1.0 sketch with another exact-mode sketch is not-empty.
assertFalse(csk2.isEmpty());
final UpdateSketch sk3 = Sketches.updateSketchBuilder().build();
aNotB = Sketches.setOperationBuilder().buildANotB();
final CompactSketch csk3 = aNotB.aNotB(sk3, sk1); //empty, T == 1.0; with est-mode sketch
println(csk3.toString());
//the AnotB of an empty, T == 1.0 sketch with another est-mode sketch is empty, T < 1.0
assertTrue(csk3.isEmpty());
}
@Test
public void checkPsampling() {
final UpdateSketch sk1 = Sketches.updateSketchBuilder().setP(.5F).build();
assertTrue(sk1.isEmpty());
//An empty P-sampling sketch where T < 1.0 and has never seen data is also empty
// and will have a full preamble of 24 bytes. But when compacted, theta returns to 1.0, so
// it will be stored as only 8 bytes.
assertEquals(sk1.compact().toByteArray().length, 8);
}
//These 3 tests reproduce a failure mode where an "old" empty sketch of 8 bytes without
// its empty-flag bit set is read.
@Test
public void checkBackwardCompatibility1() {
final int k = 16;
final int bytes = Sketches.getMaxUnionBytes(k); //288
final Union union = SetOperation.builder().buildUnion(WritableMemory.allocate(bytes));
final Memory mem = badEmptySk();
final Sketch wsk = Sketches.wrapSketch(mem);
union.union(wsk); //union has memory
}
@Test
public void checkBackwardCompatibility2() {
final Union union = SetOperation.builder().setNominalEntries(16).buildUnion();
final Memory mem = badEmptySk();
final Sketch wsk = Sketches.wrapSketch(mem);
union.union(wsk); //heap union
}
@Test
public void checkBackwardCompatibility3() {
final Memory mem = badEmptySk();
Sketches.heapifySketch(mem);
}
@Test
public void checkEmptyToCompact() {
final UpdateSketch sk1 = Sketches.updateSketchBuilder().build();
final CompactSketch csk = sk1.compact();
assertTrue(csk instanceof EmptyCompactSketch);
final CompactSketch csk2 = csk.compact();
assertTrue(csk2 instanceof EmptyCompactSketch);
final CompactSketch csk3 = csk.compact(true, WritableMemory.allocate(8));
assertTrue(csk3 instanceof DirectCompactSketch);
assertEquals(csk2.getCurrentPreambleLongs(), 1);
}
//SerVer 2 had an empty sketch where preLongs = 1, but empty bit was not set.
private static Memory badEmptySk() {
final long preLongs = 1;
final long serVer = 2;
final long family = 3; //compact
final long flags = ORDERED_FLAG_MASK | COMPACT_FLAG_MASK | READ_ONLY_FLAG_MASK;
final long seedHash = 0x93CC;
final long badEmptySk = seedHash << 48 | flags << 40
| family << 16 | serVer << 8 | preLongs;
final WritableMemory wmem = WritableMemory.allocate(8);
wmem.putLong(0, badEmptySk);
return wmem;
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,474 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/SetOperationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.common.ResizeFactor.X4;
import static org.apache.datasketches.theta.Sketch.getMaxUpdateSketchBytes;
import static org.apache.datasketches.thetacommon.HashOperations.minLgHashTableSize;
import static org.testng.Assert.assertEquals;
//import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.MemoryRequestServer;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class SetOperationTest {
@Test
public void checkBuilder() {
final int k = 2048;
final long seed = 1021;
final UpdateSketch usk1 = UpdateSketch.builder().setSeed(seed).setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setSeed(seed).setNominalEntries(k).build();
for (int i=0; i<k/2; i++) {
usk1.update(i); //256
}
for (int i=k/2; i<k; i++) {
usk2.update(i); //256 no overlap
}
final ResizeFactor rf = X4;
//use default size
final Union union = SetOperation.builder().setSeed(seed).setResizeFactor(rf).buildUnion();
union.union(usk1);
union.union(usk2);
final double exactUnionAnswer = k;
final CompactSketch comp1 = union.getResult(false, null); //ordered: false
final double compEst = comp1.getEstimate();
assertEquals(compEst, exactUnionAnswer, 0.0);
}
@Test
public void checkBuilder2() {
final SetOperationBuilder bldr = SetOperation.builder();
final long seed = 12345L;
bldr.setSeed(seed);
assertEquals(bldr.getSeed(), seed);
final float p = (float)0.5;
bldr.setP(p);
assertEquals(bldr.getP(), p);
final ResizeFactor rf = ResizeFactor.X4;
bldr.setResizeFactor(rf);
assertEquals(bldr.getResizeFactor(), rf);
final int lgK = 10;
final int k = 1 << lgK;
bldr.setNominalEntries(k);
assertEquals(bldr.getLgNominalEntries(), lgK);
final MemoryRequestServer mrs = new DefaultMemoryRequestServer();
bldr.setMemoryRequestServer(mrs);
assertEquals(bldr.getMemoryRequestServer(), mrs);
println(bldr.toString());
}
@Test
public void checkBuilderNonPowerOf2() {
SetOperation.builder().setNominalEntries(1000).buildUnion();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBuilderBadFamily() {
SetOperation.builder().build(Family.ALPHA);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBuilderIllegalPhi() {
final float p = (float)1.5;
SetOperation.builder().setP(p).buildUnion();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBuilderIllegalPlo() {
final float p = 0;
SetOperation.builder().setP(p).buildUnion();
}
@Test
public void checkBuilderValidP() {
final float p = (float).5;
SetOperation.builder().setP(p).buildUnion();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBuilderAnotB_noMem() {
final WritableMemory mem = WritableMemory.writableWrap(new byte[64]);
SetOperation.builder().build(Family.A_NOT_B, mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBuilderBadSeedHashes() {
final int k = 2048;
final long seed = 1021;
final UpdateSketch usk1 = UpdateSketch.builder().setSeed(seed).setNominalEntries(k).build();
final UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k/2; i++) {
usk1.update(i); //256
}
for (int i=k/2; i<k; i++) {
usk2.update(i); //256 no overlap
}
final ResizeFactor rf = X4;
final Union union = SetOperation.builder().setSeed(seed).setResizeFactor(rf).setNominalEntries(k).buildUnion();
union.union(usk1);
union.union(usk2); //throws seed exception here
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBuilderNomEntries() {
final int k = 1 << 27;
final SetOperationBuilder bldr = SetOperation.builder();
bldr.setNominalEntries(k);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkIllegalSetOpHeapify() {
final int k = 64;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
usk1.update(i); //64
}
final byte[] byteArray = usk1.toByteArray();
final Memory mem = Memory.wrap(byteArray);
SetOperation.heapify(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkIllegalSetOpWrap() {
final int k = 64;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
usk1.update(i); //64
}
final byte[] byteArray = usk1.toByteArray();
final Memory mem = Memory.wrap(byteArray);
Sketches.wrapIntersection(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkIllegalSetOpWrap2() {
final int k = 64;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
usk1.update(i); //64
}
final WritableMemory wmem = WritableMemory.writableWrap(usk1.toByteArray());
PreambleUtil.insertSerVer(wmem, 2); //corrupt
final Memory mem = wmem;
SetOperation.wrap(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkIllegalSetOpWrap3() {
final int k = 64;
final UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build();
for (int i=0; i<k; i++) {
usk1.update(i); //64
}
final WritableMemory wmem = WritableMemory.writableWrap(usk1.toByteArray());
SetOperation.wrap(wmem);
}
@Test
public void checkBuildSetOps() {
final SetOperationBuilder bldr = Sketches.setOperationBuilder();
bldr.buildUnion();
bldr.buildIntersection();
bldr.buildANotB();
}
@Test
public void checkComputeLgArrLongs() {
assertEquals(minLgHashTableSize(30, ThetaUtil.REBUILD_THRESHOLD), 5);
assertEquals(minLgHashTableSize(31, ThetaUtil.REBUILD_THRESHOLD), 6);
}
/**
* The objective is to union 3 16K sketches into a union SetOperation and get the result.
* All operations are to be performed within a single direct ByteBuffer as the backing store.
* First we will make the union size large enough so that its answer will be exact (with this
* specific example).
* <p> Next, we recover the Union SetOp and the 3 sketches and the space for the result. Then
* recompute the union using a Union of the same size as the input sketches, where the end result
* will be an estimate.
*/
@Test
public void checkDirectUnionExample() {
//The first task is to compute how much direct memory we need and set the heap large enough.
//For the first trial, we will set the Union large enough for an exact result for THIS example.
final int sketchNomEntries = 1 << 14; //16K
int unionNomEntries = 1 << 15; //32K
final int[] heapLayout = getHeapLayout(sketchNomEntries, unionNomEntries);
//This BB belongs to you and you always retain a link to it until you are completely
// done and then let java garbage collect it.
//I use a heap backing array, because for this example it is easier to peak into it and
// see what is going on.
final byte[] backingArr = new byte[heapLayout[5]];
final ByteBuffer heapBuf = ByteBuffer.wrap(backingArr).order(ByteOrder.nativeOrder());
// Attaches a WritableMemory object to the underlying memory of heapBuf.
// heapMem will have a Read/Write view of the complete backing memory of heapBuf (direct or not).
// Any R/W action from heapMem will be visible via heapBuf and visa versa.
//
// However, if you had created this WM object directly in raw, off-heap "native" memory
// you would have the responsibility to close it when you are done.
// But, since it was allocated via BB, it closes it for you.
final WritableMemory heapMem = WritableMemory.writableWrap(heapBuf);
double result = directUnionTrial1(heapMem, heapLayout, sketchNomEntries, unionNomEntries);
println("1st est: "+result);
final int expected = sketchNomEntries*2;
assertEquals(result, expected, 0.0); //est must be exact.
//For trial 2, we will use the same union space but use only part of it.
unionNomEntries = 1 << 14; //16K
result = directUnionTrial2(heapMem, heapLayout, sketchNomEntries, unionNomEntries);
//intentionally loose bounds
assertEquals(result, expected, expected*0.05);
println("2nd est: "+result);
println("Error %: "+(result/expected -1.0)*100);
}
@Test
public void setOpsExample() {
println("Set Operations Example:");
final int k = 4096;
final UpdateSketch skA = Sketches.updateSketchBuilder().setNominalEntries(k).build();
final UpdateSketch skB = Sketches.updateSketchBuilder().setNominalEntries(k).build();
final UpdateSketch skC = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i=1; i<=10; i++) { skA.update(i); }
for (int i=1; i<=20; i++) { skB.update(i); }
for (int i=6; i<=15; i++) { skC.update(i); } //overlapping set
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
union.union(skA);
union.union(skB);
// ... continue to iterate on the input sketches to union
final CompactSketch unionSk = union.getResult(); //the result union sketch
println("A U B : "+unionSk.getEstimate()); //the estimate of the union
//Intersection is similar
final Intersection inter = Sketches.setOperationBuilder().buildIntersection();
inter.intersect(unionSk);
inter.intersect(skC);
// ... continue to iterate on the input sketches to intersect
final CompactSketch interSk = inter.getResult(); //the result intersection sketch
println("(A U B) ^ C: "+interSk.getEstimate()); //the estimate of the intersection
//The AnotB operation is a little different as it is stateless:
final AnotB aNotB = Sketches.setOperationBuilder().buildANotB();
final CompactSketch not = aNotB.aNotB(skA, skC);
println("A \\ C : "+not.getEstimate()); //the estimate of the AnotB operation
}
@Test
public void checkIsSameResource() {
final int k = 16;
final WritableMemory wmem = WritableMemory.writableWrap(new byte[k*16 + 32]);
final Memory roCompactMem = Memory.wrap(new byte[8]);
final Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion(wmem);
assertTrue(union.isSameResource(wmem));
assertFalse(union.isSameResource(roCompactMem));
final Intersection inter = Sketches.setOperationBuilder().buildIntersection(wmem);
assertTrue(inter.isSameResource(wmem));
assertFalse(inter.isSameResource(roCompactMem));
final AnotB aNotB = Sketches.setOperationBuilder().buildANotB();
assertFalse(aNotB.isSameResource(roCompactMem));
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
/**
* Compute offsets for MyHeap for Union, sketch1, sketch2, sketch3, resultSketch, total layout.
* @param sketchNomEntries the configured nominal entries of the sketch
* @param unionNomEntries configured nominal entries of the union
* @return array of offsets for Union, sketch1, sketch2, sketch3, resultSketch, total layout
*/
private static int[] getHeapLayout(final int sketchNomEntries, final int unionNomEntries) {
final int[] heapLayout = new int[6];
final int unionBytes = SetOperation.getMaxUnionBytes(unionNomEntries);
final int sketchBytes = getMaxUpdateSketchBytes(sketchNomEntries);
final int resultBytes = Sketch.getMaxCompactSketchBytes(unionNomEntries);
heapLayout[0] = 0; //offset for Union
heapLayout[1] = unionBytes; //offset for sketch1
heapLayout[2] = unionBytes + sketchBytes; //offset for sketch2
heapLayout[3] = unionBytes + 2*sketchBytes; //offset for sketch3
heapLayout[4] = unionBytes + 3*sketchBytes; //offset for result
heapLayout[5] = unionBytes + 3*sketchBytes + resultBytes; //total
return heapLayout;
}
private static double directUnionTrial1(
final WritableMemory heapMem, final int[] heapLayout, final int sketchNomEntries, final int unionNomEntries) {
final int offset = heapLayout[0];
final int bytes = heapLayout[1] - offset;
final WritableMemory unionMem = heapMem.writableRegion(offset, bytes);
Union union = SetOperation.builder().setNominalEntries(unionNomEntries).buildUnion(unionMem);
final WritableMemory sketch1mem = heapMem.writableRegion(heapLayout[1], heapLayout[2]-heapLayout[1]);
final WritableMemory sketch2mem = heapMem.writableRegion(heapLayout[2], heapLayout[3]-heapLayout[2]);
final WritableMemory sketch3mem = heapMem.writableRegion(heapLayout[3], heapLayout[4]-heapLayout[3]);
final WritableMemory resultMem = heapMem.writableRegion(heapLayout[4], heapLayout[5]-heapLayout[4]);
//Initialize the 3 sketches
final UpdateSketch sk1 = UpdateSketch.builder().setNominalEntries(sketchNomEntries).build(sketch1mem);
final UpdateSketch sk2 = UpdateSketch.builder().setNominalEntries(sketchNomEntries).build(sketch2mem);
final UpdateSketch sk3 = UpdateSketch.builder().setNominalEntries(sketchNomEntries).build(sketch3mem);
//This little trial has sk1 and sk2 distinct and sk2 overlap both.
//Build the sketches.
for (int i=0; i< sketchNomEntries; i++) {
sk1.update(i);
sk2.update(i + sketchNomEntries/2);
sk3.update(i + sketchNomEntries);
}
//confirm that each of these 3 sketches is exact.
assertEquals(sk1.getEstimate(), sketchNomEntries, 0.0);
assertEquals(sk2.getEstimate(), sketchNomEntries, 0.0);
assertEquals(sk3.getEstimate(), sketchNomEntries, 0.0);
//Let's union the first 2 sketches
union.union(sk1);
union.union(sk2);
//Let's recover the union and the 3rd sketch
union = Sketches.wrapUnion(unionMem);
union.union(Sketch.wrap(sketch3mem));
final Sketch resSk = union.getResult(true, resultMem);
final double est = resSk.getEstimate();
return est;
}
private static double directUnionTrial2(
final WritableMemory heapMem, final int[] heapLayout, final int sketchNomEntries, final int unionNomEntries) {
final WritableMemory unionMem = heapMem.writableRegion(heapLayout[0], heapLayout[1]-heapLayout[0]);
final WritableMemory sketch1mem = heapMem.writableRegion(heapLayout[1], heapLayout[2]-heapLayout[1]);
final WritableMemory sketch2mem = heapMem.writableRegion(heapLayout[2], heapLayout[3]-heapLayout[2]);
final WritableMemory sketch3mem = heapMem.writableRegion(heapLayout[3], heapLayout[4]-heapLayout[3]);
final WritableMemory resultMem = heapMem.writableRegion(heapLayout[4], heapLayout[5]-heapLayout[4]);
//Recover the 3 sketches
final UpdateSketch sk1 = (UpdateSketch) Sketch.wrap(sketch1mem);
final UpdateSketch sk2 = (UpdateSketch) Sketch.wrap(sketch2mem);
final UpdateSketch sk3 = (UpdateSketch) Sketch.wrap(sketch3mem);
//confirm that each of these 3 sketches is exact.
assertEquals(sk1.getEstimate(), sketchNomEntries, 0.0);
assertEquals(sk2.getEstimate(), sketchNomEntries, 0.0);
assertEquals(sk3.getEstimate(), sketchNomEntries, 0.0);
//Create a new union in the same space with a smaller size.
unionMem.clear();
final Union union = SetOperation.builder().setNominalEntries(unionNomEntries).buildUnion(unionMem);
union.union(sk1);
union.union(sk2);
union.union(sk3);
final Sketch resSk = union.getResult(true, resultMem);
final double est = resSk.getEstimate();
return est;
}
}
| 2,475 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/theta/SetOpsCornerCasesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.theta;
import static org.apache.datasketches.theta.SetOpsCornerCasesTest.State.EMPTY;
import static org.apache.datasketches.theta.SetOpsCornerCasesTest.State.EST_HEAP;
import static org.apache.datasketches.theta.SetOpsCornerCasesTest.State.EST_MEMORY_UNORDERED;
import static org.apache.datasketches.theta.SetOpsCornerCasesTest.State.EXACT;
import static org.apache.datasketches.theta.SetOpsCornerCasesTest.State.NULL;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import java.util.Random;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SetOpsCornerCasesTest {
/*******************************************/
Random rand = new Random(9001); //deterministic
@Test
public void checkSetOpsRandom() {
int hiA = 0, loB = 0, hiB = 0;
for (int i = 0; i < 1000; i++) {
hiA = rand.nextInt(128); //skA fed values between 0 and 127
loB = rand.nextInt(64);
hiB = loB + rand.nextInt(64); //skB fed up to 63 values starting at loB
compareSetOpsRandom(64, 0, hiA, loB, hiB);
}
}
private static void compareSetOpsRandom(int k, int loA, int hiA, int loB, int hiB) {
UpdateSketch tskA = Sketches.updateSketchBuilder().setNominalEntries(k).build();
UpdateSketch tskB = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i = loA; i < hiA; i++) { tskA.update(i); }
for (int i = loB; i < hiB; i++) { tskB.update(i); }
CompactSketch rcskStdU = doStdUnion(tskA, tskB, k, null);
CompactSketch rcskPwU = doPwUnion(tskA, tskB, k);
checkCornerCase(rcskPwU, rcskStdU);
CompactSketch rcskStdPairU = doStdPairUnion(tskA, tskB, k, null);
checkCornerCase(rcskStdPairU, rcskStdU);
CompactSketch rcskStdI = doStdIntersection(tskA, tskB, null);
CompactSketch rcskPwI = doPwIntersection(tskA, tskB);
checkCornerCase(rcskPwI, rcskStdI);
CompactSketch rcskStdPairI = doStdPairIntersection(tskA, tskB, null);
checkCornerCase(rcskStdPairI, rcskStdI);
CompactSketch rcskStdAnotB = doStdAnotB(tskA, tskB, null);
CompactSketch rcskPwAnotB = doPwAnotB(tskA, tskB);
checkCornerCase(rcskPwAnotB, rcskStdAnotB);
CompactSketch rcskStdStatefulAnotB = doStdStatefulAnotB(tskA, tskB, null);
checkCornerCase(rcskStdStatefulAnotB, rcskStdAnotB);
}
/*******************************************/
@Test
//Check all corner cases against standard Union, Intersection, and AnotB.
//The unordered case is not tested
public void compareCornerCases() {
int k = 64;
for (State stateA : State.values()) {
for (State stateB : State.values()) {
if ((stateA == EST_MEMORY_UNORDERED) || (stateB == EST_MEMORY_UNORDERED)) { continue; }
if ((stateA == NULL) || (stateB == NULL)) { continue; }
cornerCaseChecks(stateA, stateB, k);
cornerCaseChecksMemory(stateA, stateB, k);
}
}
}
// @Test
// public void checkExactNullSpecificCase() {
// cornerCaseChecksMemory(State.EXACT, State.NULL, 64);
// }
private static void cornerCaseChecksMemory(State stateA, State stateB, int k) {
println("StateA: " + stateA + ", StateB: " + stateB);
CompactSketch tcskA = generate(stateA, k);
CompactSketch tcskB = generate(stateB, k);
WritableMemory wmem = WritableMemory.allocate(SetOperation.getMaxUnionBytes(k));
CompactSketch rcskStdU = doStdUnion(tcskA, tcskB, k, null);
CompactSketch rcskPwU = doPwUnion(tcskA, tcskB, k);
checkCornerCase(rcskPwU, rcskStdU); //heap, heap
rcskStdU = doStdUnion(tcskA, tcskB, k, wmem);
CompactSketch rcskStdPairU = doStdPairUnion(tcskA, tcskB, k, wmem);
checkCornerCase(rcskStdPairU, rcskStdU); //direct, direct
wmem = WritableMemory.allocate(SetOperation.getMaxIntersectionBytes(k));
CompactSketch rcskStdI = doStdIntersection(tcskA, tcskB, null);
CompactSketch rcskPwI = doPwIntersection(tcskA, tcskB);
checkCornerCase(rcskPwI, rcskStdI); //empty, empty
rcskStdI = doStdIntersection(tcskA, tcskB, wmem);
CompactSketch rcskStdPairI = doStdPairIntersection(tcskA, tcskB, wmem);
checkCornerCase(rcskStdPairI, rcskStdI); //empty, empty //direct, direct???
wmem = WritableMemory.allocate(SetOperation.getMaxAnotBResultBytes(k));
CompactSketch rcskStdAnotB = doStdAnotB(tcskA, tcskB, null);
CompactSketch rcskPwAnotB = doPwAnotB(tcskA, tcskB);
checkCornerCase(rcskPwAnotB, rcskStdAnotB); //heap, heap
rcskStdAnotB = doStdAnotB(tcskA, tcskB, wmem);
CompactSketch rcskStdStatefulAnotB = doStdStatefulAnotB(tcskA, tcskB, wmem);
checkCornerCase(rcskStdStatefulAnotB, rcskStdAnotB); //direct, heap
}
private static void cornerCaseChecks(State stateA, State stateB, int k) {
println("StateA: " + stateA + ", StateB: " + stateB);
CompactSketch tcskA = generate(stateA, k);
CompactSketch tcskB = generate(stateB, k);
CompactSketch rcskStdU = doStdUnion(tcskA, tcskB, k, null);
CompactSketch rcskPwU = doPwUnion(tcskA, tcskB, k);
checkCornerCase(rcskPwU, rcskStdU);
CompactSketch rcskStdPairU = doStdPairUnion(tcskA, tcskB, k, null);
checkCornerCase(rcskStdPairU, rcskStdU);
CompactSketch rcskStdI = doStdIntersection(tcskA, tcskB, null);
CompactSketch rcskPwI = doPwIntersection(tcskA, tcskB);
checkCornerCase(rcskPwI, rcskStdI);
CompactSketch rcskStdPairI = doStdPairIntersection(tcskA, tcskB, null);
checkCornerCase(rcskStdPairI, rcskStdI);
CompactSketch rcskStdAnotB = doStdAnotB(tcskA, tcskB, null);
CompactSketch rcskPwAnotB = doPwAnotB(tcskA, tcskB);
checkCornerCase(rcskPwAnotB, rcskStdAnotB);
CompactSketch rcskStdStatefulAnotB = doStdStatefulAnotB(tcskA, tcskB, null);
checkCornerCase(rcskStdStatefulAnotB, rcskStdAnotB);
}
private static CompactSketch doStdUnion(Sketch tskA, Sketch tskB, int k, WritableMemory wmem) {
Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
union.union(tskA);
union.union(tskB);
return union.getResult(true, wmem);
}
private static CompactSketch doStdPairUnion(Sketch tskA, Sketch tskB, int k, WritableMemory wmem) {
Union union = Sketches.setOperationBuilder().setNominalEntries(k).buildUnion();
return union.union(tskA, tskB, true, wmem);
}
private static CompactSketch doStdIntersection(Sketch tskA, Sketch tskB, WritableMemory wmem) {
Intersection inter = Sketches.setOperationBuilder().buildIntersection();
inter.intersect(tskA);
inter.intersect(tskB);
return inter.getResult(true, wmem);
}
private static CompactSketch doStdPairIntersection(Sketch tskA, Sketch tskB, WritableMemory wmem) {
Intersection inter = Sketches.setOperationBuilder().buildIntersection();
return inter.intersect(tskA, tskB, true, wmem);
}
private static CompactSketch doStdAnotB(Sketch tskA, Sketch tskB, WritableMemory wmem) {
AnotB anotb = Sketches.setOperationBuilder().buildANotB();
return anotb.aNotB(tskA, tskB, true, wmem);
}
private static CompactSketch doStdStatefulAnotB(Sketch tskA, Sketch tskB, WritableMemory wmem) {
AnotB anotb = Sketches.setOperationBuilder().buildANotB();
anotb.setA(tskA);
anotb.notB(tskB);
anotb.getResult(false);
return anotb.getResult(true, wmem, true);
}
private static CompactSketch doPwUnion(Sketch tskA, Sketch tskB, int k) {
CompactSketch tcskA, tcskB;
if (tskA == null) { tcskA = null; }
else { tcskA = (tskA instanceof CompactSketch) ? (CompactSketch) tskA : tskA.compact(); }
if (tskB == null) { tcskB = null; }
else { tcskB = (tskB instanceof CompactSketch) ? (CompactSketch) tskB : tskB.compact(); }
Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
return union.union(tcskA, tcskB);
}
private static CompactSketch doPwIntersection(Sketch tskA, Sketch tskB) {
Intersection inter = SetOperation.builder().buildIntersection();
return inter.intersect(tskA, tskB);
}
private static CompactSketch doPwAnotB(Sketch tskA, Sketch tskB) {
AnotB aNotB = SetOperation.builder().buildANotB();
return aNotB.aNotB(tskA, tskB);
}
private static void checkCornerCase(Sketch rskA, Sketch rskB) {
double estA = rskA.getEstimate();
double estB = rskB.getEstimate();
boolean emptyA = rskA.isEmpty();
boolean emptyB = rskB.isEmpty();
long thetaLongA = rskA.getThetaLong();
long thetaLongB = rskB.getThetaLong();
int countA = rskA.getRetainedEntries(true);
int countB = rskB.getRetainedEntries(true);
Assert.assertEquals(estB, estA, 0.0);
Assert.assertEquals(emptyB, emptyA);
Assert.assertEquals(thetaLongB, thetaLongA);
Assert.assertEquals(countB, countA);
Assert.assertEquals(rskA.getClass().getSimpleName(), rskB.getClass().getSimpleName());
}
/*******************************************/
@Test
public void checkUnionNotOrdered() {
int k = 64;
CompactSketch skNull = generate(NULL, k);
CompactSketch skEmpty = generate(EMPTY, k);
CompactSketch skHeap = generate(EST_HEAP, k);
CompactSketch skHeapUO = generate(EST_MEMORY_UNORDERED, k);
Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
union.union(skNull, skHeapUO);
union.union(skEmpty, skHeapUO);
union.union(skHeapUO, skNull);
union.union(skHeapUO, skEmpty);
union.union(skHeapUO, skHeap);
union.union(skHeap, skHeapUO);
}
@Test
public void checkSeedHash() {
int k = 64;
UpdateSketch tmp1 = Sketches.updateSketchBuilder().setNominalEntries(k).setSeed(123).build();
tmp1.update(1);
tmp1.update(3);
CompactSketch skSmallSeed2A = tmp1.compact(true, null);
UpdateSketch tmp2 = Sketches.updateSketchBuilder().setNominalEntries(k).setSeed(123).build();
tmp2.update(1);
tmp2.update(2);
CompactSketch skSmallSeed2B = tmp2.compact(true, null);
CompactSketch skExact = generate(EXACT, k);
CompactSketch skHeap = generate(EST_HEAP, 2 * k);
Intersection inter = SetOperation.builder().buildIntersection();
AnotB aNotB = SetOperation.builder().buildANotB();
Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
//Intersect
try {
inter.intersect(skExact, skSmallSeed2A);
Assert.fail();
} catch (Exception e) { } //pass
try {
inter.intersect(skExact, skSmallSeed2B);
Assert.fail();
} catch (Exception e) { } //pass
try {
inter.intersect(skSmallSeed2B, skExact);
Assert.fail();
} catch (Exception e) { } //pass
try {
inter.intersect(skHeap, skSmallSeed2B);
Assert.fail();
} catch (Exception e) { } //pass
//A NOT B
try {
aNotB.aNotB(skExact, skSmallSeed2A);
Assert.fail();
} catch (Exception e) { } //pass
try {
aNotB.aNotB(skExact, skSmallSeed2B);
Assert.fail();
} catch (Exception e) { } //pass
try {
aNotB.aNotB(skSmallSeed2B, skExact);
Assert.fail();
} catch (Exception e) { } //pass
try {
aNotB.aNotB(skHeap, skSmallSeed2B);
Assert.fail();
} catch (Exception e) { } //pass
//Union
try {
union.union(skExact, skSmallSeed2A);
Assert.fail();
} catch (Exception e) { } //pass
try {
union.union(skExact, skSmallSeed2B);
Assert.fail();
} catch (Exception e) { } //pass
try {
union.union(skSmallSeed2B, skExact);
Assert.fail();
} catch (Exception e) { } //pass
try {
union.union(skHeap, skSmallSeed2B);
Assert.fail();
} catch (Exception e) { } //pass
}
@Test
public void checkPwUnionReduceToK() {
int k = 16;
CompactSketch skNull = generate(NULL, k);
CompactSketch skEmpty = generate(EMPTY, k);
CompactSketch skHeap1 = generate(EST_HEAP, k);
CompactSketch skHeap2 = generate(EST_HEAP, k);
Union union = SetOperation.builder().setNominalEntries(k).buildUnion();
CompactSketch csk;
csk = union.union(skNull, skHeap1);
Assert.assertEquals(csk.getRetainedEntries(true), k);
csk = union.union(skEmpty, skHeap1);
Assert.assertEquals(csk.getRetainedEntries(true), k);
csk = union.union(skHeap1, skNull);
Assert.assertEquals(csk.getRetainedEntries(true), k);
csk = union.union(skHeap1, skEmpty);
Assert.assertEquals(csk.getRetainedEntries(true), k);
csk = union.union(skHeap1, skHeap2);
Assert.assertEquals(csk.getRetainedEntries(true), k);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
@Test
public void checkGenerator() {
int k = 16;
CompactSketch csk;
csk = generate(State.NULL, 0);
assertNull(csk);
csk = generate(State.EMPTY, k);
assertEquals(csk.isEmpty(), true);
assertEquals(csk.isEstimationMode(), false);
assertEquals(csk.getRetainedEntries(true), 0);
assertEquals(csk.getThetaLong(), Long.MAX_VALUE);
assertEquals(csk.isDirect(), false);
assertEquals(csk.hasMemory(), false);
assertEquals(csk.isOrdered(), true);
csk = generate(State.SINGLE, k);
assertEquals(csk.isEmpty(), false);
assertEquals(csk.isEstimationMode(), false);
assertEquals(csk.getRetainedEntries(true), 1);
assertEquals(csk.getThetaLong(), Long.MAX_VALUE);
assertEquals(csk.isDirect(), false);
assertEquals(csk.hasMemory(), false);
assertEquals(csk.isOrdered(), true);
csk = generate(State.EXACT, k);
assertEquals(csk.isEmpty(), false);
assertEquals(csk.isEstimationMode(), false);
assertEquals(csk.getRetainedEntries(true), k);
assertEquals(csk.getThetaLong(), Long.MAX_VALUE);
assertEquals(csk.isDirect(), false);
assertEquals(csk.hasMemory(), false);
assertEquals(csk.isOrdered(), true);
csk = generate(State.EST_HEAP, k);
assertEquals(csk.isEmpty(), false);
assertEquals(csk.isEstimationMode(), true);
assertEquals(csk.getRetainedEntries(true) > k, true);
assertEquals(csk.getThetaLong() < Long.MAX_VALUE, true);
assertEquals(csk.isDirect(), false);
assertEquals(csk.hasMemory(), false);
assertEquals(csk.isOrdered(), true);
csk = generate(State.THLT1_CNT0_FALSE, k);
assertEquals(csk.isEmpty(), false);
assertEquals(csk.isEstimationMode(), true);
assertEquals(csk.getRetainedEntries(true), 0);
assertEquals(csk.getThetaLong() < Long.MAX_VALUE, true);
assertEquals(csk.isDirect(), false);
assertEquals(csk.hasMemory(), false);
assertEquals(csk.isOrdered(), true);
csk = generate(State.THEQ1_CNT0_TRUE, k);
assertEquals(csk.isEmpty(), true);
assertEquals(csk.isEstimationMode(), false);
assertEquals(csk.getRetainedEntries(true), 0);
assertEquals(csk.getThetaLong() < Long.MAX_VALUE, false);
assertEquals(csk.isDirect(), false);
assertEquals(csk.hasMemory(), false);
assertEquals(csk.isOrdered(), true);
csk = generate(State.EST_MEMORY_UNORDERED, k);
assertEquals(csk.isEmpty(), false);
assertEquals(csk.isEstimationMode(), true);
assertEquals(csk.getRetainedEntries(true) > k, true);
assertEquals(csk.getThetaLong() < Long.MAX_VALUE, true);
assertEquals(csk.isDirect(), false);
assertEquals(csk.hasMemory(), true);
assertEquals(csk.isOrdered(), false);
}
enum State {NULL, EMPTY, SINGLE, EXACT, EST_HEAP, THLT1_CNT0_FALSE, THEQ1_CNT0_TRUE, EST_MEMORY_UNORDERED}
private static CompactSketch generate(State state, int k) {
UpdateSketch sk = null;
CompactSketch csk = null;
switch(state) {
case NULL : {
//already null
break;
}
case EMPTY : { //results in EmptyCompactSketch
csk = Sketches.updateSketchBuilder().setNominalEntries(k).build().compact(true, null);
break;
}
case SINGLE : { //results in SingleItemSketches most of the time
sk = Sketches.updateSketchBuilder().setNominalEntries(k).build();
sk.update(1);
csk = sk.compact(true, null);
break;
}
case EXACT : {
sk = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i = 0; i < k; i++) {
sk.update(i);
}
csk = sk.compact(true, null);
break;
}
case EST_HEAP : {
sk = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i = 0; i < (4 * k); i++) {
sk.update(i);
}
csk = sk.compact(true, null);
break;
}
case THLT1_CNT0_FALSE : {
sk = Sketches.updateSketchBuilder().setP((float)0.5).setNominalEntries(k).build();
sk.update(7); //above theta
assert(sk.getRetainedEntries(true) == 0);
csk = sk.compact(true, null); //compact as {Th < 1.0, 0, F}
break;
}
case THEQ1_CNT0_TRUE : {
sk = Sketches.updateSketchBuilder().setP((float)0.5).setNominalEntries(k).build();
assert(sk.getRetainedEntries(true) == 0);
csk = sk.compact(true, null); //compact as {Th < 1.0, 0, T}
break;
}
case EST_MEMORY_UNORDERED : {
sk = Sketches.updateSketchBuilder().setNominalEntries(k).build();
for (int i = 0; i < (4 * k); i++) {
sk.update(i);
}
int bytes = Sketch.getMaxCompactSketchBytes(sk.getRetainedEntries(true));
byte[] byteArr = new byte[bytes];
WritableMemory mem = WritableMemory.writableWrap(byteArr);
csk = sk.compact(false, mem);
break;
}
}
return csk;
}
}
| 2,476 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/ItemsSketchSortedViewString.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import java.util.Comparator;
/**
* For testing only
*/
public class ItemsSketchSortedViewString extends ItemsSketchSortedView<String> {
public ItemsSketchSortedViewString(
final String[] quantiles,
final long[] cumWeights,
final long totalN,
final Comparator<String> comparator) {
super(quantiles, cumWeights, totalN, comparator);
}
}
| 2,477 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/ReadOnlyMemoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.testng.Assert.fail;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesReadOnlyException;
import org.apache.datasketches.memory.Memory;
public class ReadOnlyMemoryTest {
@Test
public void wrapAndTryUpdatingSparseSketch() {
UpdateDoublesSketch s1 = DoublesSketch.builder().build();
s1.update(1);
s1.update(2);
final byte[] bytes = s1.toByteArray(false);
Assert.assertEquals(bytes.length, 64); // 32 + MIN_K(=2) * 2 * 8 = 64
//final Memory mem = Memory.wrap(ByteBuffer.wrap(bytes)
// .asReadOnlyBuffer().order(ByteOrder.nativeOrder()));
final Memory mem = Memory.wrap(bytes);
final UpdateDoublesSketch s2 = (UpdateDoublesSketch) DoublesSketch.wrap(mem);
Assert.assertEquals(s2.getMinItem(), 1.0);
Assert.assertEquals(s2.getMaxItem(), 2.0);
try {
s2.update(3);
fail();
} catch (final SketchesReadOnlyException e) {
// expected
}
}
@Test
public void wrapCompactSketch() {
UpdateDoublesSketch s1 = DoublesSketch.builder().build();
s1.update(1);
s1.update(2);
//Memory mem = Memory.wrap(ByteBuffer.wrap(s1.compact().toByteArray())
// .asReadOnlyBuffer().order(ByteOrder.nativeOrder())););
final Memory mem = Memory.wrap(s1.compact().toByteArray());
final DoublesSketch s2 = DoublesSketch.wrap(mem); // compact, so this is ok
Assert.assertEquals(s2.getMinItem(), 1.0);
Assert.assertEquals(s2.getMaxItem(), 2.0);
Assert.assertEquals(s2.getN(), 2);
}
@Test
public void heapifySparseSketch() {
UpdateDoublesSketch s1 = DoublesSketch.builder().build();
s1.update(1);
s1.update(2);
Memory mem = Memory.wrap(s1.toByteArray(false));
DoublesSketch s2 = DoublesSketch.heapify(mem);
Assert.assertEquals(s2.getMinItem(), 1.0);
Assert.assertEquals(s2.getMaxItem(), 2.0);
}
@Test
public void heapifyAndUpdateSparseSketch() {
UpdateDoublesSketch s1 = DoublesSketch.builder().build();
s1.update(1);
s1.update(2);
Memory mem = Memory.wrap(s1.toByteArray(false));
UpdateDoublesSketch s2 = (UpdateDoublesSketch) DoublesSketch.heapify(mem);
s2.update(3);
Assert.assertEquals(s2.getMinItem(), 1.0);
Assert.assertEquals(s2.getMaxItem(), 3.0);
}
@Test
public void heapifyCompactSketch() {
UpdateDoublesSketch s1 = DoublesSketch.builder().build();
s1.update(1);
s1.update(2);
Memory mem = Memory.wrap(s1.toByteArray(true));
DoublesSketch s2 = DoublesSketch.heapify(mem);
Assert.assertEquals(s2.getMinItem(), 1.0);
Assert.assertEquals(s2.getMaxItem(), 2.0);
}
@Test
public void heapifyEmptyUpdateSketch() {
final UpdateDoublesSketch s1 = DoublesSketch.builder().build();
final Memory mem = Memory.wrap(s1.toByteArray());
DoublesSketch s2 = DoublesSketch.heapify(mem);
Assert.assertTrue(s2.isEmpty());
}
@Test
public void heapifyEmptyCompactSketch() {
final CompactDoublesSketch s1 = DoublesSketch.builder().build().compact();
final Memory mem = Memory.wrap(s1.toByteArray());
DoublesSketch s2 = DoublesSketch.heapify(mem);
Assert.assertTrue(s2.isEmpty());
}
@Test
public void wrapEmptyUpdateSketch() {
final UpdateDoublesSketch s1 = DoublesSketch.builder().build();
final Memory mem = Memory.wrap(s1.toByteArray());
UpdateDoublesSketch s2 = (UpdateDoublesSketch) DoublesSketch.wrap(mem);
Assert.assertTrue(s2.isEmpty());
// ensure the various put calls fail
try {
s2.putMinItem(-1.0);
fail();
} catch (final SketchesReadOnlyException e) {
// expected
}
try {
s2.putMaxItem(1.0);
fail();
} catch (final SketchesReadOnlyException e) {
// expected
}
try {
s2.putN(1);
fail();
} catch (final SketchesReadOnlyException e) {
// expected
}
try {
s2.putBitPattern(1);
fail();
} catch (final SketchesReadOnlyException e) {
// expected
}
try {
s2.reset();
fail();
} catch (final SketchesReadOnlyException e) {
// expected
}
try {
s2.putBaseBufferCount(5);
fail();
} catch (final SketchesReadOnlyException e) {
// expected
}
try {
s2.putCombinedBuffer(new double[16]);
fail();
} catch (final SketchesReadOnlyException e) {
// expected
}
try {
final int currCap = s2.getCombinedBufferItemCapacity();
s2.growCombinedBuffer(currCap, 2 * currCap);
fail();
} catch (final SketchesReadOnlyException e) {
// expected
}
}
@Test
public void wrapEmptyCompactSketch() {
final UpdateDoublesSketch s1 = DoublesSketch.builder().build();
final Memory mem = Memory.wrap(s1.compact().toByteArray());
DoublesSketch s2 = DoublesSketch.wrap(mem); // compact, so this is ok
Assert.assertTrue(s2.isEmpty());
}
@Test
public void heapifyUnionFromSparse() {
UpdateDoublesSketch s1 = DoublesSketch.builder().build();
s1.update(1);
s1.update(2);
Memory mem = Memory.wrap(s1.toByteArray(false));
DoublesUnion u = DoublesUnion.heapify(mem);
u.update(3);
DoublesSketch s2 = u.getResult();
Assert.assertEquals(s2.getMinItem(), 1.0);
Assert.assertEquals(s2.getMaxItem(), 3.0);
}
@Test
public void heapifyUnionFromCompact() {
UpdateDoublesSketch s1 = DoublesSketch.builder().build();
s1.update(1);
s1.update(2);
Memory mem = Memory.wrap(s1.toByteArray(true));
DoublesUnion u = DoublesUnion.heapify(mem);
u.update(3);
DoublesSketch s2 = u.getResult();
Assert.assertEquals(s2.getMinItem(), 1.0);
Assert.assertEquals(s2.getMaxItem(), 3.0);
}
@Test
public void wrapUnionFromSparse() {
UpdateDoublesSketch s1 = DoublesSketch.builder().build();
s1.update(1);
s1.update(2);
Memory mem = Memory.wrap(s1.toByteArray(false));
DoublesUnion u = DoublesUnion.wrap(mem);
DoublesSketch s2 = u.getResult();
Assert.assertEquals(s2.getMinItem(), 1.0);
Assert.assertEquals(s2.getMaxItem(), 2.0);
// ensure update and reset methods fail
try {
u.update(3);
fail();
} catch (SketchesReadOnlyException e) {
// expected
}
try {
u.union(s2);
fail();
} catch (SketchesReadOnlyException e) {
// expected
}
try {
u.union(mem);
fail();
} catch (SketchesReadOnlyException e) {
// expected
}
try {
u.reset();
fail();
} catch (SketchesReadOnlyException e) {
// expected
}
try {
u.getResultAndReset();
fail();
} catch (SketchesReadOnlyException e) {
// expected
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void wrapUnionFromCompact() {
UpdateDoublesSketch s1 = DoublesSketch.builder().build();
s1.update(1);
s1.update(2);
Memory mem = Memory.wrap(s1.toByteArray(true));
DoublesUnion.wrap(mem);
fail();
}
}
| 2,478 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/DirectQuantilesMemoryRequestTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.quantiles.PreambleUtil.COMBINED_BUFFER;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.nio.ByteOrder;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.testng.annotations.Test;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableHandle;
import org.apache.datasketches.memory.WritableMemory;
/**
* The concept for these tests is that the "MemoryManager" classes below are proxies for the
* implementation that <i>owns</i> the native memory allocations, thus is responsible for
* allocating larger Memory when requested and the actual freeing of the old memory allocations.
*/
public class DirectQuantilesMemoryRequestTest {
@Test
public void checkLimitedMemoryScenarios() { //Requesting application
final int k = 128;
final int u = 40 * k;
final int initBytes = ((2 * k) + 4) << 3; //just the BB
//########## Owning Implementation
// This part would actually be part of the Memory owning implemention so it is faked here
try (WritableHandle wdh = WritableMemory.allocateDirect(initBytes,
ByteOrder.nativeOrder(), new DefaultMemoryRequestServer())) {
final WritableMemory wmem = wdh.getWritable();
println("Initial mem size: " + wmem.getCapacity());
//########## Receiving Application
// The receiving application has been given wmem to use for a sketch,
// but alas, it is not ultimately large enough.
final UpdateDoublesSketch usk1 = DoublesSketch.builder().setK(k).build(wmem);
assertTrue(usk1.isEmpty());
//Load the sketch
for (int i = 0; i < u; i++) {
// The sketch uses The MemoryRequest, acquired from wmem, to acquire more memory as
// needed, and requests via the MemoryRequest to free the old allocations.
usk1.update(i);
}
final double result = usk1.getQuantile(0.5);
println("Result: " + result);
assertEquals(result, u / 2.0, 0.05 * u); //Success
//########## Owning Implementation
//The actual Memory has been re-allocated several times,
// so the above wmem reference is invalid.
println("\nFinal mem size: " + wmem.getCapacity());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkGrowBaseBuf() {
final int k = 128;
final int u = 32; // don't need the BB to fill here
final int initBytes = (4 + (u / 2)) << 3; // not enough to hold everything
try (WritableHandle memHandler = WritableMemory.allocateDirect(initBytes,
ByteOrder.nativeOrder(), new DefaultMemoryRequestServer())) {
//final MemoryManager memMgr = new MemoryManager();
//final WritableMemory mem1 = memMgr.request(initBytes);
final WritableMemory mem1 = memHandler.getWritable();
println("Initial mem size: " + mem1.getCapacity());
final UpdateDoublesSketch usk1 = DoublesSketch.builder().setK(k).build(mem1);
for (int i = 1; i <= u; i++) {
usk1.update(i);
}
final int currentSpace = usk1.getCombinedBufferItemCapacity();
println("curCombBufItemCap: " + currentSpace);
assertEquals(currentSpace, 2 * k);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkGrowCombBuf() {
final int k = 128;
final int u = (2 * k) - 1; //just to fill the BB
final int initBytes = ((2 * k) + 4) << 3; //just room for BB
try (WritableHandle memHandler = WritableMemory.allocateDirect(initBytes,
ByteOrder.nativeOrder(), new DefaultMemoryRequestServer())) {
//final MemoryManager memMgr = new MemoryManager();
//final WritableMemory mem1 = memMgr.request(initBytes);
final WritableMemory mem1 = memHandler.getWritable();
println("Initial mem size: " + mem1.getCapacity());
final UpdateDoublesSketch usk1 = DoublesSketch.builder().setK(k).build(mem1);
for (int i = 1; i <= u; i++) {
usk1.update(i);
}
final int currentSpace = usk1.getCombinedBufferItemCapacity();
println("curCombBufItemCap: " + currentSpace);
final double[] newCB = usk1.growCombinedBuffer(currentSpace, 3 * k);
final int newSpace = usk1.getCombinedBufferItemCapacity();
println("newCombBurItemCap: " + newSpace);
assertEquals(newCB.length, 3 * k);
//memMgr.free(mem1);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkGrowFromWrappedEmptySketch() {
final int k = 16;
final int n = 0;
final int initBytes = DoublesSketch.getUpdatableStorageBytes(k, n); //8 bytes
final UpdateDoublesSketch usk1 = DoublesSketch.builder().setK(k).build();
final Memory origSketchMem = Memory.wrap(usk1.toByteArray());
try (WritableHandle memHandle = WritableMemory.allocateDirect(initBytes,
ByteOrder.nativeOrder(), new DefaultMemoryRequestServer())) {
WritableMemory mem = memHandle.getWritable();
origSketchMem.copyTo(0, mem, 0, initBytes);
UpdateDoublesSketch usk2 = DirectUpdateDoublesSketch.wrapInstance(mem);
assertTrue(mem.isSameResource(usk2.getMemory()));
assertEquals(mem.getCapacity(), initBytes);
assertTrue(mem.isDirect());
assertTrue(usk2.isEmpty());
//update the sketch forcing it to grow on-heap
for (int i = 1; i <= 5; i++) { usk2.update(i); }
assertEquals(usk2.getN(), 5);
WritableMemory mem2 = usk2.getMemory();
assertFalse(mem.isSameResource(mem2));
assertFalse(mem2.isDirect()); //should now be on-heap
final int expectedSize = COMBINED_BUFFER + ((2 * k) << 3);
assertEquals(mem2.getCapacity(), expectedSize);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,479 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/DoublesUnionImplTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.quantiles.DirectUpdateDoublesSketchTest.buildAndLoadDQS;
import static org.apache.datasketches.quantiles.HeapUpdateDoublesSketchTest.buildAndLoadQS;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
public class DoublesUnionImplTest {
@Test
public void checkUnion1() {
DoublesSketch result;
final DoublesSketch qs1;
final DoublesUnion union = DoublesUnion.builder().setMaxK(256).build(); //virgin 256
final DoublesSketch qs0 = buildAndLoadQS(256, 500);
union.union(qs0); //me = null, that = valid, exact
result = union.getResult();
assertEquals(result.getN(), 500);
assertEquals(result.getK(), 256);
union.reset();
qs1 = buildAndLoadQS(256, 1000); //first 1000
union.union(qs1); //me = null, that = valid, OK
//check copy me = null, that = valid
result = union.getResult();
assertEquals(result.getN(), 1000);
assertEquals(result.getK(), 256);
//check merge me = valid, that = valid, both K's the same
final DoublesSketch qs2 = buildAndLoadQS(256, 1000, 1000); //add 1000
union.union(qs2);
result = union.getResult();
assertEquals(result.getN(), 2000);
assertEquals(result.getK(), 256);
}
@Test
public void checkUnion1Direct() {
DoublesSketch result;
final DoublesSketch qs1;
final DoublesUnion union = DoublesUnion.builder().setMaxK(256).build(); //virgin 256
final DoublesSketch qs0 = buildAndLoadDQS(256, 500);
union.union(qs0); //me = null, that = valid, exact
result = union.getResult();
assertEquals(result.getN(), 500);
assertEquals(result.getK(), 256);
union.reset();
qs1 = buildAndLoadDQS(256, 1000); //first 1000
union.union(qs1); //me = null, that = valid, OK
//check copy me = null, that = valid
result = union.getResult();
assertEquals(result.getN(), 1000);
assertEquals(result.getK(), 256);
//check merge me = valid, that = valid, both K's the same
final DoublesSketch qs2 = buildAndLoadDQS(256, 1000, 1000).compact(); //add 1000
union.union(qs2);
result = union.getResult();
assertEquals(result.getN(), 2000);
assertEquals(result.getK(), 256);
}
@Test
public void checkUnion2() {
final DoublesSketch qs1 = buildAndLoadQS(256, 1000).compact();
final DoublesSketch qs2 = buildAndLoadQS(128, 1000);
final DoublesUnion union = DoublesUnion.builder().setMaxK(256).build(); //virgin 256
assertEquals(union.getEffectiveK(), 256);
union.union(qs1);
final DoublesSketch res1 = union.getResult();
//println(res1.toString());
assertEquals(res1.getN(), 1000);
assertEquals(res1.getK(), 256);
union.union(qs2);
final DoublesSketch res2 = union.getResult();
assertEquals(res2.getN(), 2000);
assertEquals(res2.getK(), 128);
assertEquals(union.getEffectiveK(), 128);
println(union.toString());
}
@Test
public void checkUnion2Direct() {
final DoublesSketch qs1 = buildAndLoadDQS(256, 1000);
final DoublesSketch qs2 = buildAndLoadDQS(128, 1000);
final DoublesUnion union = DoublesUnion.builder().setMaxK(256).build(); //virgin 256
assertEquals(union.getEffectiveK(), 256);
union.union(qs1);
final DoublesSketch res1 = union.getResult();
//println(res1.toString());
assertEquals(res1.getN(), 1000);
assertEquals(res1.getK(), 256);
union.union(qs2);
final DoublesSketch res2 = union.getResult();
assertEquals(res2.getN(), 2000);
assertEquals(res2.getK(), 128);
assertEquals(union.getEffectiveK(), 128);
println(union.toString());
}
@Test
public void checkUnion3() { //Union is direct, empty and with larger K than valid input
final int k1 = 128;
final int n1 = 2 * k1;
final int k2 = 256;
final int n2 = 2000;
final DoublesSketch sketchIn1 = buildAndLoadQS(k1, n1);
final int bytes = DoublesSketch.getUpdatableStorageBytes(k2, n2);//just for size
final WritableMemory mem = WritableMemory.writableWrap(new byte[bytes]);
final DoublesUnion union = DoublesUnion.builder().setMaxK(k2).build(mem); //virgin 256
union.union(sketchIn1);
assertEquals(union.getMaxK(), k2);
assertEquals(union.getEffectiveK(), k1);
final DoublesSketch result = union.getResult();
assertEquals(result.getMaxItem(), n1, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
assertEquals(result.getK(), k1);
}
@Test
public void checkUnion3Direct() { //Union is direct, empty and with larger K than valid input
final int k1 = 128;
final int n1 = 2 * k1;
final int k2 = 256;
final int n2 = 2000;
final DoublesSketch sketchIn1 = buildAndLoadDQS(k1, n1);
final int bytes = DoublesSketch.getUpdatableStorageBytes(k2, n2);//just for size
final WritableMemory mem = WritableMemory.writableWrap(new byte[bytes]);
final DoublesUnion union = DoublesUnion.builder().setMaxK(k2).build(mem); //virgin 256
union.union(sketchIn1);
assertEquals(union.getMaxK(), k2);
assertEquals(union.getEffectiveK(), k1);
final DoublesSketch result = union.getResult();
assertEquals(result.getMaxItem(), n1, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
assertEquals(result.getK(), k1);
}
@Test
public void checkUnion4() { //Union is direct, valid and with larger K than valid input
final int k1 = 8;
final int n1 = 2 * k1; //16
final int k2 = 4;
final int n2 = 2 * k2; //8
final int bytes = DoublesSketch.getUpdatableStorageBytes(256, 50);//just for size
final WritableMemory skMem = WritableMemory.writableWrap(new byte[bytes]);
final UpdateDoublesSketch sketchIn1 = DoublesSketch.builder().setK(k1).build(skMem);
for (int i = 0; i < n1; i++) { sketchIn1.update(i + 1); }
final WritableMemory uMem = WritableMemory.writableWrap(new byte[bytes]);
final DoublesUnion union = DoublesUnion.builder().setMaxK(256).build(uMem); //virgin 256
//DoublesUnion union = DoublesUnion.builder().setMaxK(256).build(); //virgin 256
union.union(sketchIn1);
assertEquals(union.getResult().getN(), n1);
assertEquals(union.getMaxK(), 256);
assertEquals(union.getEffectiveK(), k1);
DoublesSketch result = union.getResult();
assertEquals(result.getN(), 16);
assertEquals(result.getMaxItem(), n1, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
assertEquals(result.getK(), k1);
final DoublesSketch sketchIn2 = buildAndLoadQS(k2, n2, 17);
union.reset();
union.union(sketchIn2);
result = union.getResult();
assertEquals(result.getMaxItem(), n2 + 17, 0.0);
assertEquals(result.getMinItem(), 1.0 + 17, 0.0);
println("\nFinal" + union.getResult().toString(true, true));
}
@Test
public void checkUnion4Direct() { //Union is direct, valid and with larger K than valid input
final int k1 = 8;
final int n1 = 2 * k1; //16
final int k2 = 4;
final int n2 = 2 * k2; //8
final int bytes = DoublesSketch.getUpdatableStorageBytes(256, 50);//just for size
final WritableMemory skMem = WritableMemory.writableWrap(new byte[bytes]);
final UpdateDoublesSketch sketchIn1 = DoublesSketch.builder().setK(k1).build(skMem);
for (int i = 0; i < n1; i++) { sketchIn1.update(i + 1); }
final WritableMemory uMem = WritableMemory.writableWrap(new byte[bytes]);
final DoublesUnion union = DoublesUnion.builder().setMaxK(256).build(uMem); //virgin 256
union.union(sketchIn1);
assertEquals(union.getResult().getN(), n1);
assertEquals(union.getMaxK(), 256);
assertEquals(union.getEffectiveK(), k1);
DoublesSketch result = union.getResult();
assertEquals(result.getN(), 16);
assertEquals(result.getMaxItem(), n1, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
assertEquals(result.getK(), k1);
final DoublesSketch sketchIn2 = buildAndLoadDQS(k2, n2, 17);
union.reset();
union.union(sketchIn2);
result = union.getResult();
assertEquals(result.getMaxItem(), n2 + 17, 0.0);
assertEquals(result.getMinItem(), 1.0 + 17, 0.0);
println("\nFinal" + union.getResult().toString(true, true));
}
@Test
public void checkUnion4DirectCompact() {
final int k1 = 8;
final int n1 = 2 * k1; //16
final int k2 = 4;
final int n2 = 5 * k2; //8
final int bytes = DoublesSketch.getUpdatableStorageBytes(256, 50);//just for size
final WritableMemory skMem = WritableMemory.writableWrap(new byte[bytes]);
final UpdateDoublesSketch sketchIn0 = DoublesSketch.builder().setK(k1).build(skMem);
for (int i = 0; i < n1; i++) { sketchIn0.update(i + 1); }
final CompactDoublesSketch sketchIn1 = sketchIn0.compact();
final WritableMemory uMem = WritableMemory.writableWrap(new byte[bytes]);
final DoublesUnion union = DoublesUnion.builder().setMaxK(256).build(uMem); //virgin 256
union.union(sketchIn1);
assertEquals(union.getResult().getN(), n1);
assertEquals(union.getMaxK(), 256);
assertEquals(union.getEffectiveK(), k1);
DoublesSketch result = union.getResult();
assertEquals(result.getN(), 16);
assertEquals(result.getMaxItem(), n1, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
assertEquals(result.getK(), k1);
final CompactDoublesSketch sketchIn2 = buildAndLoadDQS(k2, n2, 17).compact();
union.reset();
union.union(sketchIn2);
result = union.getResult();
assertEquals(result.getMaxItem(), n2 + 17, 0.0);
assertEquals(result.getMinItem(), 1.0 + 17, 0.0);
println("\nFinal" + union.getResult().toString(true, true));
}
@Test
public void checkUnion5() { //Union is direct, valid and with larger K than valid input
final int k2 = 4;
final int n2 = 2 * k2; //8
final int bytes = DoublesSketch.getUpdatableStorageBytes(256, 50);//big enough
final WritableMemory skMem = WritableMemory.writableWrap(new byte[bytes]);
DoublesSketch.builder().setK(256).build(skMem);
final DoublesUnion union = DoublesUnionImpl.heapifyInstance(skMem);
assertEquals(union.getResult().getN(), 0);
assertEquals(union.getMaxK(), 256);
assertEquals(union.getEffectiveK(), 256);
final DoublesSketch result = union.getResult();
assertEquals(result.getK(), 256);
final DoublesSketch sketchIn2 = buildAndLoadQS(k2, n2, 17);
union.union(sketchIn2);
println("\nFinal" + union.getResult().toString(true, true));
assertEquals(union.getResult().getN(), n2);
}
@Test
public void checkUnion5Direct() { //Union is direct, valid and with larger K than valid input
final int k2 = 4;
final int n2 = 2 * k2; //8
final int bytes = DoublesSketch.getUpdatableStorageBytes(256, 50);//big enough
final WritableMemory skMem = WritableMemory.writableWrap(new byte[bytes]);
DoublesSketch.builder().setK(256).build(skMem);
final DoublesUnion union = DoublesUnionImpl.heapifyInstance(skMem);
assertEquals(union.getResult().getN(), 0);
assertEquals(union.getMaxK(), 256);
assertEquals(union.getEffectiveK(), 256);
final DoublesSketch result = union.getResult();
assertEquals(result.getK(), 256);
final DoublesSketch sketchIn2 = buildAndLoadDQS(k2, n2, 17);
union.union(sketchIn2);
println("\nFinal" + union.getResult().toString(true, true));
assertEquals(union.getResult().getN(), n2);
}
@Test
public void checkUnion6() {
final int k1 = 8;
final int n1 = 2 * k1; //16
final int k2 = 16;
final int n2 = 2 * k2; //32
final DoublesSketch sk1 = buildAndLoadQS(k1, n1, 0);
final DoublesSketch sk2 = buildAndLoadQS(k2, n2, n1);
final DoublesUnion union = DoublesUnionImpl.heapifyInstance(sk1);
union.union(sk2);
final DoublesSketch result = union.getResult();
assertEquals(result.getMaxItem(), n1 + n2, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
println("\nFinal" + union.getResult().toString(true, true));
}
@Test
public void checkUnion6Direct() {
final int k1 = 8;
final int n1 = 2 * k1; //16
final int k2 = 16;
final int n2 = 2 * k2; //32
final DoublesSketch sk1 = buildAndLoadDQS(k1, n1, 0);
final DoublesSketch sk2 = buildAndLoadDQS(k2, n2, n1);
final DoublesUnion union = DoublesUnionImpl.heapifyInstance(sk1);
union.union(sk2);
final DoublesSketch result = union.getResult();
assertEquals(result.getMaxItem(), n1 + n2, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
println("\nFinal" + union.getResult().toString(true, true));
}
@Test
public void checkUnion7() {
final DoublesUnion union = DoublesUnionImpl.heapInstance(16);
final DoublesSketch skEst = buildAndLoadQS(32, 64); //other is bigger, est
union.union(skEst);
println(skEst.toString(true, true));
println(union.toString(true, true));
final DoublesSketch result = union.getResult();
assertEquals(result.getMaxItem(), 64, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
}
@Test
public void checkUnionQuantiles() {
final int k = 128;
final int n1 = k * 13;
final int n2 = (k * 8) + (k / 2);
final int n = n1 + n2;
final double errorTolerance = 0.0175 * n; // assuming k = 128
final UpdateDoublesSketch sketch1 = buildAndLoadQS(k, n1);
final CompactDoublesSketch sketch2 = buildAndLoadQS(k, n2, n1).compact();
final DoublesUnion union = DoublesUnion.builder().setMaxK(256).build(); //virgin 256
union.union(sketch2);
union.union(sketch1);
final Memory mem = Memory.wrap(union.getResult().toByteArray(true));
final DoublesSketch result = DoublesSketch.wrap(mem);
assertEquals(result.getN(), n1 + n2);
assertEquals(result.getK(), k);
for (double fraction = 0.05; fraction < 1.0; fraction += 0.05) {
assertEquals(result.getQuantile(fraction), fraction * n, errorTolerance);
}
}
@Test
public void checkUnion7Direct() {
final DoublesUnion union = DoublesUnionImpl.heapInstance(16);
final DoublesSketch skEst = buildAndLoadDQS(32, 64); //other is bigger, est
union.union(skEst);
final DoublesSketch result = union.getResult();
assertEquals(result.getMaxItem(), 64, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
// println(skEst.toString(true, true));
// println(union.toString(true, true));
}
@Test
public void checkUpdateMemory() {
final DoublesSketch qs1 = buildAndLoadQS(256, 1000);
final int bytes = qs1.getCurrentCompactSerializedSizeBytes();
final WritableMemory dstMem = WritableMemory.writableWrap(new byte[bytes]);
qs1.putMemory(dstMem);
final Memory srcMem = dstMem;
final DoublesUnion union = DoublesUnion.builder().build(); //virgin
union.union(srcMem);
for (int i = 1000; i < 2000; i++) { union.update(i); }
final DoublesSketch qs2 = union.getResult();
assertEquals(qs2.getMaxItem(), 1999, 0.0);
final String s = union.toString();
println(s); //enable printing to see
union.reset(); //sets to null
}
@Test
public void checkUpdateMemoryDirect() {
final DoublesSketch qs1 = buildAndLoadDQS(256, 1000);
final int bytes = qs1.getCurrentCompactSerializedSizeBytes();
final WritableMemory dstMem = WritableMemory.writableWrap(new byte[bytes]);
qs1.putMemory(dstMem);
final Memory srcMem = dstMem;
final DoublesUnion union = DoublesUnion.builder().build(); //virgin
union.union(srcMem);
for (int i = 1000; i < 2000; i++) { union.update(i); }
final DoublesSketch qs2 = union.getResult();
assertEquals(qs2.getMaxItem(), 1999, 0.0);
final String s = union.toString();
println(s); //enable printing to see
union.reset(); //sets to null
}
@Test
public void checkUnionUpdateLogic() {
final HeapUpdateDoublesSketch qs1 = null;
final HeapUpdateDoublesSketch qs2 = (HeapUpdateDoublesSketch) buildAndLoadQS(256, 0);
DoublesUnionImpl.updateLogic(256, qs1, qs2); //null, empty
DoublesUnionImpl.updateLogic(256, qs2, qs1); //empty, null
qs2.update(1); //no longer empty
final DoublesSketch result = DoublesUnionImpl.updateLogic(256, qs2, qs1); //valid, null
assertEquals(result.getMaxItem(), result.getMinItem(), 0.0);
}
@Test
public void checkUnionUpdateLogicDirect() {
final HeapUpdateDoublesSketch qs1 = null;
final DirectUpdateDoublesSketch qs2 = (DirectUpdateDoublesSketch) buildAndLoadDQS(256, 0);
DoublesUnionImpl.updateLogic(256, qs1, qs2); //null, empty
DoublesUnionImpl.updateLogic(256, qs2, qs1); //empty, null
qs2.update(1); //no longer empty
final DoublesSketch result = DoublesUnionImpl.updateLogic(256, qs2, qs1); //valid, null
assertEquals(result.getMaxItem(), result.getMinItem(), 0.0);
}
@Test
public void checkUnionUpdateLogicDirectDownsampled() {
final DirectUpdateDoublesSketch qs1 = (DirectUpdateDoublesSketch) buildAndLoadDQS(256, 1000);
final DirectUpdateDoublesSketch qs2 = (DirectUpdateDoublesSketch) buildAndLoadDQS(128, 2000);
final DoublesSketch result = DoublesUnionImpl.updateLogic(128, qs1, qs2);
assertEquals(result.getMaxItem(), 2000.0, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
assertEquals(result.getN(), 3000);
assertEquals(result.getK(), 128);
}
@Test
public void checkUnionUpdateLogic2() {
DoublesSketch qs1 = DoublesSketch.builder().build();
final DoublesSketch qs2 = DoublesSketch.builder().build();
final DoublesUnion union = DoublesUnion.builder().build();
union.union(qs1);
union.union(qs2); //case 5
qs1 = buildAndLoadQS(128, 1000);
union.union(qs1);
union.union(qs2); //case 9
final DoublesSketch result = union.getResult();
//println(union.toString(true, true));
assertEquals(result.getMaxItem(), 1000.0, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
}
@Test
public void checkUnionUpdateLogic2Direct() {
DoublesSketch qs1 = DoublesSketch.builder().build();
final DoublesSketch qs2 = DoublesSketch.builder().build();
final DoublesUnion union = DoublesUnion.builder().build();
union.union(qs1);
union.union(qs2); //case 5
qs1 = buildAndLoadDQS(128, 1000);
union.union(qs1);
union.union(qs2); //case 9
final DoublesSketch result = union.getResult();
//println(union.toString(true, true));
assertEquals(result.getMaxItem(), 1000.0, 0.0);
assertEquals(result.getMinItem(), 1.0, 0.0);
}
@Test
public void checkResultAndReset() {
final DoublesSketch qs1 = buildAndLoadQS(256, 0);
final DoublesUnion union = DoublesUnion.heapify(qs1);
final DoublesSketch qs2 = union.getResultAndReset();
assertEquals(qs2.getK(), 256);
}
@Test
public void checkResultAndResetDirect() {
final DoublesSketch qs1 = buildAndLoadDQS(256, 0);
final DoublesUnion union = DoublesUnion.heapify(qs1);
final DoublesSketch qs2 = union.getResultAndReset();
assertEquals(qs2.getK(), 256);
}
@Test
public void checkResultViaMemory() {
// empty gadget
final DoublesUnion union = DoublesUnion.builder().build();
// memory too small
WritableMemory mem = WritableMemory.allocate(1);
try {
union.getResult(mem);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
// sufficient memory
mem = WritableMemory.allocate(8);
DoublesSketch result = union.getResult(mem);
assertTrue(result.isEmpty());
final int k = 128;
final int n = 1392;
mem = WritableMemory.allocate(DoublesSketch.getUpdatableStorageBytes(k, n));
final DoublesSketch qs = buildAndLoadQS(k, n);
union.union(qs);
result = union.getResult(mem);
DoublesSketchTest.testSketchEquality(result, qs);
}
@Test
public void updateWithDoubleValueOnly() {
final DoublesUnion union = DoublesUnion.builder().build();
union.update(123.456);
final DoublesSketch qs = union.getResultAndReset();
assertEquals(qs.getN(), 1);
}
@Test
public void checkEmptyUnion() {
final DoublesUnionImpl union = DoublesUnionImpl.heapInstance(128);
final DoublesSketch sk = union.getResult();
assertNotNull(sk);
final byte[] bytes = union.toByteArray();
assertEquals(bytes.length, 8); //
final String s = union.toString();
assertNotNull(s);
}
@Test
public void checkUnionNulls() {
final DoublesUnion union = DoublesUnionImpl.heapInstance(128);
final DoublesSketch sk1 = union.getResultAndReset();
final DoublesSketch sk2 = union.getResultAndReset();
assertNull(sk1);
assertNull(sk2);
try { union.union(sk2); fail(); }
catch (NullPointerException e) { }
final DoublesSketch sk3 = union.getResultAndReset();
assertNull(sk3);
}
@Test
public void differentLargerK() {
final DoublesUnion union = DoublesUnion.builder().setMaxK(128).build();
final UpdateDoublesSketch sketch1 = buildAndLoadQS(256, 0);
union.union(sketch1);
Assert.assertEquals(union.getResult().getK(), 128);
sketch1.update(1.0);
union.union(sketch1);
Assert.assertEquals(union.getResult().getK(), 128);
}
@Test
public void differentLargerKDirect() {
final DoublesUnion union = DoublesUnion.builder().setMaxK(128).build();
final UpdateDoublesSketch sketch1 = buildAndLoadDQS(256, 0);
union.union(sketch1);
Assert.assertEquals(union.getResult().getK(), 128);
sketch1.update(1.0);
union.union(sketch1);
Assert.assertEquals(union.getResult().getK(), 128);
}
@Test
public void differentEmptySmallerK() {
final int k128 = 128;
final int k64 = 64;
final DoublesUnion union = DoublesUnion.builder().setMaxK(k128).build();
assertTrue(union.isEmpty()); //gadget is null
assertFalse(union.hasMemory());
assertFalse(union.isDirect());
// byte[] unionByteArr = union.toByteArray();
// Assert.assertEquals(unionByteArr.length, 32 + 32); //empty
final UpdateDoublesSketch sketch1 = buildAndLoadQS(k64, 0); //build smaller empty sketch
union.union(sketch1);
assertTrue(union.isEmpty()); //gadget is valid
assertFalse(union.hasMemory());
assertFalse(union.isDirect());
// unionByteArr = union.toByteArray();
// int udBytes = DoublesSketch.getUpdatableStorageBytes(k64, 0);
// Assert.assertEquals(unionByteArr.length, udBytes); //empty
assertEquals(union.getResult().getK(), 128);
sketch1.update(1.0);
union.union(sketch1);
assertEquals(union.getResult().getK(), 128);
}
@Test
public void differentEmptySmallerKDirect() {
final int k128 = 128;
final int k64 = 64;
final DoublesUnion union = DoublesUnion.builder().setMaxK(k128).build();
assertTrue(union.isEmpty()); //gadget is null
assertFalse(union.hasMemory());
assertFalse(union.isDirect());
// byte[] unionByteArr = union.toByteArray();
// Assert.assertEquals(unionByteArr.length, 32 + 32); //empty
final UpdateDoublesSketch sketch1 = buildAndLoadDQS(k64, 0); //build smaller empty sketch
union.union(sketch1);
assertTrue(union.isEmpty()); //gadget is valid
assertFalse(union.hasMemory());
assertFalse(union.isDirect());
// unionByteArr = union.toByteArray();
// int udBytes = DoublesSketch.getUpdatableStorageBytes(k64, 0);
// Assert.assertEquals(unionByteArr.length, udBytes); //empty
assertEquals(union.getResult().getK(), 128);
sketch1.update(1.0);
union.union(sketch1);
assertEquals(union.getResult().getK(), 128);
}
@Test
public void checkDirectInstance() {
final int k = 128;
final int n = 1000;
final DoublesUnionBuilder bldr = DoublesUnion.builder();
bldr.setMaxK(k);
assertEquals(bldr.getMaxK(), k);
final int bytes = DoublesSketch.getUpdatableStorageBytes(k, n);
final byte[] byteArr = new byte[bytes];
final WritableMemory mem = WritableMemory.writableWrap(byteArr);
final DoublesUnion union = bldr.build(mem);
assertTrue(union.isEmpty());
assertTrue(union.hasMemory());
assertFalse(union.isDirect());
for (int i = 1; i <= n; i++) {
union.update(i);
}
assertFalse(union.isEmpty());
final DoublesSketch res = union.getResult();
final double median = res.getQuantile(.5);
assertEquals(median, 500, 10);
println(union.toString());
}
@Test
public void checkWrapInstance() {
final int k = 128;
final int n = 1000;
final UpdateDoublesSketch sketch = DoublesSketch.builder().setK(k).build();
for (int i = 1; i <= n; i++) {
sketch.update(i);
}
final double skMedian = sketch.getQuantile(.5);
Assert.assertEquals(skMedian, 500, 10);
final byte[] byteArr = sketch.toByteArray(false);
final WritableMemory mem = WritableMemory.writableWrap(byteArr);
final DoublesUnion union = DoublesUnion.wrap(mem);
Assert.assertFalse(union.isEmpty());
assertTrue(union.hasMemory());
assertFalse(union.isDirect());
final DoublesSketch sketch2 = union.getResult();
final double uMedian = sketch2.getQuantile(0.5);
Assert.assertEquals(skMedian, uMedian, 0.0);
// check serializing again
final byte[] bytesOut = union.toByteArray();
assertEquals(bytesOut.length, byteArr.length);
assertEquals(bytesOut, byteArr); // wrapped, so should be exact
}
@Test
public void isSameResourceHeap() {
DoublesUnion union = DoublesUnion.builder().build();
Assert.assertFalse(union.isSameResource(null));
}
@Test
public void isSameResourceDirect() {
WritableMemory mem1 = WritableMemory.writableWrap(new byte[1000000]);
DoublesUnion union = DoublesUnion.builder().build(mem1);
Assert.assertTrue(union.isSameResource(mem1));
WritableMemory mem2 = WritableMemory.writableWrap(new byte[1000000]);
Assert.assertFalse(union.isSameResource(mem2));
}
@Test
public void emptyUnionSerDeIssue195() {
DoublesUnion union = DoublesUnion.builder().build();
byte[] byteArr = union.toByteArray();
Memory mem = Memory.wrap(byteArr);
DoublesUnion union2 = DoublesUnion.heapify(mem);
Assert.assertEquals(mem.getCapacity(), 8L);
Assert.assertTrue(union2.isEmpty());
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,480 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/ItemsUnionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.quantiles.PreambleUtil.DEFAULT_K;
import static org.testng.Assert.fail;
import java.util.Comparator;
import org.apache.datasketches.common.ArrayOfItemsSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.memory.Memory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ItemsUnionTest {
@Test
public void nullAndEmpty() {
final ItemsSketch<Integer> emptySk = ItemsSketch.getInstance(Integer.class, Comparator.naturalOrder());
final ItemsSketch<Integer> validSk = ItemsSketch.getInstance(Integer.class, Comparator.naturalOrder());
ItemsSketch<Integer> result;
validSk.update(1);
ItemsUnion<Integer> union = ItemsUnion.getInstance(Integer.class, Comparator.naturalOrder());
union.union(validSk);
union = ItemsUnion.getInstance(emptySk);
// internal sketch is empty at this point
union.union((ItemsSketch<Integer>) null);
union.union(emptySk);
Assert.assertTrue(union.isEmpty());
Assert.assertFalse(union.isDirect());
Assert.assertEquals(union.getMaxK(), DEFAULT_K);
Assert.assertEquals(union.getEffectiveK(), DEFAULT_K);
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getN(), 0);
try { result.getMinItem(); fail(); } catch (IllegalArgumentException e) {}
try { result.getMaxItem(); fail(); } catch (IllegalArgumentException e) {}
union.union(validSk);
union.reset();
// internal sketch is null again
union.union((ItemsSketch<Integer>) null);
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getN(), 0);
try { result.getMinItem(); fail(); } catch (IllegalArgumentException e) {}
try { result.getMaxItem(); fail(); } catch (IllegalArgumentException e) {}
// internal sketch is not null again because getResult() instantiated it
union.union(ItemsSketch.getInstance(Integer.class, Comparator.naturalOrder()));
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getN(), 0);
try { result.getMinItem(); fail(); } catch (IllegalArgumentException e) {}
try { result.getMaxItem(); fail(); } catch (IllegalArgumentException e) {}
union.reset();
// internal sketch is null again
union.union(ItemsSketch.getInstance(Integer.class, Comparator.naturalOrder()));
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getN(), 0);
try { result.getMinItem(); fail(); } catch (IllegalArgumentException e) {}
try { result.getMaxItem(); fail(); } catch (IllegalArgumentException e) {}
}
@Test
public void nullAndEmptyInputsToNonEmptyUnion() {
final ItemsUnion<Integer> union = ItemsUnion.getInstance(Integer.class, 128, Comparator.naturalOrder());
union.update(1);
ItemsSketch<Integer> result = union.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getN(), 1);
Assert.assertEquals(result.getMinItem(), Integer.valueOf(1));
Assert.assertEquals(result.getMaxItem(), Integer.valueOf(1));
union.union((ItemsSketch<Integer>) null);
result = union.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getN(), 1);
Assert.assertEquals(result.getMinItem(), Integer.valueOf(1));
Assert.assertEquals(result.getMaxItem(), Integer.valueOf(1));
union.union(ItemsSketch.getInstance(Integer.class, Comparator.naturalOrder()));
result = union.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getN(), 1);
Assert.assertEquals(result.getMinItem(), Integer.valueOf(1));
Assert.assertEquals(result.getMaxItem(), Integer.valueOf(1));
}
@Test
public void basedOnSketch() {
final Comparator<String> comp = Comparator.naturalOrder();
final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, comp);
ItemsUnion<String> union = ItemsUnion.getInstance(sketch);
union.reset();
final byte[] byteArr = sketch.toByteArray(serDe);
final Memory mem = Memory.wrap(byteArr);
union = ItemsUnion.getInstance(String.class, mem, comp, serDe);
Assert.assertEquals(byteArr.length, 8);
union.reset();
}
@Test
public void sameK() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(Long.class, 128, Comparator.naturalOrder());
ItemsSketch<Long> result = union.getResult();
Assert.assertEquals(result.getN(), 0);
try { result.getMinItem(); fail(); } catch (IllegalArgumentException e) { }
try { result.getMaxItem(); fail(); } catch (IllegalArgumentException e) { }
for (int i = 1; i <= 1000; i++) { union.update((long) i); }
result = union.getResult();
Assert.assertEquals(result.getN(), 1000);
Assert.assertEquals(result.getMinItem(), Long.valueOf(1));
Assert.assertEquals(result.getMaxItem(), Long.valueOf(1000));
Assert.assertEquals(result.getQuantile(0.5), 500, 17); // ~1.7% normalized rank error
final ItemsSketch<Long> sketch1 = ItemsSketch.getInstance(Long.class, Comparator.naturalOrder());
for (int i = 1001; i <= 2000; i++) { sketch1.update((long) i); }
union.union(sketch1);
result = union.getResult();
Assert.assertEquals(result.getN(), 2000);
Assert.assertEquals(result.getMinItem(), Long.valueOf(1));
Assert.assertEquals(result.getMaxItem(), Long.valueOf(2000));
Assert.assertEquals(result.getQuantile(0.5), 1000, 34); // ~1.7% normalized rank error
final ItemsSketch<Long> sketch2 = ItemsSketch.getInstance(Long.class, Comparator.naturalOrder());
for (int i = 2001; i <= 3000; i++) { sketch2.update((long) i); }
final ArrayOfItemsSerDe<Long> serDe = new ArrayOfLongsSerDe();
union.union(Memory.wrap(sketch2.toByteArray(serDe)), serDe);
result = union.getResultAndReset();
Assert.assertNotNull(result);
Assert.assertEquals(result.getN(), 3000);
Assert.assertEquals(result.getMinItem(), Long.valueOf(1));
Assert.assertEquals(result.getMaxItem(), Long.valueOf(3000));
Assert.assertEquals(result.getQuantile(0.5), 1500, 51); // ~1.7% normalized rank error
result = union.getResult();
Assert.assertEquals(result.getN(), 0);
try { result.getMinItem(); fail(); } catch (IllegalArgumentException e) { }
try { result.getMaxItem(); fail(); } catch (IllegalArgumentException e) { }
}
@Test
public void differentK() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(Long.class, 512, Comparator.naturalOrder());
ItemsSketch<Long> result = union.getResult();
Assert.assertEquals(result.getN(), 0);
try { result.getMinItem(); fail(); } catch (IllegalArgumentException e) {}
try { result.getMaxItem(); fail(); } catch (IllegalArgumentException e) {}
for (int i = 1; i <= 10000; i++) { union.update((long) i); }
result = union.getResult();
Assert.assertEquals(result.getK(), 512);
Assert.assertEquals(result.getN(), 10000);
Assert.assertEquals(result.getMinItem(), Long.valueOf(1));
Assert.assertEquals(result.getMaxItem(), Long.valueOf(10000));
Assert.assertEquals(result.getQuantile(0.5), 5000, 50); // ~0.5% normalized rank error
final ItemsSketch<Long> sketch1 = ItemsSketch.getInstance(Long.class, 256, Comparator.naturalOrder());
for (int i = 10001; i <= 20000; i++) { sketch1.update((long) i); }
union.union(sketch1);
result = union.getResult();
Assert.assertEquals(result.getK(), 256);
Assert.assertEquals(result.getN(), 20000);
Assert.assertEquals(result.getMinItem(), Long.valueOf(1));
Assert.assertEquals(result.getMaxItem(), Long.valueOf(20000));
Assert.assertEquals(result.getQuantile(0.5), 10000, 180); // ~0.9% normalized rank error
final ItemsSketch<Long> sketch2 = ItemsSketch.getInstance(Long.class,128, Comparator.naturalOrder());
for (int i = 20001; i <= 30000; i++) { sketch2.update((long) i); }
final ArrayOfItemsSerDe<Long> serDe = new ArrayOfLongsSerDe();
union.union(Memory.wrap(sketch2.toByteArray(serDe)), serDe);
result = union.getResultAndReset();
Assert.assertNotNull(result);
Assert.assertEquals(result.getK(), 128);
Assert.assertEquals(result.getN(), 30000);
Assert.assertEquals(result.getMinItem(), Long.valueOf(1));
Assert.assertEquals(result.getMaxItem(), Long.valueOf(30000));
Assert.assertEquals(result.getQuantile(0.5), 15000, 510); // ~1.7% normalized rank error
result = union.getResult();
Assert.assertEquals(result.getN(), 0);
try { result.getMinItem(); fail(); } catch (IllegalArgumentException e) {}
try { result.getMaxItem(); fail(); } catch (IllegalArgumentException e) {}
}
@Test
public void differentLargerK() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(Long.class, 128, Comparator.naturalOrder());
final ItemsSketch<Long> sketch1 = ItemsSketch.getInstance(Long.class, 256, Comparator.naturalOrder());
union.union(sketch1);
Assert.assertEquals(union.getResult().getK(), 128);
sketch1.update(1L);
union.union(sketch1);
Assert.assertEquals(union.getResult().getK(), 128);
}
@Test
public void differentSmallerK() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(Long.class, 128, Comparator.naturalOrder());
final ItemsSketch<Long> sketch1 = ItemsSketch.getInstance(Long.class, 64, Comparator.naturalOrder());
union.union(sketch1); //union empty, sketch1: empty
Assert.assertEquals(union.getResult().getK(), 128); //union: empty, k=128
sketch1.update(1L); //union: empty, k=128; sketch: valid, k=64
union.union(sketch1);
Assert.assertEquals(union.getResult().getK(), 128);
}
@Test
public void toStringCrudeCheck() {
final ItemsUnion<String> union = ItemsUnion.getInstance(String.class, 128, Comparator.naturalOrder());
union.update("a");
final String brief = union.toString();
final String full = union.toString(true, true);
Assert.assertTrue(brief.length() < full.length());
}
@Test
public void meNullOtherExactBiggerSmaller() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(Long.class, 16, Comparator.naturalOrder()); //me null
ItemsSketch<Long> skExact = buildIS(32, 31); //other is bigger, exact
union.union(skExact);
println(skExact.toString(true, true));
println(union.toString(true, true));
Assert.assertEquals(skExact.getQuantile(0.5), union.getResult().getQuantile(0.5), 0.0);
union.reset();
skExact = buildIS(8, 15); //other is smaller exact,
union.union(skExact);
println(skExact.toString(true, true));
println(union.toString(true, true));
Assert.assertEquals(skExact.getQuantile(0.5), union.getResult().getQuantile(0.5), 0.0);
}
@Test
public void meNullOtherEstBiggerSmaller() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(Long.class, 16, Comparator.naturalOrder()); //me null
ItemsSketch<Long> skEst = buildIS(32, 64); //other is bigger, est
union.union(skEst);
Assert.assertEquals(union.getResult().getMinItem(), skEst.getMinItem(), 0.0);
Assert.assertEquals(union.getResult().getMaxItem(), skEst.getMaxItem(), 0.0);
union.reset();
skEst = buildIS(8, 64); //other is smaller est,
union.union(skEst);
Assert.assertEquals(union.getResult().getMinItem(), skEst.getMinItem(), 0.0);
Assert.assertEquals(union.getResult().getMaxItem(), skEst.getMaxItem(), 0.0);
}
@Test
public void meEmptyOtherExactBiggerSmaller() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(Long.class, 16, Comparator.naturalOrder()); //me null
final ItemsSketch<Long> skEmpty = ItemsSketch.getInstance(Long.class, 64, Comparator.naturalOrder());
union.union(skEmpty); //empty at k = 16
ItemsSketch<Long> skExact = buildIS(32, 63); //bigger, exact
union.union(skExact);
Assert.assertEquals(union.getResult().getMinItem(), skExact.getMinItem(), 0.0);
Assert.assertEquals(union.getResult().getMaxItem(), skExact.getMaxItem(), 0.0);
union.reset();
union.union(skEmpty); //empty at k = 16
skExact = buildIS(8, 15); //smaller, exact
union.union(skExact);
Assert.assertEquals(union.getResult().getMinItem(), skExact.getMinItem(), 0.0);
Assert.assertEquals(union.getResult().getMaxItem(), skExact.getMaxItem(), 0.0);
}
@Test
public void meEmptyOtherEstBiggerSmaller() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(Long.class, 16, Comparator.naturalOrder()); //me null
final ItemsSketch<Long> skEmpty = ItemsSketch.getInstance(Long.class, 64, Comparator.naturalOrder());
union.union(skEmpty); //empty at k = 16
ItemsSketch<Long> skExact = buildIS(32, 64); //bigger, est
union.union(skExact);
Assert.assertEquals(union.getResult().getMinItem(), skExact.getMinItem(), 0.0);
Assert.assertEquals(union.getResult().getMaxItem(), skExact.getMaxItem(), 0.0);
union.reset();
union.union(skEmpty); //empty at k = 16
skExact = buildIS(8, 16); //smaller, est
union.union(skExact);
Assert.assertEquals(union.getResult().getMinItem(), skExact.getMinItem(), 0.0);
Assert.assertEquals(union.getResult().getMaxItem(), skExact.getMaxItem(), 0.0);
}
@Test
public void checkMergeIntoEqualKs() {
final ItemsSketch<Long> skEmpty1 = buildIS(32, 0);
final ItemsSketch<Long> skEmpty2 = buildIS(32, 0);
ItemsMergeImpl.mergeInto(skEmpty1, skEmpty2);
try { skEmpty2.getMinItem(); fail(); } catch (IllegalArgumentException e) {}
try { skEmpty2.getMaxItem(); fail(); } catch (IllegalArgumentException e) {}
ItemsSketch<Long> skValid1, skValid2;
int n = 64;
skValid1 = buildIS(32, n, 0);
skValid2 = buildIS(32, 0, 0); //empty
ItemsMergeImpl.mergeInto(skValid1, skValid2);
Assert.assertEquals(skValid2.getMinItem(), 0.0, 0.0);
Assert.assertEquals(skValid2.getMaxItem(), n - 1.0, 0.0);
skValid1 = buildIS(32, 0, 0); //empty
skValid2 = buildIS(32, n, 0);
ItemsMergeImpl.mergeInto(skValid1, skValid2);
Assert.assertEquals(skValid2.getMinItem(), 0.0, 0.0);
Assert.assertEquals(skValid2.getMaxItem(), n - 1.0, 0.0);
skValid1 = buildIS(32, n, 0);
skValid2 = buildIS(32, n, n);
ItemsMergeImpl.mergeInto(skValid1, skValid2);
Assert.assertEquals(skValid2.getMinItem(), 0.0, 0.0);
Assert.assertEquals(skValid2.getMaxItem(), (2 * n) - 1.0, 0.0);
n = 512;
skValid1 = buildIS(32, n, 0);
skValid2 = buildIS(32, n, n);
ItemsMergeImpl.mergeInto(skValid1, skValid2);
Assert.assertEquals(skValid2.getMinItem(), 0.0, 0.0);
Assert.assertEquals(skValid2.getMaxItem(), (2 * n) - 1.0, 0.0);
skValid1 = buildIS(32, n, 0);
skValid2 = buildIS(32, n, n);
ItemsMergeImpl.mergeInto(skValid2, skValid1);
Assert.assertEquals(skValid1.getMinItem(), 0.0, 0.0);
Assert.assertEquals(skValid1.getMaxItem(), (2 * n) - 1.0, 0.0);
}
@Test
public void checkDownSamplingMergeIntoUnequalKs() {
ItemsSketch<Long> sk1, sk2;
final int n = 128;
sk1 = buildIS(64, n, 0);
sk2 = buildIS(32, n, 128);
ItemsMergeImpl.downSamplingMergeInto(sk1, sk2);
sk1 = buildIS(64, n, 128);
sk2 = buildIS(32, n, 0);
ItemsMergeImpl.downSamplingMergeInto(sk1, sk2);
}
@Test
public void checkToByteArray() {
final int k = 32;
final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
ItemsUnion<Long> union = ItemsUnion.getInstance(Long.class, k, Comparator.naturalOrder());
byte[] bytesOut = union.toByteArray(serDe);
Assert.assertEquals(bytesOut.length, 8);
Assert.assertTrue(union.isEmpty());
final byte[] byteArr = buildIS(k, (2 * k) + 5).toByteArray(serDe);
final Memory mem = Memory.wrap(byteArr);
union = ItemsUnion.getInstance(Long.class, mem, Comparator.naturalOrder(), serDe);
bytesOut = union.toByteArray(serDe);
Assert.assertEquals(bytesOut.length, byteArr.length);
Assert.assertEquals(bytesOut, byteArr); // assumes consistent internal use of toByteArray()
}
private static ItemsSketch<Long> buildIS(final int k, final int n) {
return buildIS(k, n, 0);
}
private static ItemsSketch<Long> buildIS(final int k, final int n, final int startV) {
final ItemsSketch<Long> is = ItemsSketch.getInstance(Long.class, k, Comparator.naturalOrder());
for (long i = 0; i < n; i++) { is.update(i + startV); }
return is;
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param o value to print
*/
static void println(final Object o) {
//System.out.println(o.toString()); //disable here
}
}
| 2,481 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/DoublesSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.nio.ByteOrder;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.WritableHandle;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.quantilescommon.DoublesSortedView;
import org.apache.datasketches.quantilescommon.DoublesSortedViewIterator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DoublesSketchTest {
@Test
public void heapToDirect() {
UpdateDoublesSketch heapSketch = DoublesSketch.builder().build();
for (int i = 0; i < 1000; i++) {
heapSketch.update(i);
}
DoublesSketch directSketch = DoublesSketch.wrap(WritableMemory.writableWrap(heapSketch.toByteArray(false)));
assertEquals(directSketch.getMinItem(), 0.0);
assertEquals(directSketch.getMaxItem(), 999.0);
assertEquals(directSketch.getQuantile(0.5), 500.0, 4.0);
}
@Test
public void directToHeap() {
int sizeBytes = 10000;
UpdateDoublesSketch directSketch = DoublesSketch.builder().build(WritableMemory.writableWrap(new byte[sizeBytes]));
for (int i = 0; i < 1000; i++) {
directSketch.update(i);
}
UpdateDoublesSketch heapSketch;
heapSketch = (UpdateDoublesSketch) DoublesSketch.heapify(WritableMemory.writableWrap(directSketch.toByteArray()));
for (int i = 0; i < 1000; i++) {
heapSketch.update(i + 1000);
}
assertEquals(heapSketch.getMinItem(), 0.0);
assertEquals(heapSketch.getMaxItem(), 1999.0);
assertEquals(heapSketch.getQuantile(0.5), 1000.0, 10.0);
}
@Test
public void checkToByteArray() {
UpdateDoublesSketch ds = DoublesSketch.builder().build(); //k = 128
ds.update(1);
ds.update(2);
byte[] arr = ds.toByteArray(false);
assertEquals(arr.length, ds.getCurrentUpdatableSerializedSizeBytes());
}
/**
* Checks 2 DoublesSketches for equality, triggering an assert if unequal. Handles all
* input sketches and compares only values on valid levels, allowing it to be used to compare
* Update and Compact sketches.
* @param sketch1 input sketch 1
* @param sketch2 input sketch 2
*/
static void testSketchEquality(final DoublesSketch sketch1,
final DoublesSketch sketch2) {
assertEquals(sketch1.getK(), sketch2.getK());
assertEquals(sketch1.getN(), sketch2.getN());
assertEquals(sketch1.getBitPattern(), sketch2.getBitPattern());
assertEquals(sketch1.getMinItem(), sketch2.getMinItem());
assertEquals(sketch1.getMaxItem(), sketch2.getMaxItem());
final DoublesSketchAccessor accessor1 = DoublesSketchAccessor.wrap(sketch1);
final DoublesSketchAccessor accessor2 = DoublesSketchAccessor.wrap(sketch2);
// Compare base buffers. Already confirmed n and k match.
for (int i = 0; i < accessor1.numItems(); ++i) {
assertEquals(accessor1.get(i), accessor2.get(i));
}
// Iterate over levels comparing items
long bitPattern = sketch1.getBitPattern();
for (int lvl = 0; bitPattern != 0; ++lvl, bitPattern >>>= 1) {
if ((bitPattern & 1) > 0) {
accessor1.setLevel(lvl);
accessor2.setLevel(lvl);
for (int i = 0; i < accessor1.numItems(); ++i) {
assertEquals(accessor1.get(i), accessor2.get(i));
}
}
}
}
@Test
public void checkIsSameResource() {
int k = 16;
WritableMemory mem = WritableMemory.writableWrap(new byte[(k*16) +24]);
WritableMemory cmem = WritableMemory.writableWrap(new byte[8]);
DirectUpdateDoublesSketch duds =
(DirectUpdateDoublesSketch) DoublesSketch.builder().setK(k).build(mem);
assertTrue(duds.isSameResource(mem));
DirectCompactDoublesSketch dcds = (DirectCompactDoublesSketch) duds.compact(cmem);
assertTrue(dcds.isSameResource(cmem));
UpdateDoublesSketch uds = DoublesSketch.builder().setK(k).build();
assertFalse(uds.isSameResource(mem));
}
@Test
public void checkEmptyExceptions() {
int k = 16;
UpdateDoublesSketch uds = DoublesSketch.builder().setK(k).build();
try { uds.getMaxItem(); fail(); } catch (IllegalArgumentException e) {}
try { uds.getMinItem(); fail(); } catch (IllegalArgumentException e) {}
try { uds.getRank(1.0); fail(); } catch (IllegalArgumentException e) {}
try { uds.getPartitionBoundaries(5); fail(); } catch (IllegalArgumentException e) {}
try { uds.getPMF(new double[] { 0, 0.5, 1.0 }); fail(); } catch (IllegalArgumentException e) {}
try { uds.getCDF(new double[] { 0, 0.5, 1.0 }); fail(); } catch (IllegalArgumentException e) {}
}
@Test
public void directSketchShouldMoveOntoHeapEventually() {
try (WritableHandle wdh = WritableMemory.allocateDirect(1000,
ByteOrder.nativeOrder(), new DefaultMemoryRequestServer())) {
WritableMemory mem = wdh.getWritable();
UpdateDoublesSketch sketch = DoublesSketch.builder().build(mem);
Assert.assertTrue(sketch.isSameResource(mem));
for (int i = 0; i < 1000; i++) {
sketch.update(i);
}
Assert.assertFalse(sketch.isSameResource(mem));
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void directSketchShouldMoveOntoHeapEventually2() {
int i = 0;
try (WritableHandle wdh =
WritableMemory.allocateDirect(50, ByteOrder.LITTLE_ENDIAN, new DefaultMemoryRequestServer())) {
WritableMemory mem = wdh.getWritable();
UpdateDoublesSketch sketch = DoublesSketch.builder().build(mem);
Assert.assertTrue(sketch.isSameResource(mem));
for (; i < 1000; i++) {
if (sketch.isSameResource(mem)) {
sketch.update(i);
} else {
//println("MOVED OUT at i = " + i);
break;
}
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkEmptyDirect() {
try (WritableHandle wdh = WritableMemory.allocateDirect(1000)) {
WritableMemory mem = wdh.getWritable();
UpdateDoublesSketch sketch = DoublesSketch.builder().build(mem);
sketch.toByteArray(); //exercises a specific path
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void sortedView() {
final UpdateDoublesSketch sketch = DoublesSketch.builder().build();
sketch.update(3);
sketch.update(1);
sketch.update(2);
{ // cumulative inclusive
final DoublesSortedView view = sketch.getSortedView();
final DoublesSortedViewIterator it = view.iterator();
Assert.assertEquals(it.next(), true);
Assert.assertEquals(it.getQuantile(), 1);
Assert.assertEquals(it.getWeight(), 1);
Assert.assertEquals(it.getCumulativeWeight(INCLUSIVE), 1);
Assert.assertEquals(it.next(), true);
Assert.assertEquals(it.getQuantile(), 2);
Assert.assertEquals(it.getWeight(), 1);
Assert.assertEquals(it.getCumulativeWeight(INCLUSIVE), 2);
Assert.assertEquals(it.next(), true);
Assert.assertEquals(it.getQuantile(), 3);
Assert.assertEquals(it.getWeight(), 1);
Assert.assertEquals(it.getCumulativeWeight(INCLUSIVE), 3);
Assert.assertEquals(it.next(), false);
}
}
@Test
public void checkRankLBError() {
final UpdateDoublesSketch sk = DoublesSketch.builder().build();
final double eps = sk.getNormalizedRankError(false);
println("" + (2 * eps));
for (int i = 1; i <= 10000; i++) { sk.update(i); }
double rlb = sk.getRankLowerBound(.5);
println(.5 - rlb);
assertTrue(.5 - rlb <= 2* eps);
}
@Test
public void checkRankUBError() {
final UpdateDoublesSketch sk = DoublesSketch.builder().build();
final double eps = sk.getNormalizedRankError(false);
println(""+ (2 * eps));
for (int i = 1; i <= 10000; i++) { sk.update(i); }
double rub = sk.getRankUpperBound(.5);
println(rub -.5);
assertTrue(rub -.5 <= 2 * eps);
}
@Test
public void checkGetRanks() {
final UpdateDoublesSketch sk = DoublesSketch.builder().build();
for (int i = 1; i <= 10000; i++) { sk.update(i); }
final double[] qArr = {1000,2000,3000,4000,5000,6000,7000,8000,9000,10000};
final double[] ranks = sk.getRanks(qArr, INCLUSIVE);
for (int i = 0; i < qArr.length; i++) {
final double rLB = sk.getRankLowerBound(ranks[i]);
final double rUB = sk.getRankUpperBound(ranks[i]);
assertTrue(rLB <= ranks[i]);
assertTrue(rUB >= ranks[i]);
println(rLB + ", " + ranks[i] + ", " + rUB);
}
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param o value to print
*/
static void println(Object o) {
//System.out.println(o.toString()); //disable here
}
}
| 2,482 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/AccuracyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import java.util.Random;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class AccuracyTest {
static Random rand = new Random(1);
@Test
public void baseTest() {
int n = 1 << 20;
int k = 1 << 5;
double[] seqArr = new double[n];
//build sequential array
for (int i = 1; i <= n; i++) {
seqArr[i - 1] = i;
}
double[] randArr = seqArr.clone();
shuffle(randArr);
UpdateDoublesSketch sketch = DoublesSketch.builder().setK(k).build();
for (int i = 0; i < n; i++) {
sketch.update(randArr[i]);
}
double[] ranks = sketch.getCDF(seqArr);
double maxDelta = 0;
for (int i = 0; i < n; i++) {
double actRank = (double)i/n;
double estRank = ranks[i];
double delta = actRank - estRank;
maxDelta = Math.max(maxDelta, delta);
//println("Act: " + + " \tEst: " + ranks[i]);
}
println("Max delta: " + maxDelta);
println(sketch.toString());
}
public static void shuffle(double[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int j = i + rand.nextInt(n - i);
swap(arr, i, j);
}
}
public static void swap(double[] arr, int i, int j) {
double t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
//@Test
public void getEpsilon() {
for (int lgK = 4; lgK < 15; lgK++) {
int k = 1 << lgK;
double eps = ClassicUtil.getNormalizedRankError(k, false);
println(k + "\t" + eps);
}
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,483 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/ItemsSketchIteratorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import java.util.Comparator;
import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIterator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ItemsSketchIteratorTest {
@Test
public void emptySketch() {
ItemsSketch<Integer> sketch = ItemsSketch.getInstance(Integer.class, 128, Comparator.naturalOrder());
QuantilesGenericSketchIterator<Integer> it = sketch.iterator();
Assert.assertFalse(it.next());
}
@Test
public void oneItemSketch() {
ItemsSketch<Integer> sketch = ItemsSketch.getInstance(Integer.class, 128, Comparator.naturalOrder());
sketch.update(0);
QuantilesGenericSketchIterator<Integer> it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getQuantile(), Integer.valueOf(0));
Assert.assertEquals(it.getWeight(), 1);
Assert.assertFalse(it.next());
}
@Test
public void bigSketches() {
for (int n = 1000; n < 100000; n += 2000) {
ItemsSketch<Integer> sketch = ItemsSketch.getInstance(Integer.class, 128, Comparator.naturalOrder());
for (int i = 0; i < n; i++) {
sketch.update(i);
}
QuantilesGenericSketchIterator<Integer> it = sketch.iterator();
int count = 0;
int weight = 0;
while (it.next()) {
count++;
weight += (int)it.getWeight();
}
Assert.assertEquals(count, sketch.getNumRetained());
Assert.assertEquals(weight, n);
}
}
}
| 2,484 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/UtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.quantiles.ClassicUtil.MIN_K;
import static org.apache.datasketches.quantiles.ClassicUtil.checkPreLongsFlagsCap;
import static org.apache.datasketches.quantiles.ClassicUtil.computeCombinedBufferItemCapacity;
import static org.apache.datasketches.quantiles.ClassicUtil.computeValidLevels;
import static org.apache.datasketches.quantiles.ClassicUtil.hiBitPos;
import static org.apache.datasketches.quantiles.ClassicUtil.lowestZeroBitStartingAt;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Arrays;
import org.apache.datasketches.common.SketchesArgumentException;
import org.testng.annotations.Test;
public class UtilTest {
@Test
public void checkCombBufItemCapacity() {
int k = 227;
int capEl = computeCombinedBufferItemCapacity(k, 0);
assertEquals(capEl, 2 * MIN_K);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkThePreLongsFlagsCap() {
checkPreLongsFlagsCap(2, 0, 15L);
}
@Test
public void checkHiBitPos() {
int bitPos = hiBitPos(4096);
assertEquals(bitPos, 12);
}
@Test
public void checkNumValidLevels() {
long v = (1L << 32)-1L;
int ones = computeValidLevels(v);
assertEquals(ones, 32);
}
@Test
public void testPositionOfLowestZeroBitStartingAt() {
int [] answers = {9, 8, 7, 7, 7, 4, 4, 4, 1, 1};
long v = 109L;
//println("IN: " + Long.toBinaryString(v));
for (int i = 0, j = 9; i < 10; i++, j--) {
int result = lowestZeroBitStartingAt(v, i);
//System.out.printf ("%d %d %d%n", i, result, answers[j]);
assertTrue (answers[j] == result);
}
}
@Test
public void testPositionOfLowestZeroBitStartingAt2() {
long bits = -1L;
int startingBit = 70; //only low 6 bits are used
int result = lowestZeroBitStartingAt(bits, startingBit);
assertEquals(result, 64);
}
//The remainder of this file is a brute force test of corner cases
// for blockyTandemMergeSort.
private static void assertMergeTestPrecondition(double [] arr, long [] brr, int arrLen, int blkSize) {
int violationsCount = 0;
for (int i = 0; i < (arrLen-1); i++) {
if (((i+1) % blkSize) == 0) {
continue;
}
if (arr[i] > arr[i+1]) { violationsCount++; }
}
for (int i = 0; i < arrLen; i++) {
if (brr[i] != (long) (1e12 * (1.0 - arr[i]))) {
violationsCount++;
}
}
if (brr[arrLen] != 0) { violationsCount++; }
assertEquals(violationsCount, 0);
}
private static void assertMergeTestPostcondition(double [] arr, long [] brr, int arrLen) {
int violationsCount = 0;
for (int i = 0; i < (arrLen-1); i++) {
if (arr[i] > arr[i+1]) { violationsCount++; }
}
for (int i = 0; i < arrLen; i++) {
if (brr[i] != (long) (1e12 * (1.0 - arr[i]))) {
violationsCount++;
}
}
if (brr[arrLen] != 0) { violationsCount++; }
assertEquals(violationsCount, 0);
}
private static double[] makeMergeTestInput(int arrLen, int blkSize) {
double[] arr = new double[arrLen];
double pick = Math.random ();
for (int i = 0; i < arrLen; i++) {
if (pick < 0.01) { // every value the same
arr[i] = 0.3;
}
else if (pick < 0.02) { // ascending values
int j = i+1;
int denom = arrLen+1;
arr[i] = ((double) j) / ((double) denom);
}
else if (pick < 0.03) { // descending values
int j = i+1;
int denom = arrLen+1;
arr[i] = 1.0 - (((double) j) / ((double) denom));
}
else { // random values
arr[i] = Math.random ();
}
}
for (int start = 0; start < arrLen; start += blkSize) {
Arrays.sort (arr, start, Math.min (arrLen, start + blkSize));
}
return arr;
}
private static long [] makeTheTandemArray(double [] arr) {
long [] brr = new long [arr.length + 1]; /* make it one longer, just like in the sketches */
for (int i = 0; i < arr.length; i++) {
brr[i] = (long) (1e12 * (1.0 - arr[i])); /* it's a better test with the order reversed */
}
brr[arr.length] = 0;
return brr;
}
@Test
public void checkBlockyTandemMergeSort() {
testBlockyTandemMergeSort(10, 50);
}
/**
*
* @param numTries number of tries
* @param maxArrLen maximum length of array size
*/
private static void testBlockyTandemMergeSort(int numTries, int maxArrLen) {
int arrLen = 0;
double[] arr = null;
for (arrLen = 0; arrLen <= maxArrLen; arrLen++) {
for (int blkSize = 1; blkSize <= (arrLen + 100); blkSize++) {
for (int tryno = 1; tryno <= numTries; tryno++) {
arr = makeMergeTestInput(arrLen, blkSize);
long [] brr = makeTheTandemArray(arr);
assertMergeTestPrecondition(arr, brr, arrLen, blkSize);
DoublesSketchSortedView.blockyTandemMergeSort(arr, brr, arrLen, blkSize);
/* verify sorted order */
for (int i = 0; i < (arrLen-1); i++) {
assert arr[i] <= arr[i+1];
}
assertMergeTestPostcondition(arr, brr, arrLen);
}
}
}
//System.out.printf ("Passed: testBlockyTandemMergeSort%n");
}
// we are retaining this stand-alone test because it can be more exhaustive
// @SuppressWarnings("unused")
// private static void exhaustiveMain(String[] args) {
// assert (args.length == 2);
// int numTries = Integer.parseInt(args[0]);
// int maxArrLen = Integer.parseInt(args[1]);
// System.out.printf("Testing blockyTandemMergeSort%n");
// for (int arrLen = 0; arrLen < maxArrLen; arrLen++) {
// for (int blkSize = 1; blkSize <= arrLen + 100; blkSize++) {
// System.out.printf (
// "Testing %d times with arrLen = %d and blkSize = %d%n", numTries, arrLen, blkSize);
// for (int tryno = 1; tryno <= numTries; tryno++) {
// double[] arr = makeMergeTestInput(arrLen, blkSize);
// long[] brr = makeTheTandemArray(arr);
// assertMergeTestPrecondition(arr, brr, arrLen, blkSize);
// DoublesAuxiliary.blockyTandemMergeSort(arr, brr, arrLen, blkSize);
// assertMergeTestPostcondition(arr, brr, arrLen);
// }
// }
// }
// }
//
// public static void main(String[] args) {
// exhaustiveMain(new String[] {"10", "100"});
// }
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,485 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/DoublesUnionBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import org.testng.annotations.Test;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
public class DoublesUnionBuilderTest {
@Test
public void checkBuilds() {
UpdateDoublesSketch qs1 = DoublesSketch.builder().build();
for (int i=0; i<1000; i++) { qs1.update(i); }
int bytes = qs1.getCurrentCompactSerializedSizeBytes();
WritableMemory dstMem = WritableMemory.writableWrap(new byte[bytes]);
qs1.putMemory(dstMem);
Memory srcMem = dstMem;
DoublesUnionBuilder bldr = new DoublesUnionBuilder();
bldr.setMaxK(128);
DoublesUnion union = bldr.build(); //virgin union
union = DoublesUnion.heapify(srcMem);
DoublesSketch qs2 = union.getResult();
assertEquals(qs1.getCurrentCompactSerializedSizeBytes(), qs2.getCurrentCompactSerializedSizeBytes());
union = DoublesUnion.heapify(qs2);
DoublesSketch qs3 = union.getResult();
assertEquals(qs2.getCurrentCompactSerializedSizeBytes(), qs3.getCurrentCompactSerializedSizeBytes());
assertFalse(qs2 == qs3);
}
@Test
public void checkDeprecated1() {
UpdateDoublesSketch qs1 = DoublesSketch.builder().build();
for (int i=0; i<1000; i++) {
qs1.update(i);
}
int bytes = qs1.getCurrentCompactSerializedSizeBytes();
WritableMemory dstMem = WritableMemory.writableWrap(new byte[bytes]);
qs1.putMemory(dstMem);
Memory srcMem = dstMem;
DoublesUnionBuilder bldr = new DoublesUnionBuilder();
bldr.setMaxK(128);
DoublesUnion union = bldr.build(); //virgin union
union = DoublesUnion.heapify(srcMem); //heapify
DoublesSketch qs2 = union.getResult();
assertEquals(qs1.getCurrentCompactSerializedSizeBytes(), qs2.getCurrentCompactSerializedSizeBytes());
assertEquals(qs1.getCurrentUpdatableSerializedSizeBytes(), qs2.getCurrentUpdatableSerializedSizeBytes());
union = DoublesUnion.heapify(qs2); //heapify again
DoublesSketch qs3 = union.getResult();
assertEquals(qs2.getCurrentCompactSerializedSizeBytes(), qs3.getCurrentCompactSerializedSizeBytes());
assertEquals(qs2.getCurrentUpdatableSerializedSizeBytes(), qs3.getCurrentUpdatableSerializedSizeBytes());
assertFalse(qs2 == qs3); //different objects
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.err.println(s); //disable here
}
}
| 2,486 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/DoublesSketchBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
import org.apache.datasketches.memory.WritableMemory;
public class DoublesSketchBuilderTest {
@Test
public void checkBuilder() {
int k = 256; //default is 128
DoublesSketchBuilder bldr = DoublesSketch.builder();
bldr.setK(k);
assertEquals(bldr.getK(), k); //confirms new k
println(bldr.toString());
int bytes = DoublesSketch.getUpdatableStorageBytes(k, 0);
byte[] byteArr = new byte[bytes];
WritableMemory mem = WritableMemory.writableWrap(byteArr);
DoublesSketch ds = bldr.build(mem);
assertTrue(ds.hasMemory());
assertFalse(ds.isDirect());
println(bldr.toString());
bldr = DoublesSketch.builder();
assertEquals(bldr.getK(), PreambleUtil.DEFAULT_K);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,487 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/HeapUpdateDoublesSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static java.lang.Math.floor;
import static org.apache.datasketches.common.Util.log2;
import static org.apache.datasketches.quantiles.ClassicUtil.LS;
import static org.apache.datasketches.quantiles.ClassicUtil.computeCombinedBufferItemCapacity;
import static org.apache.datasketches.quantiles.ClassicUtil.computeNumLevelsNeeded;
import static org.apache.datasketches.quantiles.HeapUpdateDoublesSketch.checkPreLongsFlagsSerVer;
import static org.apache.datasketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK;
import static org.apache.datasketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE;
import static org.apache.datasketches.quantilescommon.QuantilesUtil.equallyWeightedRanks;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.nio.ByteOrder;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.quantilescommon.QuantilesUtil;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class HeapUpdateDoublesSketchTest {
@BeforeMethod
public void setUp() {
DoublesSketch.rand.setSeed(32749); // make sketches deterministic for testing
}
// Please note that this is a randomized test that could probabilistically fail
// if we didn't set the seed. (The probability of failure could be reduced by increasing k.)
// Setting the seed has now made it deterministic.
@Test
public void checkEndToEnd() {
int k = 256;
UpdateDoublesSketch qs = DoublesSketch.builder().setK(k).build();
UpdateDoublesSketch qs2 = DoublesSketch.builder().setK(k).build();
int n = 1000000;
for (int item = n; item >= 1; item--) {
if ((item % 4) == 0) {
qs.update(item);
}
else {
qs2.update(item);
}
}
assertEquals(qs.getN() + qs2.getN(), n);
DoublesUnion union = DoublesUnion.heapify(qs);
union.union(qs2);
DoublesSketch result = union.getResult();
int numPhiValues = 99;
double[] phiArr = new double[numPhiValues];
for (int q = 1; q <= 99; q++) {
phiArr[q-1] = q / 100.0;
}
double[] splitPoints = result.getQuantiles(phiArr);
// for (int i = 0; i < 99; i++) {
// String s = String.format("%d\t%.6f\t%.6f", i, phiArr[i], splitPoints[i]);
// println(s);
// }
for (int q = 1; q <= 99; q++) {
double nominal = (1e6 * q) / 100.0;
double reported = splitPoints[q-1];
assertTrue(reported >= (nominal - 10000.0));
assertTrue(reported <= (nominal + 10000.0));
}
double[] pmfResult = result.getPMF(splitPoints);
double subtotal = 0.0;
for (int q = 1; q <= 100; q++) {
double phi = q / 100.0;
subtotal += pmfResult[q-1];
assertTrue(subtotal >= (phi - 0.01));
assertTrue(subtotal <= (phi + 0.01));
}
double[] cdfResult = result.getCDF(splitPoints);
for (int q = 1; q <= 100; q++) {
double phi = q / 100.0;
subtotal = cdfResult[q-1];
assertTrue(subtotal >= (phi - 0.01));
assertTrue(subtotal <= (phi + 0.01));
}
assertEquals(result.getRank(500000), 0.5, 0.01);
}
@Test
public void checkSmallMinMax () {
int k = 32;
int n = 8;
UpdateDoublesSketch qs1 = DoublesSketch.builder().setK(k).build();
UpdateDoublesSketch qs2 = DoublesSketch.builder().setK(k).build();
UpdateDoublesSketch qs3 = DoublesSketch.builder().setK(k).build();
for (int i = n; i >= 1; i--) {
qs1.update(i);
qs2.update(10+i);
qs3.update(i);
}
assertEquals(qs1.getQuantile (0.0, EXCLUSIVE), 1.0);
assertEquals(qs1.getQuantile (0.5, EXCLUSIVE), 5.0);
assertEquals(qs1.getQuantile (1.0, EXCLUSIVE), 8.0);
assertEquals(qs2.getQuantile (0.0, EXCLUSIVE), 11.0);
assertEquals(qs2.getQuantile (0.5, EXCLUSIVE), 15.0);
assertEquals(qs2.getQuantile (1.0, EXCLUSIVE), 18.0);
assertEquals(qs3.getQuantile (0.0, EXCLUSIVE), 1.0);
assertEquals(qs3.getQuantile (0.5, EXCLUSIVE), 5.0);
assertEquals(qs3.getQuantile (1.0, EXCLUSIVE), 8.0);
double[] queries = {0.0, 0.5, 1.0};
double[] resultsA = qs1.getQuantiles(queries, EXCLUSIVE);
assertEquals(resultsA[0], 1.0);
assertEquals(resultsA[1], 5.0);
assertEquals(resultsA[2], 8.0);
DoublesUnion union1 = DoublesUnion.heapify(qs1);
union1.union(qs2);
DoublesSketch result1 = union1.getResult();
DoublesUnion union2 = DoublesUnion.heapify(qs2);
union2.union(qs3);
DoublesSketch result2 = union2.getResult();
double[] resultsB = result1.getQuantiles(queries, EXCLUSIVE);
assertEquals(resultsB[0], 1.0);
assertEquals(resultsB[1], 11.0);
assertEquals(resultsB[2], 18.0);
double[] resultsC = result2.getQuantiles(queries, EXCLUSIVE);
assertEquals(resultsC[0], 1.0);
assertEquals(resultsC[1], 11.0);
assertEquals(resultsC[2], 18.0);
}
@Test
public void checkMisc() {
int k = PreambleUtil.DEFAULT_K;
int n = 10000;
UpdateDoublesSketch qs = buildAndLoadQS(k, n);
qs.update(Double.NaN); //ignore
int n2 = (int)qs.getN();
assertEquals(n2, n);
qs.reset();
assertEquals(qs.getN(), 0);
}
@SuppressWarnings("unused")
@Test
public void checkToStringDetail() {
int k = PreambleUtil.DEFAULT_K;
int n = 1000000;
UpdateDoublesSketch qs = buildAndLoadQS(k, 0);
String s = qs.toString();
s = qs.toString(false, true);
//println(s);
qs = buildAndLoadQS(k, n);
s = qs.toString();
//println(s);
s = qs.toString(false, true);
//println(qs.toString(false, true));
int n2 = (int)qs.getN();
assertEquals(n2, n);
qs.update(Double.NaN); //ignore
qs.reset();
assertEquals(qs.getN(), 0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkConstructorException() {
DoublesSketch.builder().setK(0).build();
}
@Test
public void checkPreLongsFlagsAndSize() {
byte[] byteArr;
UpdateDoublesSketch ds = DoublesSketch.builder().build(); //k = 128
//empty
byteArr = ds.toByteArray(true); // compact
assertEquals(byteArr.length, 8);
byteArr = ds.toByteArray(false); // not compact
assertEquals(byteArr.length, 8);
assertEquals(byteArr[3], EMPTY_FLAG_MASK);
//not empty
ds.update(1);
byteArr = ds.toByteArray(true); // compact
assertEquals(byteArr.length, 40); //compact, 1 value
byteArr = ds.toByteArray(false); // not compact
assertEquals(byteArr.length, 64); // 32 + MIN_K(=2) * 2 * 8 = 64
}
@Test
public void checkPreLongsFlagsSerVerB() {
checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK, 1, 1); //38
checkPreLongsFlagsSerVer(0, 1, 5); //164
checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK, 2, 1); //42
checkPreLongsFlagsSerVer(0, 2, 2); //72
checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK | COMPACT_FLAG_MASK, 3, 1); //47
checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK | COMPACT_FLAG_MASK, 3, 2); //79
checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK, 3, 2); //78
checkPreLongsFlagsSerVer(COMPACT_FLAG_MASK, 3, 2);//77
checkPreLongsFlagsSerVer(0, 3, 2); //76
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkPreLongsFlagsSerVer3() {
checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK, 1, 2);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkGetQuantiles() {
int k = PreambleUtil.DEFAULT_K;
int n = 1000000;
DoublesSketch qs = buildAndLoadQS(k, n);
double[] frac = {-0.5};
qs.getQuantiles(frac);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkGetQuantile() {
int k = PreambleUtil.DEFAULT_K;
int n = 1000000;
DoublesSketch qs = buildAndLoadQS(k, n);
double frac = -0.5; //negative not allowed
qs.getQuantile(frac);
}
//@Test //visual only
public void summaryCheckViaMemory() {
DoublesSketch qs = buildAndLoadQS(256, 1000000);
String s = qs.toString();
println(s);
println("");
Memory srcMem = WritableMemory.writableWrap(qs.toByteArray());
HeapUpdateDoublesSketch qs2 = HeapUpdateDoublesSketch.heapifyInstance(srcMem);
s = qs2.toString();
println(s);
}
@Test
public void checkComputeNumLevelsNeeded() {
int n = 1 << 20;
int k = PreambleUtil.DEFAULT_K;
int lvls1 = computeNumLevelsNeeded(k, n);
int lvls2 = (int)Math.max(floor(log2((double)n/k)),0);
assertEquals(lvls1, lvls2);
}
@Test
public void checkComputeBitPattern() {
int n = 1 << 20;
int k = PreambleUtil.DEFAULT_K;
long bitP = ClassicUtil.computeBitPattern(k, n);
assertEquals(bitP, n/(2L*k));
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkValidateSplitPointsOrder() {
double[] arr = {2, 1};
QuantilesUtil.checkDoublesSplitPointsOrder(arr);
}
@Test
public void checkGetStorageBytes() {
int k = PreambleUtil.DEFAULT_K; //128
DoublesSketch qs = buildAndLoadQS(k, 0); //k, n
int stor = qs.getCurrentCompactSerializedSizeBytes();
assertEquals(stor, 8);
qs = buildAndLoadQS(k, 2*k); //forces one level
stor = qs.getCurrentCompactSerializedSizeBytes();
int retItems = ClassicUtil.computeRetainedItems(k, 2*k);
assertEquals(stor, 32 + (retItems << 3));
qs = buildAndLoadQS(k, (2*k)-1); //just Base Buffer
stor = qs.getCurrentCompactSerializedSizeBytes();
retItems = ClassicUtil.computeRetainedItems(k, (2*k)-1);
assertEquals(stor, 32 + (retItems << 3));
}
@Test
public void checkGetStorageBytes2() {
int k = PreambleUtil.DEFAULT_K;
long v = 1;
UpdateDoublesSketch qs = DoublesSketch.builder().setK(k).build();
for (int i = 0; i< 1000; i++) {
qs.update(v++);
// for (int j = 0; j < 1000; j++) {
// qs.update(v++);
// }
byte[] byteArr = qs.toByteArray(false);
assertEquals(byteArr.length, qs.getCurrentUpdatableSerializedSizeBytes());
}
}
@Test
public void checkMerge() {
int k = PreambleUtil.DEFAULT_K;
int n = 1000000;
DoublesSketch qs1 = buildAndLoadQS(k,n,0);
DoublesSketch qs2 = buildAndLoadQS(k,0,0); //empty
DoublesUnion union = DoublesUnion.heapify(qs2);
union.union(qs1);
DoublesSketch result = union.getResult();
double med1 = qs1.getQuantile(0.5);
double med2 = result.getQuantile(0.5);
assertEquals(med1, med2, 0.0);
//println(med1+","+med2);
}
@Test
public void checkReverseMerge() {
int k = PreambleUtil.DEFAULT_K;
DoublesSketch qs1 = buildAndLoadQS(k, 1000, 0);
DoublesSketch qs2 = buildAndLoadQS(2*k,1000, 1000);
DoublesUnion union = DoublesUnion.heapify(qs2);
union.union(qs1); //attempt merge into larger k
DoublesSketch result = union.getResult();
assertEquals(result.getK(), k);
}
@Test
public void checkInternalBuildHistogram() {
int k = PreambleUtil.DEFAULT_K;
int n = 1000000;
DoublesSketch qs = buildAndLoadQS(k,n,0);
double eps = qs.getNormalizedRankError(true);
//println("EPS:"+eps);
double[] spts = {100000, 500000, 900000};
double[] fracArr = qs.getPMF(spts);
// println(fracArr[0]+", "+ (fracArr[0]-0.1));
// println(fracArr[1]+", "+ (fracArr[1]-0.4));
// println(fracArr[2]+", "+ (fracArr[2]-0.4));
// println(fracArr[3]+", "+ (fracArr[3]-0.1));
assertEquals(fracArr[0], .1, eps);
assertEquals(fracArr[1], .4, eps);
assertEquals(fracArr[2], .4, eps);
assertEquals(fracArr[3], .1, eps);
}
@Test
public void checkComputeBaseBufferCount() {
int n = 1 << 20;
int k = PreambleUtil.DEFAULT_K;
long bbCnt = ClassicUtil.computeBaseBufferItems(k, n);
assertEquals(bbCnt, n % (2L*k));
}
@Test
public void checkToFromByteArray() {
checkToFromByteArray2(128, 1300); //generates a pattern of 5 -> 101
checkToFromByteArray2(4, 7);
checkToFromByteArray2(4, 8);
checkToFromByteArray2(4, 9);
}
private static void checkToFromByteArray2(int k, int n) {
DoublesSketch qs = buildAndLoadQS(k, n);
byte[] byteArr;
Memory mem;
DoublesSketch qs2;
// from compact
byteArr = qs.toByteArray(true);
mem = Memory.wrap(byteArr);
qs2 = UpdateDoublesSketch.heapify(mem);
for (double f = 0.1; f < 0.95; f += 0.1) {
assertEquals(qs.getQuantile(f), qs2.getQuantile(f), 0.0);
}
// ordered, non-compact
byteArr = qs.toByteArray(false);
mem = Memory.wrap(byteArr);
qs2 = DoublesSketch.heapify(mem);
final DoublesSketchAccessor dsa = DoublesSketchAccessor.wrap(qs2);
dsa.sort();
for (double f = 0.1; f < 0.95; f += 0.1) {
assertEquals(qs.getQuantile(f), qs2.getQuantile(f), 0.0);
}
// not ordered, not compact
byteArr = qs.toByteArray(false);
mem = Memory.wrap(byteArr);
qs2 = DoublesSketch.heapify(mem);
for (double f = 0.1; f < 0.95; f += 0.1) {
assertEquals(qs.getQuantile(f), qs2.getQuantile(f), 0.0);
}
}
@Test
public void checkEmpty() {
int k = PreambleUtil.DEFAULT_K;
DoublesSketch qs1 = buildAndLoadQS(k, 0);
byte[] byteArr = qs1.toByteArray();
Memory mem = Memory.wrap(byteArr);
DoublesSketch qs2 = DoublesSketch.heapify(mem);
assertTrue(qs2.isEmpty());
final int expectedSizeBytes = 8; //COMBINED_BUFFER + ((2 * MIN_K) << 3);
assertEquals(byteArr.length, expectedSizeBytes);
try { qs2.getQuantile(0.5); fail(); } catch (IllegalArgumentException e) { }
try { qs2.getQuantiles(new double[] {0.0, 0.5, 1.0}); fail(); } catch (IllegalArgumentException e) { }
try { qs2.getRank(0); fail(); } catch (IllegalArgumentException e) { }
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMemTooSmall1() {
Memory mem = Memory.wrap(new byte[7]);
HeapUpdateDoublesSketch.heapifyInstance(mem);
fail();
//qs2.getQuantile(0.5);
}
//Corruption tests
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkSerVer() {
DoublesUtil.checkDoublesSerVer(0, HeapUpdateDoublesSketch.MIN_HEAP_DOUBLES_SER_VER);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkFamilyID() {
ClassicUtil.checkFamilyID(3);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMemCapacityException() {
int k = PreambleUtil.DEFAULT_K;
long n = 1000;
int serVer = 3;
int combBufItemCap = computeCombinedBufferItemCapacity(k, n);
int memCapBytes = (combBufItemCap + 4) << 3;
int badCapBytes = memCapBytes - 1; //corrupt
HeapUpdateDoublesSketch.checkHeapMemCapacity(k, n, false, serVer, badCapBytes);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBufAllocAndCap() {
int k = PreambleUtil.DEFAULT_K;
long n = 1000;
int serVer = 3;
int combBufItemCap = computeCombinedBufferItemCapacity(k, n); //non-compact cap
int memCapBytes = (combBufItemCap + 4) << 3;
int memCapBytesV1 = (combBufItemCap + 5) << 3;
HeapUpdateDoublesSketch.checkHeapMemCapacity(k, n, false, 1, memCapBytesV1);
HeapUpdateDoublesSketch.checkHeapMemCapacity(k, n, false, serVer, memCapBytes - 1); //corrupt
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkPreLongsFlagsCap() {
int preLongs = 5;
int flags = EMPTY_FLAG_MASK;
int memCap = 8;
ClassicUtil.checkPreLongsFlagsCap(preLongs, flags, memCap); //corrupt
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkPreLongsFlagsCap2() {
int preLongs = 5;
int flags = 0;
int memCap = 8;
ClassicUtil.checkPreLongsFlagsCap(preLongs, flags, memCap); //corrupt
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkFlags() {
int flags = 1;
ClassicUtil.checkHeapFlags(flags);
}
@Test
public void checkZeroPatternReturn() {
int k = PreambleUtil.DEFAULT_K;
DoublesSketch qs1 = buildAndLoadQS(k, 64);
byte[] byteArr = qs1.toByteArray();
Memory mem = Memory.wrap(byteArr);
HeapUpdateDoublesSketch.heapifyInstance(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadDownSamplingRatio() {
int k1 = 64;
DoublesSketch qs1 = buildAndLoadQS(k1, k1);
qs1.downSample(qs1, 2*k1, null);//should be smaller
}
@Test
public void checkImproperKvalues() {
checksForImproperK(0);
checksForImproperK(1<<16);
}
//Primarily visual only tests
static void testDownSampling(int bigK, int smallK) {
HeapUpdateDoublesSketch sketch1 = HeapUpdateDoublesSketch.newInstance(bigK);
HeapUpdateDoublesSketch sketch2 = HeapUpdateDoublesSketch.newInstance(smallK);
for (int i = 127; i >= 1; i--) {
sketch1.update (i);
sketch2.update (i);
}
HeapUpdateDoublesSketch downSketch =
(HeapUpdateDoublesSketch)sketch1.downSample(sketch1, smallK, null);
println (LS+"Sk1"+LS);
String s1, s2, down;
s1 = sketch1.toString(true, true);
println(s1);
println (LS+"Down"+LS);
down = downSketch.toString(true, true);
println(down);
println(LS+"Sk2"+LS);
s2 = sketch2.toString(true, true);
println(s2);
assertEquals(downSketch.getNumRetained(), sketch2.getNumRetained());
}
@Test
public void checkDownSampling() {
testDownSampling(4,4); //no down sampling
testDownSampling(16,4);
//testDownSampling(12,3);
}
@Test
public void testDownSampling2() {
HeapUpdateDoublesSketch sketch1 = HeapUpdateDoublesSketch.newInstance(8);
HeapUpdateDoublesSketch sketch2 = HeapUpdateDoublesSketch.newInstance(2);
DoublesSketch downSketch;
downSketch = sketch1.downSample(sketch1, 2, null);
assertTrue(sameStructurePredicate(sketch2, downSketch));
for (int i = 0; i < 50; i++) {
sketch1.update (i);
sketch2.update (i);
downSketch = sketch1.downSample(sketch1, 2, null);
assertTrue (sameStructurePredicate(sketch2, downSketch));
}
}
@Test
public void testDownSampling3() {
int k1 = 8;
int k2 = 2;
int n = 50;
UpdateDoublesSketch sketch1 = DoublesSketch.builder().setK(k1).build();
UpdateDoublesSketch sketch2 = DoublesSketch.builder().setK(k2).build();
DoublesSketch downSketch;
for (int i = 0; i < n; i++) {
sketch1.update (i);
sketch2.update (i);
downSketch = sketch1.downSample(sketch1, k2, null);
assertTrue (sameStructurePredicate(sketch2, downSketch));
}
}
@Test //
public void testDownSampling3withMem() {
int k1 = 8;
int k2 = 2;
int n = 50;
UpdateDoublesSketch sketch1 = DoublesSketch.builder().setK(k1).build();
UpdateDoublesSketch sketch2 = DoublesSketch.builder().setK(k2).build();
DoublesSketch downSketch;
int bytes = DoublesSketch.getUpdatableStorageBytes(k2, n);
WritableMemory mem = WritableMemory.writableWrap(new byte[bytes]);
for (int i = 0; i < n; i++) {
sketch1.update (i);
sketch2.update (i);
downSketch = sketch1.downSample(sketch1, k2, mem);
assertTrue (sameStructurePredicate(sketch2, downSketch));
}
}
@Test
public void testDownSampling4() {
for (int n1 = 0; n1 < 50; n1++ ) {
HeapUpdateDoublesSketch bigSketch = HeapUpdateDoublesSketch.newInstance(8);
for (int i1 = 1; i1 <= n1; i1++ ) {
bigSketch.update(i1);
}
for (int n2 = 0; n2 < 50; n2++ ) {
HeapUpdateDoublesSketch directSketch = HeapUpdateDoublesSketch.newInstance(2);
for (int i1 = 1; i1 <= n1; i1++ ) {
directSketch.update(i1);
}
for (int i2 = 1; i2 <= n2; i2++ ) {
directSketch.update(i2);
}
HeapUpdateDoublesSketch smlSketch = HeapUpdateDoublesSketch.newInstance(2);
for (int i2 = 1; i2 <= n2; i2++ ) {
smlSketch.update(i2);
}
DoublesMergeImpl.downSamplingMergeInto(bigSketch, smlSketch);
assertTrue (sameStructurePredicate(directSketch, smlSketch));
}
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void testDownSamplingExceptions1() {
UpdateDoublesSketch qs1 = DoublesSketch.builder().setK(4).build(); // not smaller
DoublesSketch qs2 = DoublesSketch.builder().setK(3).build();
DoublesMergeImpl.mergeInto(qs2, qs1);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void testDownSamplingExceptions2() {
UpdateDoublesSketch qs1 = DoublesSketch.builder().setK(4).build();
DoublesSketch qs2 = DoublesSketch.builder().setK(7).build(); // 7/4 not pwr of 2
DoublesMergeImpl.mergeInto(qs2, qs1);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void testDownSamplingExceptions3() {
UpdateDoublesSketch qs1 = DoublesSketch.builder().setK(4).build();
DoublesSketch qs2 = DoublesSketch.builder().setK(12).build(); // 12/4 not pwr of 2
DoublesMergeImpl.mergeInto(qs2, qs1);
}
//@Test //visual only
public void quantilesCheckViaMemory() {
int k = 256;
int n = 1000000;
DoublesSketch qs = buildAndLoadQS(k, n);
double[] ranks = {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0};
String s = getRanksTable(qs, ranks);
println(s);
println("");
Memory srcMem = Memory.wrap(qs.toByteArray());
HeapUpdateDoublesSketch qs2 = HeapUpdateDoublesSketch.heapifyInstance(srcMem);
println(getRanksTable(qs2, ranks));
}
static String getRanksTable(DoublesSketch qs, double[] ranks) {
double rankError = qs.getNormalizedRankError(false);
double[] values = qs.getQuantiles(ranks);
double maxV = qs.getMaxItem();
double minV = qs.getMinItem();
double delta = maxV - minV;
println("Note: This prints the relative value errors for illustration.");
println("The quantiles sketch does not and can not guarantee relative value errors");
StringBuilder sb = new StringBuilder();
sb.append(LS);
sb.append("N = ").append(qs.getN()).append(LS);
sb.append("K = ").append(qs.getK()).append(LS);
String formatStr1 = "%10s%15s%10s%15s%10s%10s";
String formatStr2 = "%10.1f%15.5f%10.0f%15.5f%10.5f%10.5f";
String hdr = String.format(
formatStr1, "Rank", "ValueLB", "<= Value", "<= ValueUB", "RelErrLB", "RelErrUB");
sb.append(hdr).append(LS);
for (int i=0; i<ranks.length; i++) {
double rank = ranks[i];
double value = values[i];
if (rank == 0.0) { assertEquals(value, minV, 0.0); }
else if (rank == 1.0) { assertEquals(value, maxV, 0.0); }
else {
double rankUB = rank + rankError;
double valueUB = minV + (delta*rankUB);
double rankLB = Math.max(rank - rankError, 0.0);
double valueLB = minV + (delta*rankLB);
assertTrue(value < valueUB);
assertTrue(value > valueLB);
double valRelPctErrUB = (valueUB/ value) -1.0;
double valRelPctErrLB = (valueLB/ value) -1.0;
String row = String.format(
formatStr2,rank, valueLB, value, valueUB, valRelPctErrLB, valRelPctErrUB);
sb.append(row).append(LS);
}
}
return sb.toString();
}
@Test
public void checkKisTwo() {
int k = 2;
UpdateDoublesSketch qs1 = DoublesSketch.builder().setK(k).build();
double err = qs1.getNormalizedRankError(false);
assertTrue(err < 1.0);
byte[] arr = qs1.toByteArray(true); //8
assertEquals(arr.length, DoublesSketch.getCompactSerialiedSizeBytes(k, 0));
qs1.update(1.0);
arr = qs1.toByteArray(true); //40
assertEquals(arr.length, DoublesSketch.getCompactSerialiedSizeBytes(k, 1));
}
@Test
public void checkKisTwoDeprecated() {
int k = 2;
UpdateDoublesSketch qs1 = DoublesSketch.builder().setK(k).build();
double err = qs1.getNormalizedRankError(false);
assertTrue(err < 1.0);
byte[] arr = qs1.toByteArray(true); //8
assertEquals(arr.length, DoublesSketch.getCompactSerialiedSizeBytes(k, 0));
assertEquals(arr.length, qs1.getCurrentCompactSerializedSizeBytes());
qs1.update(1.0);
arr = qs1.toByteArray(true); //40
assertEquals(arr.length, DoublesSketch.getCompactSerialiedSizeBytes(k, 1));
assertEquals(arr.length, qs1.getCurrentCompactSerializedSizeBytes());
}
@Test
public void checkPutMemory() {
UpdateDoublesSketch qs1 = DoublesSketch.builder().build(); //k = 128
for (int i=0; i<1000; i++) {
qs1.update(i);
}
int bytes = qs1.getCurrentUpdatableSerializedSizeBytes();
WritableMemory dstMem = WritableMemory.writableWrap(new byte[bytes]);
qs1.putMemory(dstMem, false);
Memory srcMem = dstMem;
DoublesSketch qs2 = DoublesSketch.heapify(srcMem);
assertEquals(qs1.getMinItem(), qs2.getMinItem(), 0.0);
assertEquals(qs1.getMaxItem(), qs2.getMaxItem(), 0.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkPutMemoryTooSmall() {
UpdateDoublesSketch qs1 = DoublesSketch.builder().build(); //k = 128
for (int i=0; i<1000; i++) {
qs1.update(i);
}
int bytes = qs1.getCurrentCompactSerializedSizeBytes();
WritableMemory dstMem = WritableMemory.writableWrap(new byte[bytes-1]); //too small
qs1.putMemory(dstMem);
}
//Himanshu's case
@Test
public void testIt() {
java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(1<<20).order(ByteOrder.nativeOrder());
WritableMemory mem = WritableMemory.writableWrap(bb);
int k = 1024;
DoublesSketch qsk = new DoublesSketchBuilder().setK(k).build();
DoublesUnion u1 = DoublesUnion.heapify(qsk);
u1.getResult().putMemory(mem);
DoublesUnion u2 = DoublesUnion.heapify(mem);
DoublesSketch qsk2 = u2.getResult();
assertTrue(qsk2.isEmpty());
}
@Test
public void checkEvenlySpacedQuantiles() {
DoublesSketch qsk = buildAndLoadQS(32, 1001);
double[] values = qsk.getPartitionBoundaries(10).boundaries;
for (int i = 0; i<values.length; i++) {
println(""+values[i]);
}
assertEquals(values.length, 11);
}
@Test
public void getQuantiles() {
final DoublesSketch sketch = buildAndLoadQS(32,0);
sketch.update(1);
sketch.update(2);
sketch.update(3);
sketch.update(4);
double[] quantiles1 = sketch.getQuantiles(new double[] {0.0, 0.5, 1.0}, EXCLUSIVE);
double[] quantiles2 = sketch.getPartitionBoundaries(2, EXCLUSIVE).boundaries;
assertEquals(quantiles1, quantiles2);
quantiles1 = sketch.getQuantiles(new double[] {0.0, 0.5, 1.0}, INCLUSIVE);
quantiles2 = sketch.getPartitionBoundaries(2, INCLUSIVE).boundaries;
assertEquals(quantiles1, quantiles2);
}
@Test
public void checkEquallySpacedRanks() {
int n = 10;
double[] es = equallyWeightedRanks(n);
int len = es.length;
for (int j=0; j<len; j++) {
double f = es[j];
assertEquals(f, j/10.0, (j/10.0) * 0.001);
print(es[j]+", ");
}
println("");
}
@Test
public void checkPMFonEmpty() {
DoublesSketch qsk = buildAndLoadQS(32, 1001);
double[] array = new double[0];
double[] qOut = qsk.getQuantiles(array);
assertEquals(qOut.length, 0);
println("qOut: "+qOut.length);
double[] cdfOut = qsk.getCDF(array);
println("cdfOut: "+cdfOut.length);
assertEquals(cdfOut[0], 1.0, 0.0);
}
@Test
public void checkPuts() {
long n1 = 1001;
UpdateDoublesSketch qsk = buildAndLoadQS(32, (int)n1);
long n2 = qsk.getN();
assertEquals(n2, n1);
int bbCnt1 = qsk.getBaseBufferCount();
long pat1 = qsk.getBitPattern();
qsk.putBitPattern(pat1 + 1); //corrupt the pattern
long pat2 = qsk.getBitPattern();
assertEquals(pat1 + 1, pat2);
qsk.putBaseBufferCount(bbCnt1 + 1); //corrupt the bbCount
int bbCnt2 = qsk.getBaseBufferCount();
assertEquals(bbCnt1 + 1, bbCnt2);
qsk.putN(n1 + 1); //corrupt N
long n3 = qsk.getN();
assertEquals(n1 + 1, n3);
assertNull(qsk.getMemory());
}
@Test
public void serializeDeserializeCompact() {
UpdateDoublesSketch sketch1 = DoublesSketch.builder().build();
for (int i = 0; i < 1000; i++) {
sketch1.update(i);
}
UpdateDoublesSketch sketch2;
sketch2 = (UpdateDoublesSketch) DoublesSketch.heapify(Memory.wrap(sketch1.toByteArray()));
for (int i = 0; i < 1000; i++) {
sketch2.update(i + 1000);
}
assertEquals(sketch2.getMinItem(), 0.0);
assertEquals(sketch2.getMaxItem(), 1999.0);
assertEquals(sketch2.getQuantile(0.5), 1000.0, 10.0);
}
@Test
public void serializeDeserializeEmptyNonCompact() {
UpdateDoublesSketch sketch1 = DoublesSketch.builder().build();
byte[] byteArr = sketch1.toByteArray(false); //Ordered, Not Compact, Empty
assertEquals(byteArr.length, sketch1.getSerializedSizeBytes());
Memory mem = Memory.wrap(byteArr);
UpdateDoublesSketch sketch2 = (UpdateDoublesSketch) DoublesSketch.heapify(mem);
for (int i = 0; i < 1000; i++) {
sketch2.update(i);
}
assertEquals(sketch2.getMinItem(), 0.0);
assertEquals(sketch2.getMaxItem(), 999.0);
assertEquals(sketch2.getQuantile(0.5), 500.0, 4.0);
}
@Test
public void getRankAndGetCdfConsistency() {
final UpdateDoublesSketch sketch = DoublesSketch.builder().build();
final int n = 1_000_000;
final double[] values = new double[n];
for (int i = 0; i < n; i++) {
sketch.update(i);
values[i] = i;
}
{ // inclusive = false (default)
final double[] ranks = sketch.getCDF(values);
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i]), 0.00001, "CDF vs rank for value " + i);
}
}
{ // inclusive = true
final double[] ranks = sketch.getCDF(values, INCLUSIVE);
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i], INCLUSIVE), 0.00001, "CDF vs rank for value " + i);
}
}
}
@Test
public void maxK() {
final UpdateDoublesSketch sketch = DoublesSketch.builder().setK(32768).build();
Assert.assertEquals(sketch.getK(), 32768);
}
@Test
public void checkBounds() {
final UpdateDoublesSketch sketch = DoublesSketch.builder().build();
for (int i = 0; i < 1000; i++) {
sketch.update(i);
}
double eps = sketch.getNormalizedRankError(false);
double est = sketch.getQuantile(0.5);
double ub = sketch.getQuantileUpperBound(0.5);
double lb = sketch.getQuantileLowerBound(0.5);
assertEquals(ub, sketch.getQuantile(.5 + eps));
assertEquals(lb, sketch.getQuantile(0.5 - eps));
println("Ext : " + est);
println("UB : " + ub);
println("LB : " + lb);
}
@Test
public void checkGetKFromEqs() {
final UpdateDoublesSketch sketch = DoublesSketch.builder().build();
int k = sketch.getK();
double eps = DoublesSketch.getNormalizedRankError(k, false);
double epsPmf = DoublesSketch.getNormalizedRankError(k, true);
int kEps = DoublesSketch.getKFromEpsilon(eps, false);
int kEpsPmf = DoublesSketch.getKFromEpsilon(epsPmf, true);
assertEquals(kEps, k);
assertEquals(kEpsPmf, k);
}
@Test
public void tenItems() {
final UpdateDoublesSketch sketch = DoublesSketch.builder().build();
for (int i = 1; i <= 10; i++) { sketch.update(i); }
assertFalse(sketch.isEmpty());
assertEquals(sketch.getN(), 10);
assertEquals(sketch.getNumRetained(), 10);
for (int i = 1; i <= 10; i++) {
assertEquals(sketch.getRank(i, EXCLUSIVE), (i - 1) / 10.0);
assertEquals(sketch.getRank(i, EXCLUSIVE), (i - 1) / 10.0);
assertEquals(sketch.getRank(i, INCLUSIVE), i / 10.0);
}
// inclusive = false (default)
assertEquals(sketch.getQuantile(0, EXCLUSIVE), 1);
assertEquals(sketch.getQuantile(0.1, EXCLUSIVE), 2);
assertEquals(sketch.getQuantile(0.2, EXCLUSIVE), 3);
assertEquals(sketch.getQuantile(0.3, EXCLUSIVE), 4);
assertEquals(sketch.getQuantile(0.4, EXCLUSIVE), 5);
assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 6);
assertEquals(sketch.getQuantile(0.6, EXCLUSIVE), 7);
assertEquals(sketch.getQuantile(0.7, EXCLUSIVE), 8);
assertEquals(sketch.getQuantile(0.8, EXCLUSIVE), 9);
assertEquals(sketch.getQuantile(0.9, EXCLUSIVE), 10);
assertEquals(sketch.getQuantile(1, EXCLUSIVE), 10);
// inclusive = true
assertEquals(sketch.getQuantile(0, INCLUSIVE), 1);
assertEquals(sketch.getQuantile(0.1, INCLUSIVE), 1);
assertEquals(sketch.getQuantile(0.2, INCLUSIVE), 2);
assertEquals(sketch.getQuantile(0.3, INCLUSIVE), 3);
assertEquals(sketch.getQuantile(0.4, INCLUSIVE), 4);
assertEquals(sketch.getQuantile(0.5, INCLUSIVE), 5);
assertEquals(sketch.getQuantile(0.6, INCLUSIVE), 6);
assertEquals(sketch.getQuantile(0.7, INCLUSIVE), 7);
assertEquals(sketch.getQuantile(0.8, INCLUSIVE), 8);
assertEquals(sketch.getQuantile(0.9, INCLUSIVE), 9);
assertEquals(sketch.getQuantile(1, INCLUSIVE), 10);
// getQuantile() and getQuantiles() equivalence
{
// inclusive = false (default)
final double[] quantiles =
sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1});
for (int i = 0; i <= 10; i++) {
assertEquals(sketch.getQuantile(i / 10.0), quantiles[i]);
}
}
{
// inclusive = true
final double[] quantiles =
sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1}, INCLUSIVE);
for (int i = 0; i <= 10; i++) {
assertEquals(sketch.getQuantile(i / 10.0, INCLUSIVE), quantiles[i]);
}
}
}
//private methods
private static void checksForImproperK(final int k) {
final String s = "Did not catch improper k: " + k;
try {
DoublesSketch.builder().setK(k);
fail(s);
} catch (SketchesArgumentException e) {
//pass
}
try {
DoublesSketch.builder().setK(k).build();
fail(s);
} catch (SketchesArgumentException e) {
//pass
}
try {
HeapUpdateDoublesSketch.newInstance(k);
fail(s);
} catch (SketchesArgumentException e) {
//pass
}
}
private static boolean sameStructurePredicate(final DoublesSketch mq1, final DoublesSketch mq2) {
final boolean b1 =
( (mq1.getK() == mq2.getK())
&& (mq1.getN() == mq2.getN())
&& (mq1.getCombinedBufferItemCapacity()
>= ClassicUtil.computeCombinedBufferItemCapacity(mq1.getK(), mq1.getN()))
&& (mq2.getCombinedBufferItemCapacity()
>= ClassicUtil.computeCombinedBufferItemCapacity(mq2.getK(), mq2.getN()))
&& (mq1.getBaseBufferCount() == mq2.getBaseBufferCount())
&& (mq1.getBitPattern() == mq2.getBitPattern()) );
final boolean b2;
if (mq1.isEmpty()) {
b2 = mq2.isEmpty();
} else {
b2 = (mq1.getMinItem() == mq2.getMinItem()) && (mq1.getMaxItem() == mq2.getMaxItem());
}
return b1 && b2;
}
static UpdateDoublesSketch buildAndLoadQS(int k, int n) {
return buildAndLoadQS(k, n, 0);
}
static UpdateDoublesSketch buildAndLoadQS(int k, int n, int startV) {
UpdateDoublesSketch qs = DoublesSketch.builder().setK(k).build();
for (int i=1; i<=n; i++) {
qs.update(startV + i);
}
return qs;
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
print("PRINTING: "+this.getClass().getName() + LS);
}
/**
* @param s value to print
*/
static void println(String s) {
print(s+LS);
}
/**
* @param s value to print
*/
static void print(String s) {
//System.err.print(s); //disable here
}
}
| 2,488 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/ItemsSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.Arrays;
import java.util.Comparator;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfItemsSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.quantilescommon.GenericSortedView;
import org.apache.datasketches.quantilescommon.GenericSortedViewIterator;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ItemsSketchTest {
@BeforeMethod
public void setUp() {
ItemsSketch.rand.setSeed(32749); // make sketches deterministic for testing
}
@Test
public void empty() {
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, 128, Comparator.naturalOrder());
assertNotNull(sketch);
sketch.update(null);
assertTrue(sketch.isEmpty());
assertEquals(sketch.getN(), 0);
assertEquals(sketch.getNumRetained(), 0);
try { sketch.getMinItem(); fail(); } catch (IllegalArgumentException e) {}
try { sketch.getMaxItem(); fail(); } catch (IllegalArgumentException e) {}
try { sketch.getQuantile(0.5); fail(); } catch (IllegalArgumentException e) {}
try { sketch.getQuantiles(new double[] {0.0, 1.0}); fail(); } catch (IllegalArgumentException e) {}
final byte[] byteArr = sketch.toByteArray(new ArrayOfStringsSerDe());
assertEquals(byteArr.length, 8);
try { sketch.getPMF(new String[0]); fail(); } catch (IllegalArgumentException e) {}
try { sketch.getCDF(new String[0]); fail(); } catch (IllegalArgumentException e) {}
try { sketch.getRank("a"); fail(); } catch (IllegalArgumentException e) {}
}
@Test
public void oneItem() {
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, 128, Comparator.naturalOrder());
sketch.update("a");
assertEquals(sketch.getN(), 1);
assertEquals(sketch.getNumRetained(), 1);
assertEquals(sketch.getMinItem(), "a");
assertEquals(sketch.getMaxItem(), "a");
assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), "a");
assertEquals(sketch.getRank("a", EXCLUSIVE), 0.0);
{
final double[] pmf = sketch.getPMF(new String[0], EXCLUSIVE);
assertEquals(pmf.length, 1);
assertEquals(pmf[0], 1.0);
}
{
final double[] pmf = sketch.getPMF(new String[] {"a"}, EXCLUSIVE);
assertEquals(pmf.length, 2);
assertEquals(pmf[0], 0.0);
assertEquals(pmf[1], 1.0);
}
{
final double[] cdf = sketch.getCDF(new String[0], EXCLUSIVE);
assertEquals(cdf.length, 1);
assertEquals(cdf[0], 1.0);
}
{
final double[] cdf = sketch.getCDF(new String[] {"a"}, EXCLUSIVE);
assertEquals(cdf.length, 2);
assertEquals(cdf[0], 0.0);
assertEquals(cdf[1], 1.0);
}
sketch.reset();
assertTrue(sketch.isEmpty());
assertEquals(sketch.getN(), 0);
assertEquals(sketch.getNumRetained(), 0);
try { sketch.getMinItem(); fail(); } catch (IllegalArgumentException e) {}
try { sketch.getMaxItem(); fail(); } catch (IllegalArgumentException e) {}
try { sketch.getQuantile(0.5); fail(); } catch (IllegalArgumentException e) {}
}
@Test
public void tenItems() {
final ItemsSketch<Integer> sketch = ItemsSketch.getInstance(Integer.class, 128, Comparator.naturalOrder());
for (int i = 1; i <= 10; i++) { sketch.update(i); }
assertFalse(sketch.isEmpty());
assertFalse(sketch.hasMemory());
assertFalse(sketch.isReadOnly());
assertEquals(sketch.getN(), 10);
assertEquals(sketch.getNumRetained(), 10);
for (int i = 1; i <= 10; i++) {
assertEquals(sketch.getRank(i), (i) / 10.0);
assertEquals(sketch.getRank(i, EXCLUSIVE), (i - 1) / 10.0);
assertEquals(sketch.getRank(i, INCLUSIVE), i / 10.0);
}
final Integer[] qArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
double[] rOut = sketch.getRanks(qArr); //inclusive
for (int i = 0; i < qArr.length; i++) {
assertEquals(rOut[i], (i + 1) / 10.0);
}
rOut = sketch.getRanks(qArr, EXCLUSIVE); //exclusive
for (int i = 0; i < qArr.length; i++) {
assertEquals(rOut[i], i / 10.0);
}
// inclusive = (default)
assertEquals(sketch.getQuantile(0, EXCLUSIVE), 1);
assertEquals(sketch.getQuantile(0.1, EXCLUSIVE), 2);
assertEquals(sketch.getQuantile(0.2, EXCLUSIVE), 3);
assertEquals(sketch.getQuantile(0.3, EXCLUSIVE), 4);
assertEquals(sketch.getQuantile(0.4, EXCLUSIVE), 5);
assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 6);
assertEquals(sketch.getQuantile(0.6, EXCLUSIVE), 7);
assertEquals(sketch.getQuantile(0.7, EXCLUSIVE), 8);
assertEquals(sketch.getQuantile(0.8, EXCLUSIVE), 9);
assertEquals(sketch.getQuantile(0.9, EXCLUSIVE), 10);
assertEquals(sketch.getQuantile(1, EXCLUSIVE), 10);
// inclusive = true
assertEquals(sketch.getQuantile(0, INCLUSIVE), 1);
assertEquals(sketch.getQuantile(0.1, INCLUSIVE), 1);
assertEquals(sketch.getQuantile(0.2, INCLUSIVE), 2);
assertEquals(sketch.getQuantile(0.3, INCLUSIVE), 3);
assertEquals(sketch.getQuantile(0.4, INCLUSIVE), 4);
assertEquals(sketch.getQuantile(0.5, INCLUSIVE), 5);
assertEquals(sketch.getQuantile(0.6, INCLUSIVE), 6);
assertEquals(sketch.getQuantile(0.7, INCLUSIVE), 7);
assertEquals(sketch.getQuantile(0.8, INCLUSIVE), 8);
assertEquals(sketch.getQuantile(0.9, INCLUSIVE), 9);
assertEquals(sketch.getQuantile(1, INCLUSIVE), 10);
// getQuantile() and getQuantiles() equivalence
{
// inclusive = (default)
final Integer[] quantiles =
sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1});
for (int i = 0; i <= 10; i++) {
assertEquals(sketch.getQuantile(i / 10.0), quantiles[i]);
}
}
{
// inclusive = true
final Integer[] quantiles =
sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1}, INCLUSIVE);
for (int i = 0; i <= 10; i++) {
assertEquals(sketch.getQuantile(i / 10.0, INCLUSIVE), quantiles[i]);
}
}
}
@Test
public void estimation() {
final ItemsSketch<Integer> sketch = ItemsSketch.getInstance(Integer.class, 128, Comparator.naturalOrder());
for (int i = 1; i <= 1000; i++) {
sketch.update(i);
}
assertEquals(sketch.getN(), 1000);
assertTrue(sketch.getNumRetained() < 1000);
assertEquals(sketch.getMinItem(), Integer.valueOf(1));
assertEquals(sketch.getMaxItem(), Integer.valueOf(1000));
// based on ~1.7% normalized rank error for this particular case
assertEquals(sketch.getQuantile(0.5), Integer.valueOf(500), 17);
final double[] normRanks = {0.0, 0.5, 1.0};
Integer[] quantiles = sketch.getQuantiles(normRanks);
assertEquals(quantiles[1], Integer.valueOf(500), 17); // median
final double[] normRanks2 = {.25, 0.5, 0.75};
final Integer[] quantiles2 = sketch.getQuantiles(normRanks2);
assertEquals(quantiles2[0], Integer.valueOf(250), 17);
assertEquals(quantiles2[1], Integer.valueOf(500), 17);
assertEquals(quantiles2[2], Integer.valueOf(750), 17);
final double normErr = sketch.getNormalizedRankError(true);
assertEquals(normErr, .0172, .001);
println(""+normErr);
{
final double[] pmf = sketch.getPMF(new Integer[0]);
assertEquals(pmf.length, 1);
assertEquals(pmf[0], 1.0);
}
{
final double[] pmf = sketch.getPMF(new Integer[] {500});
assertEquals(pmf.length, 2);
assertEquals(pmf[0], 0.5, 0.05);
assertEquals(pmf[1], 0.5, 0.05);
}
{
final Integer[] intArr = new Integer[50];
for (int i= 0; i<50; i++) {
intArr[i] = 20*i +10;
}
final double[] pmf = sketch.getPMF(intArr);
assertEquals(pmf.length, 51);
}
{
final double[] cdf = sketch.getCDF(new Integer[0]);
assertEquals(cdf.length, 1);
assertEquals(cdf[0], 1.0);
}
{
final double[] cdf = sketch.getCDF(new Integer[] {500});
assertEquals(cdf.length, 2);
assertEquals(cdf[0], 0.5, 0.05);
assertEquals(cdf[1], 1.0, 0.05);
}
assertEquals(sketch.getRank(500), 0.5, 0.01);
}
@Test
public void serializeDeserializeLong() {
final ItemsSketch<Long> sketch1 = ItemsSketch.getInstance(Long.class, 128, Comparator.naturalOrder());
for (int i = 1; i <= 500; i++) {
sketch1.update((long) i);
}
final ArrayOfItemsSerDe<Long> serDe = new ArrayOfLongsSerDe();
final byte[] bytes = sketch1.toByteArray(serDe);
final ItemsSketch<Long> sketch2 =
ItemsSketch.getInstance(Long.class, Memory.wrap(bytes), Comparator.naturalOrder(), serDe);
for (int i = 501; i <= 1000; i++) {
sketch2.update((long) i);
}
assertEquals(sketch2.getN(), 1000);
assertTrue(sketch2.getNumRetained() < 1000);
assertEquals(sketch2.getMinItem(), Long.valueOf(1));
assertEquals(sketch2.getMaxItem(), Long.valueOf(1000));
// based on ~1.7% normalized rank error for this particular case
assertEquals(sketch2.getQuantile(0.5), Long.valueOf(500), 17);
}
@Test
public void serializeDeserializeDouble() {
final ItemsSketch<Double> sketch1 = ItemsSketch.getInstance(Double.class, 128, Comparator.naturalOrder());
for (int i = 1; i <= 500; i++) {
sketch1.update((double) i);
}
final ArrayOfItemsSerDe<Double> serDe = new ArrayOfDoublesSerDe();
final byte[] bytes = sketch1.toByteArray(serDe);
final ItemsSketch<Double> sketch2 =
ItemsSketch.getInstance(Double.class, Memory.wrap(bytes), Comparator.naturalOrder(), serDe);
for (int i = 501; i <= 1000; i++) {
sketch2.update((double) i);
}
assertEquals(sketch2.getN(), 1000);
assertTrue(sketch2.getNumRetained() < 1000);
assertEquals(sketch2.getMinItem(), Double.valueOf(1));
assertEquals(sketch2.getMaxItem(), Double.valueOf(1000));
// based on ~1.7% normalized rank error for this particular case
assertEquals(sketch2.getQuantile(0.5), 500, 17);
}
@Test
public void serializeDeserializeString() {
// numeric order to be able to make meaningful assertions
final Comparator<String> numericOrder = new Comparator<String>() {
@Override
public int compare(final String s1, final String s2) {
final Integer i1 = Integer.parseInt(s1, 2);
final Integer i2 = Integer.parseInt(s2, 2);
return i1.compareTo(i2);
}
};
final ItemsSketch<String> sketch1 = ItemsSketch.getInstance(String.class, 128, numericOrder);
for (int i = 1; i <= 500; i++)
{
sketch1.update(Integer.toBinaryString(i << 10)); // to make strings longer
}
final ArrayOfItemsSerDe<String> serDe = new ArrayOfStringsSerDe();
final byte[] bytes = sketch1.toByteArray(serDe);
final ItemsSketch<String> sketch2 = ItemsSketch.getInstance(String.class, Memory.wrap(bytes), numericOrder, serDe);
for (int i = 501; i <= 1000; i++) {
sketch2.update(Integer.toBinaryString(i << 10));
}
assertEquals(sketch2.getN(), 1000);
assertTrue(sketch2.getNumRetained() < 1000);
assertEquals(sketch2.getMinItem(), Integer.toBinaryString(1 << 10));
assertEquals(sketch2.getMaxItem(), Integer.toBinaryString(1000 << 10));
// based on ~1.7% normalized rank error for this particular case
assertEquals(Integer.parseInt(sketch2.getQuantile(0.5), 2) >> 10, Integer.valueOf(500), 17);
}
@Test
public void toStringCrudeCheck() {
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, Comparator.naturalOrder());
String brief, full, part;
brief = sketch.toString();
full = sketch.toString(true, true);
part = sketch.toString(false, true);
sketch.update("a");
brief = sketch.toString();
full = sketch.toString(true, true);
part = sketch.toString(false, true);
//println(full);
assertTrue(brief.length() < full.length());
assertTrue(part.length() < full.length());
final ArrayOfItemsSerDe<String> serDe = new ArrayOfStringsSerDe();
final byte[] bytes = sketch.toByteArray(serDe);
ItemsSketch.toString(bytes);
ItemsSketch.toString(Memory.wrap(bytes));
//PreambleUtil.toString(bytes, true); // not a DoublesSketch so this will fail
//ItemsSketch<String> sketch2 = ItemsSketch.getInstance(Memory.wrap(bytes), Comparator.naturalOrder(), serDe);
}
@Test
public void toStringBiggerCheck() {
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder());
for (int i=0; i<40; i++) {
sketch.update(Integer.toString(i));
}
final String bigger = sketch.toString();
final String full = sketch.toString(true, true);
//println(full);
assertTrue(bigger.length() < full.length());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkDownsampleException() {
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder());
for (int i=0; i<40; i++) {
sketch.update(Integer.toString(i));
}
sketch.downSample(32);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void negativeQuantileMustThrow() {
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder());
sketch.update("ABC");
sketch.getQuantile(-0.1);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkGetInstanceExcep1() {
final Memory mem = Memory.wrap(new byte[4]);
ItemsSketch.getInstance(String.class, mem, Comparator.naturalOrder(), new ArrayOfStringsSerDe());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkGetInstanceExcep2() {
final Memory mem = Memory.wrap(new byte[8]);
ItemsSketch.getInstance(String.class, mem, Comparator.naturalOrder(), new ArrayOfStringsSerDe());
}
@Test
public void checkGoodSerDeId() {
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, Comparator.naturalOrder());
final byte[] byteArr = sketch.toByteArray(new ArrayOfStringsSerDe());
final Memory mem = Memory.wrap(byteArr);
//println(PreambleUtil.toString(mem));
ItemsSketch.getInstance(String.class, mem, Comparator.naturalOrder(), new ArrayOfStringsSerDe());
}
@Test
public void checkDownsample() {
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder());
for (int i=0; i<40; i++) {
sketch.update(Integer.toString(i));
}
final ItemsSketch<String> out = sketch.downSample(8);
assertEquals(out.getK(), 8);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void unorderedSplitPoints() {
final ItemsSketch<Integer> sketch = ItemsSketch.getInstance(Integer.class, Comparator.naturalOrder());
sketch.update(1);
sketch.getPMF(new Integer[] {2, 1});
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void nonUniqueSplitPoints() {
final ItemsSketch<Integer> sketch = ItemsSketch.getInstance(Integer.class, Comparator.naturalOrder());
sketch.update(1);
sketch.getPMF(new Integer[] {1, 1});
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void nullInSplitPoints() {
final ItemsSketch<Integer> sketch = ItemsSketch.getInstance(Integer.class, Comparator.naturalOrder());
sketch.update(1);
sketch.getPMF(new Integer[] {1, null});
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void compactNotSupported() {
final ArrayOfDoublesSerDe serDe = new ArrayOfDoublesSerDe();
final ItemsSketch<Double> sketch = ItemsSketch.getInstance(Double.class, Comparator.naturalOrder());
final byte[] byteArr = sketch.toByteArray(serDe);
final WritableMemory mem = WritableMemory.writableWrap(byteArr);
mem.clearBits(PreambleUtil.FLAGS_BYTE, (byte) PreambleUtil.COMPACT_FLAG_MASK);
println(PreambleUtil.toString(mem, false));
ItemsSketch.getInstance(Double.class, mem, Comparator.naturalOrder(), serDe);
}
@Test
public void checkPutMemory() {
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder());
for (int i=0; i<40; i++) {
sketch.update(Integer.toString(i));
}
final byte[] byteArr = new byte[200];
final WritableMemory mem = WritableMemory.writableWrap(byteArr);
sketch.putMemory(mem, new ArrayOfStringsSerDe());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkPutMemoryException() {
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder());
for (int i=0; i<40; i++) {
sketch.update(Integer.toString(i));
}
final byte[] byteArr = new byte[100];
final WritableMemory mem = WritableMemory.writableWrap(byteArr);
sketch.putMemory(mem, new ArrayOfStringsSerDe());
}
@Test
public void checkPMFonEmpty() {
final ItemsSketch<String> iss = buildStringIS(32, 32);
final double[] ranks = new double[0];
final String[] qOut = iss.getQuantiles(ranks);
println("qOut: "+qOut.length);
assertEquals(qOut.length, 0);
final double[] cdfOut = iss.getCDF(new String[0]);
println("cdfOut: "+cdfOut.length);
assertEquals(cdfOut[0], 1.0, 0.0);
}
@Test
public void checkToFromByteArray() {
checkToFromByteArray2(128, 1300); //generates a pattern of 5 -> 101
checkToFromByteArray2(4, 7);
checkToFromByteArray2(4, 8);
checkToFromByteArray2(4, 9);
}
@Test
public void getRankAndGetCdfConsistency() {
final ItemsSketch<Integer> sketch = ItemsSketch.getInstance(Integer.class, Comparator.naturalOrder());
final int n = 1_000_000;
final Integer[] values = new Integer[n];
for (int i = 0; i < n; i++) {
sketch.update(i);
values[i] = i;
}
{ // inclusive = false (default)
final double[] ranks = sketch.getCDF(values);
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i]), 0.00001, "CDF vs rank for value " + i);
}
}
{ // inclusive = true
final double[] ranks = sketch.getCDF(values, INCLUSIVE);
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i], INCLUSIVE), 0.00001, "CDF vs rank for value " + i);
}
}
}
@Test
public void getRankAndGetCdfConsistencyReverseComparator() {
final ItemsSketch<Integer> sketch =
ItemsSketch.getInstance(Integer.class, Comparator.<Integer>naturalOrder().reversed());
final int n = 1_000_000;
final Integer[] values = new Integer[n];
for (int i = 0; i < n; i++) {
sketch.update(i);
values[i] = i;
}
Arrays.sort(values, sketch.getComparator());
final double[] ranks = sketch.getCDF(values);
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i]), 0.00001, "CDF vs rank for value " + i);
}
}
@Test
public void checkBounds() {
final ItemsSketch<Double> sketch = ItemsSketch.getInstance(Double.class, Comparator.naturalOrder());
for (int i = 0; i < 1000; i++) {
sketch.update((double)i);
}
final double eps = sketch.getNormalizedRankError(false);
final double est = sketch.getQuantile(0.5);
final double ub = sketch.getQuantileUpperBound(0.5);
final double lb = sketch.getQuantileLowerBound(0.5);
assertEquals(ub, (double)sketch.getQuantile(.5 + eps));
assertEquals(lb, (double)sketch.getQuantile(0.5 - eps));
println("Ext : " + est);
println("UB : " + ub);
println("LB : " + lb);
}
@Test
public void checkGetKFromEqs() {
final ItemsSketch<Double> sketch = ItemsSketch.getInstance(Double.class, Comparator.naturalOrder());
final int k = sketch.getK();
final double eps = ItemsSketch.getNormalizedRankError(k, false);
final double epsPmf = ItemsSketch.getNormalizedRankError(k, true);
final int kEps = ItemsSketch.getKFromEpsilon(eps, false);
final int kEpsPmf = ItemsSketch.getKFromEpsilon(epsPmf, true);
assertEquals(kEps, k);
assertEquals(kEpsPmf, k);
}
private static void checkToFromByteArray2(final int k, final int n) {
final ItemsSketch<String> is = buildStringIS(k, n);
byte[] byteArr;
Memory mem;
ItemsSketch<String> is2;
final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
//ordered
byteArr = is.toByteArray(true, serDe);
mem = Memory.wrap(byteArr);
is2 = ItemsSketch.getInstance(String.class, mem, Comparator.naturalOrder(), serDe);
for (double f = 0.1; f < 0.95; f += 0.1) {
assertEquals(is.getQuantile(f), is2.getQuantile(f));
}
//Not-ordered
byteArr = is.toByteArray(false, serDe);
mem = Memory.wrap(byteArr);
is2 = ItemsSketch.getInstance(String.class, mem, Comparator.naturalOrder(), serDe);
for (double f = 0.1; f < 0.95; f += 0.1) {
assertEquals(is.getQuantile(f), is2.getQuantile(f));
}
}
static ItemsSketch<String> buildStringIS(final int k, final int n) {
return buildStringIS(k, n, 0);
}
static ItemsSketch<String> buildStringIS(final int k, final int n, final int start) {
final ItemsSketch<String> sketch = ItemsSketch.getInstance(String.class, k, Comparator.naturalOrder());
for (int i = 0; i < n; i++) {
sketch.update(Integer.toString(i + start));
}
return sketch;
}
@Test
public void sortedView() {
final ItemsSketch<Integer> sketch = ItemsSketch.getInstance(Integer.class, Comparator.naturalOrder());
sketch.update(3);
sketch.update(1);
sketch.update(2);
{ // cumulative inclusive
final GenericSortedView<Integer> view = sketch.getSortedView();
final GenericSortedViewIterator<Integer> it = view.iterator();
assertEquals(it.next(), true);
assertEquals(it.getQuantile(), 1);
assertEquals(it.getWeight(), 1);
assertEquals(it.getCumulativeWeight(INCLUSIVE), 1);
assertEquals(it.next(), true);
assertEquals(it.getQuantile(), 2);
assertEquals(it.getWeight(), 1);
assertEquals(it.getCumulativeWeight(INCLUSIVE), 2);
assertEquals(it.next(), true);
assertEquals(it.getQuantile(), 3);
assertEquals(it.getWeight(), 1);
assertEquals(it.getCumulativeWeight(INCLUSIVE), 3);
assertEquals(it.next(), false);
}
}
@Test
public void sortedView2() {
Double[] qArr = {8.0, 10.0, 10.0, 20.0};
long[] cwArr = {1, 3, 4, 5};
Comparator<Double> comp = Comparator.naturalOrder();
ItemsSketchSortedView<Double> sv = new ItemsSketchSortedView<>(qArr, cwArr, 5L, comp);
double[] ranks = {0, .1, .2, .3, .6, .7, .8, .9, 1.0};
Double[] qOut = new Double[9];
for (int i = 0; i < ranks.length; i++) {
qOut[i] = sv.getQuantile(ranks[i], EXCLUSIVE);
println("rank: " + ranks[i] + ", quantiles: " + qOut[i]);
}
long[] cumWts = sv.getCumulativeWeights();
Double[] quants = sv.getQuantiles();
for (int i = 0; i < qArr.length; i++) {
assertEquals(quants[i], qArr[i]);
assertEquals(cumWts[i], cwArr[i]);
}
}
@Test
public void getQuantiles() {
final ItemsSketch<Integer> sketch = ItemsSketch.getInstance(Integer.class, Comparator.naturalOrder());
sketch.update(1);
sketch.update(2);
sketch.update(3);
sketch.update(4);
Integer[] quantiles1 = sketch.getQuantiles(new double[] {0.0, 0.5, 1.0}, EXCLUSIVE);
Integer[] quantiles2 = sketch.getPartitionBoundaries(2, EXCLUSIVE).boundaries;
assertEquals(quantiles1, quantiles2);
quantiles1 = sketch.getQuantiles(new double[] {0.0, 0.5, 1.0}, INCLUSIVE);
quantiles2 = sketch.getPartitionBoundaries(2, INCLUSIVE).boundaries;
assertEquals(quantiles1, quantiles2);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| 2,489 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/PreambleUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.quantiles.PreambleUtil.extractFamilyID;
import static org.apache.datasketches.quantiles.PreambleUtil.extractFlags;
import static org.apache.datasketches.quantiles.PreambleUtil.extractK;
import static org.apache.datasketches.quantiles.PreambleUtil.extractMaxDouble;
import static org.apache.datasketches.quantiles.PreambleUtil.extractMinDouble;
import static org.apache.datasketches.quantiles.PreambleUtil.extractN;
import static org.apache.datasketches.quantiles.PreambleUtil.extractPreLongs;
import static org.apache.datasketches.quantiles.PreambleUtil.extractSerVer;
import static org.apache.datasketches.quantiles.PreambleUtil.insertFamilyID;
import static org.apache.datasketches.quantiles.PreambleUtil.insertFlags;
import static org.apache.datasketches.quantiles.PreambleUtil.insertK;
import static org.apache.datasketches.quantiles.PreambleUtil.insertMaxDouble;
import static org.apache.datasketches.quantiles.PreambleUtil.insertMinDouble;
import static org.apache.datasketches.quantiles.PreambleUtil.insertN;
import static org.apache.datasketches.quantiles.PreambleUtil.insertPreLongs;
import static org.apache.datasketches.quantiles.PreambleUtil.insertSerVer;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableHandle;
import org.apache.datasketches.memory.WritableMemory;
public class PreambleUtilTest {
@Test
public void checkInsertsAndExtracts() {
final int bytes = 32;
try (WritableHandle offHeapMemHandler = WritableMemory.allocateDirect(bytes)) {
final WritableMemory offHeapMem = offHeapMemHandler.getWritable();
final WritableMemory onHeapMem = WritableMemory.writableWrap(new byte[bytes]);
onHeapMem.clear();
offHeapMem.clear();
//BYTES
int v = 0XFF;
int onH, offH;
//PREAMBLE_LONGS_BYTE;
insertPreLongs(onHeapMem, v);
onH = extractPreLongs(onHeapMem);
assertEquals(onH, v);
insertPreLongs(offHeapMem, v);
offH = extractPreLongs(offHeapMem);
assertEquals(offH, v);
onHeapMem.clear();
offHeapMem.clear();
//SER_VER_BYTE;
insertSerVer(onHeapMem, v);
onH = extractSerVer(onHeapMem);
assertEquals(onH, v);
insertSerVer(offHeapMem, v);
offH = extractSerVer(offHeapMem);
assertEquals(offH, v);
onHeapMem.clear();
offHeapMem.clear();
//FAMILY_BYTE;
insertFamilyID(onHeapMem, v);
onH = extractFamilyID(onHeapMem);
assertEquals(onH, v);
insertFamilyID(offHeapMem, v);
offH = extractFamilyID(offHeapMem);
assertEquals(offH, v);
onHeapMem.clear();
offHeapMem.clear();
//FLAGS_BYTE;
insertFlags(onHeapMem, v);
onH = extractFlags(onHeapMem);
assertEquals(onH, v);
insertFlags(offHeapMem, v);
offH = extractFlags(offHeapMem);
assertEquals(offH, v);
onHeapMem.clear();
offHeapMem.clear();
//SHORTS
v = 0XFFFF;
//K_SHORT;
insertK(onHeapMem, v);
onH = extractK(onHeapMem);
assertEquals(onH, v);
insertK(offHeapMem, v);
offH = extractK(offHeapMem);
assertEquals(offH, v);
onHeapMem.clear();
offHeapMem.clear();
//LONGS
//N_LONG;
long onHL, offHL, vL = 1L << 30;
insertN(onHeapMem, vL);
onHL = extractN(onHeapMem);
assertEquals(onHL, vL);
insertN(offHeapMem, vL);
offHL = extractN(offHeapMem);
assertEquals(offHL, vL);
onHeapMem.clear();
offHeapMem.clear();
//DOUBLES
//MIN_DOUBLE;
double onHD, offHD, vD = 1L << 40;
insertMinDouble(onHeapMem, vD);
onHD = extractMinDouble(onHeapMem);
assertEquals(onHD, vD);
insertMinDouble(offHeapMem, vD);
offHD = extractMinDouble(offHeapMem);
assertEquals(offHD, vD);
onHeapMem.clear();
offHeapMem.clear();
//MAX_DOUBLE;
insertMaxDouble(onHeapMem, vD);
onHD = extractMaxDouble(onHeapMem);
assertEquals(onHD, vD);
insertMaxDouble(offHeapMem, vD);
offHD = extractMaxDouble(offHeapMem);
assertEquals(offHD, vD);
onHeapMem.clear();
offHeapMem.clear();
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkToString() {
int k = PreambleUtil.DEFAULT_K;
int n = 1000000;
UpdateDoublesSketch qs = DoublesSketch.builder().setK(k).build();
for (int i=0; i<n; i++) {
qs.update(i);
}
byte[] byteArr = qs.toByteArray();
DoublesSketch.toString(byteArr);
println(DoublesSketch.toString(Memory.wrap(byteArr)));
}
@Test
public void checkToStringEmpty() {
int k = PreambleUtil.DEFAULT_K;
DoublesSketch qs = DoublesSketch.builder().setK(k).build();
byte[] byteArr = qs.toByteArray();
println(PreambleUtil.toString(byteArr, true));
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,490 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/CustomQuantilesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueDoubleQuantile;
import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueDoubleRank;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
public class CustomQuantilesTest {
@Test
/**
* Currently, this test only exercises the classic DoublesSketch, but all the quantiles
* sketches use the same code for getQuantile() and getRank() anyway.
* This same pattern is also part of the CrossCheckQuantilesTest.
* This structure of this test allows more detailed analysis for troubleshooting.
*/
public void checkQuantilesV400() {
println("Classic DoubleSketch, Version 4.0.0, k=4");
println("");
//The following for loop creates the following pattern for the sorted view:
// Quantiles: {10,10,20,20,30,30,40,40}
// Weights : { 2, 1, 2, 1, 2, 1, 2, 1}
//This is easy to create from the classic quantiles sketch directly, but for the other
//quantiles sketches it would be easier to create by loading the sorted view directly via
//a package-private constructor.
int k = 4;
UpdateDoublesSketch sk = DoublesSketch.builder().setK(k).build();
for (int i = 1; i <= 3; i++) {
for (int q = 10; q <= k * 10; q += 10) {
sk.update(q);
}
}
long N = sk.getN();
DoublesSketchSortedView sv = new DoublesSketchSortedView(sk);
double[] quantilesArr = sv.getQuantiles();
long[] cumWtsArr = sv.getCumulativeWeights();
int lenQ = quantilesArr.length;
println("Sorted View:");
printf("%12s%12s%12s\n", "Quantiles", "ICumWts", "IRanks");
double normRank;
for (int i = 0; i < lenQ; i++) {
normRank = (double)cumWtsArr[i] / N;
printf("%12.1f%12d%12.4f\n", quantilesArr[i], cumWtsArr[i], normRank);
}
println("");
println("GetRanks, EXCLUSIVE:");
println(" R of the largest Q at the highest index that is < q. If q <= smallest Q => 0");
printf("%12s%12s\n", "Quantiles", "Ranks");
for (int q = 0; q <= (k * 10) + 5; q += 5) {
double nr = sk.getRank(q, EXCLUSIVE);
double nrTrue = getTrueDoubleRank(cumWtsArr, quantilesArr, q, EXCLUSIVE);
assertEquals(nr, nrTrue);
printf("%12.1f%12.3f\n", (double)q, nr);
}
println("");
println("GetQuantiles, EXCLUSIVE (round down)");
println(" Q of the smallest rank > r. If r = 1.0 => null or NaN");
printf("%12s%12s%12s\n", "Ranks", "Quantiles", "CompRank");
double inc = 1.0 / (2 * N);
for (long j = 0; j <= (2 * N); j++) {
double nr = (j * inc);
double q = sk.getQuantile(nr, EXCLUSIVE);
double qTrue = getTrueDoubleQuantile(cumWtsArr, quantilesArr, nr, EXCLUSIVE);
assertEquals(q, qTrue);
double nrN = Math.floor(nr * N);
printf("%12.4f%12.1f%12.1f\n", nr, q, nrN);
}
println("");
println("GetRanks, INCLUSIVE:");
println(" R of the largest Q at the highest index that is <= q. If q < smallest Q => 0");
printf("%12s%12s\n", "Quantiles", "Ranks");
for (int q = 0; q <= (k * 10) + 5; q += 5) {
double nr = sk.getRank(q, INCLUSIVE);
double nrTrue = getTrueDoubleRank(cumWtsArr, quantilesArr, q, INCLUSIVE);
assertEquals(nr, nrTrue);
printf("%12.1f%12.3f\n", (double)q, nr);
}
println("");
println("GetQuantiles, INCLUSIVE (round up)");
println(" Q of the smallest rank >= r.");
printf("%12s%12s%12s\n", "Ranks", "Quantiles", "CompRank");
inc = 1.0 / (2 * N);
for (long j = 0; j <= (2 * N); j++) {
double nr = (j * inc);
double q = sk.getQuantile(nr, INCLUSIVE);
double qTrue = getTrueDoubleQuantile(cumWtsArr, quantilesArr, nr, INCLUSIVE);
assertEquals(q, qTrue);
double nrN = Math.ceil(nr * N);
printf("%12.4f%12.1f%12.1f\n", nr, q, nrN);
}
println("");
}
private final static boolean enablePrinting = false;
/**
* @param o the Object to print
*/
static final void print(final Object o) {
if (enablePrinting) { System.out.print(o.toString()); }
}
/**
* @param o the Object to println
*/
static final void println(final Object o) {
if (enablePrinting) { System.out.println(o.toString()); }
}
/**
* @param format the format
* @param args the args
*/
static final void printf(final String format, final Object ...args) {
if (enablePrinting) { System.out.printf(format, args); }
}
}
| 2,491 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/DirectUpdateDoublesSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.common.Util.ceilingIntPowerOf2;
import static org.apache.datasketches.quantiles.ClassicUtil.LS;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DirectUpdateDoublesSketchTest {
@BeforeMethod
public void setUp() {
DoublesSketch.rand.setSeed(32749); // make sketches deterministic for testing
}
@Test
public void checkSmallMinMax () {
int k = 32;
int n = 8;
UpdateDoublesSketch qs1 = buildDQS(k, n);
UpdateDoublesSketch qs2 = buildDQS(k, n);
UpdateDoublesSketch qs3 = buildDQS(k, n);
for (int i = n; i >= 1; i--) {
qs1.update(i);
qs2.update(10+i);
qs3.update(i);
}
assertEquals(qs1.getQuantile (0.0, EXCLUSIVE), 1.0);
assertEquals(qs1.getQuantile (0.5, EXCLUSIVE), 5.0);
assertEquals(qs1.getQuantile (1.0, EXCLUSIVE), 8.0);
assertEquals(qs2.getQuantile (0.0, EXCLUSIVE), 11.0);
assertEquals(qs2.getQuantile (0.5, EXCLUSIVE), 15.0);
assertEquals(qs2.getQuantile (1.0, EXCLUSIVE), 18.0);
assertEquals(qs3.getQuantile (0.0, EXCLUSIVE), 1.0);
assertEquals(qs3.getQuantile (0.5, EXCLUSIVE), 5.0);
assertEquals(qs3.getQuantile (1.0, EXCLUSIVE), 8.0);
double[] queries = {0.0, 0.5, 1.0};
double[] resultsA = qs1.getQuantiles(queries, EXCLUSIVE);
assertEquals(resultsA[0], 1.0);
assertEquals(resultsA[1], 5.0);
assertEquals(resultsA[2], 8.0);
DoublesUnion union1 = DoublesUnion.heapify(qs1);
union1.union(qs2);
DoublesSketch result1 = union1.getResult();
DoublesUnion union2 = DoublesUnion.heapify(qs2);
union2.union(qs3);
DoublesSketch result2 = union2.getResult();
double[] resultsB = result1.getQuantiles(queries, EXCLUSIVE);
printResults(resultsB);
assertEquals(resultsB[0], 1.0);
assertEquals(resultsB[1], 11.0);
assertEquals(resultsB[2], 18.0);
double[] resultsC = result2.getQuantiles(queries, EXCLUSIVE);
assertEquals(resultsC[0], 1.0);
assertEquals(resultsC[1], 11.0);
assertEquals(resultsC[2], 18.0);
}
static void printResults(double[] results) {
println(results[0] + ", " + results[1] + ", " + results[2]);
}
@Test
public void wrapEmptyUpdateSketch() {
final UpdateDoublesSketch s1 = DoublesSketch.builder().build();
final WritableMemory mem
= WritableMemory.writableWrap(ByteBuffer.wrap(s1.toByteArray()).order(ByteOrder.nativeOrder()));
final UpdateDoublesSketch s2 = DirectUpdateDoublesSketch.wrapInstance(mem);
assertTrue(s2.isEmpty());
assertEquals(s2.getN(), 0);
assertTrue(Double.isNaN(s2.isEmpty() ? Double.NaN : s2.getMinItem()));
assertTrue(Double.isNaN(s2.isEmpty() ? Double.NaN : s2.getMaxItem()));
s2.reset(); // empty: so should be a no-op
assertEquals(s2.getN(), 0);
}
@Test
public void checkPutCombinedBuffer() {
final int k = PreambleUtil.DEFAULT_K;
final int cap = 32 + ((2 * k) << 3);
WritableMemory mem = WritableMemory.writableWrap(new byte[cap]);
final UpdateDoublesSketch qs = DoublesSketch.builder().setK(k).build(mem);
mem = qs.getMemory();
assertEquals(mem.getCapacity(), cap);
assertTrue(qs.isEmpty());
final int n = 16;
final double[] data = new double[n];
for (int i = 0; i < n; ++i) {
data[i] = i + 1;
}
qs.putBaseBufferCount(n);
qs.putN(n);
qs.putCombinedBuffer(data);
final double[] combBuf = qs.getCombinedBuffer();
assertEquals(combBuf, data);
// shouldn't have changed min/max values
assertTrue(Double.isNaN(qs.getMinItem()));
assertTrue(Double.isNaN(qs.getMaxItem()));
}
@Test
public void checkMisc() {
int k = PreambleUtil.DEFAULT_K;
int n = 48;
int cap = 32 + ((2 * k) << 3);
WritableMemory mem = WritableMemory.writableWrap(new byte[cap]);
UpdateDoublesSketch qs = DoublesSketch.builder().setK(k).build(mem);
mem = qs.getMemory();
assertEquals(mem.getCapacity(), cap);
double[] combBuf = qs.getCombinedBuffer();
assertEquals(combBuf.length, 2 * k);
qs = buildAndLoadDQS(k, n);
qs.update(Double.NaN);
int n2 = (int)qs.getN();
assertEquals(n2, n);
combBuf = qs.getCombinedBuffer();
assertEquals(combBuf.length, ceilingIntPowerOf2(n)); // since n < k
println(qs.toString(true, true));
qs.reset();
assertEquals(qs.getN(), 0);
qs.putBaseBufferCount(0);
}
@SuppressWarnings("unused")
@Test
public void variousExceptions() {
WritableMemory mem = WritableMemory.writableWrap(new byte[8]);
try {
int flags = PreambleUtil.COMPACT_FLAG_MASK;
DirectUpdateDoublesSketchR.checkCompact(2, 0);
fail();
} catch (SketchesArgumentException e) {} //OK
try {
int flags = PreambleUtil.COMPACT_FLAG_MASK;
DirectUpdateDoublesSketchR.checkCompact(3, flags);
fail();
} catch (SketchesArgumentException e) {} //OK
try {
DirectUpdateDoublesSketchR.checkPreLongs(3);
fail();
} catch (SketchesArgumentException e) {} //OK
try {
DirectUpdateDoublesSketchR.checkPreLongs(0);
fail();
} catch (SketchesArgumentException e) {} //OK
try {
DirectUpdateDoublesSketchR.checkDirectFlags(PreambleUtil.COMPACT_FLAG_MASK);
fail();
} catch (SketchesArgumentException e) {} //OK
try {
DirectUpdateDoublesSketchR.checkEmptyAndN(true, 1);
fail();
} catch (SketchesArgumentException e) {} //OK
}
@Test
public void checkCheckDirectMemCapacity() {
final int k = 128;
DirectUpdateDoublesSketchR.checkDirectMemCapacity(k, (2 * k) - 1, (4 + (2 * k)) * 8);
DirectUpdateDoublesSketchR.checkDirectMemCapacity(k, (2 * k) + 1, (4 + (3 * k)) * 8);
DirectUpdateDoublesSketchR.checkDirectMemCapacity(k, 0, 8);
try {
DirectUpdateDoublesSketchR.checkDirectMemCapacity(k, 10000, 64);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
}
@Test
public void serializeDeserialize() {
int sizeBytes = DoublesSketch.getUpdatableStorageBytes(128, 2000);
WritableMemory mem = WritableMemory.writableWrap(new byte[sizeBytes]);
UpdateDoublesSketch sketch1 = DoublesSketch.builder().build(mem);
for (int i = 0; i < 1000; i++) {
sketch1.update(i);
}
UpdateDoublesSketch sketch2 = UpdateDoublesSketch.wrap(mem);
for (int i = 0; i < 1000; i++) {
sketch2.update(i + 1000);
}
assertEquals(sketch2.getMinItem(), 0.0);
assertEquals(sketch2.getMaxItem(), 1999.0);
assertEquals(sketch2.getQuantile(0.5), 1000.0, 10.0);
byte[] arr2 = sketch2.toByteArray(false);
assertEquals(arr2.length, sketch2.getSerializedSizeBytes());
DoublesSketch sketch3 = DoublesSketch.wrap(WritableMemory.writableWrap(arr2));
assertEquals(sketch3.getMinItem(), 0.0);
assertEquals(sketch3.getMaxItem(), 1999.0);
assertEquals(sketch3.getQuantile(0.5), 1000.0, 10.0);
}
@Test
public void mergeTest() {
DoublesSketch dqs1 = buildAndLoadDQS(128, 256);
DoublesSketch dqs2 = buildAndLoadDQS(128, 256, 256);
DoublesUnion union = DoublesUnion.builder().setMaxK(128).build();
union.union(dqs1);
union.union(dqs2);
DoublesSketch result = union.getResult();
double median = result.getQuantile(0.5);
println("Median: " + median);
assertEquals(median, 258.0, .05 * 258);
}
@Test
public void checkSimplePropagateCarryDirect() {
final int k = 16;
final int n = k * 2;
final int memBytes = DoublesSketch.getUpdatableStorageBytes(k, n);
final WritableMemory mem = WritableMemory.writableWrap(new byte[memBytes]);
final DoublesSketchBuilder bldr = DoublesSketch.builder();
final UpdateDoublesSketch ds = bldr.setK(k).build(mem);
for (int i = 1; i <= n; i++) { // 1 ... n
ds.update(i);
}
double last = 0.0;
for (int i = 0; i < k; i++) { //check the level 0
final double d = mem.getDouble((4 + (2 * k) + i) << 3);
assertTrue(d > 0);
assertTrue(d > last);
last = d;
}
//println(ds.toString(true, true));
}
@Test
public void getRankAndGetCdfConsistency() {
final int k = 128;
final int n = 1_000_000;
final int memBytes = DoublesSketch.getUpdatableStorageBytes(k, n);
final WritableMemory mem = WritableMemory.writableWrap(new byte[memBytes]);
final UpdateDoublesSketch sketch = DoublesSketch.builder().build(mem);
final double[] values = new double[n];
for (int i = 0; i < n; i++) {
sketch.update(i);
values[i] = i;
}
final double[] ranks = sketch.getCDF(values);
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i]));
}
}
static UpdateDoublesSketch buildAndLoadDQS(int k, int n) {
return buildAndLoadDQS(k, n, 0);
}
static UpdateDoublesSketch buildAndLoadDQS(int k, long n, int startV) {
UpdateDoublesSketch qs = buildDQS(k, n);
for (long i = 1; i <= n; i++) {
qs.update(startV + i);
}
return qs;
}
static UpdateDoublesSketch buildDQS(int k, long n) {
int cap = DoublesSketch.getUpdatableStorageBytes(k, n);
if (cap < (2 * k)) { cap = 2 * k; }
DoublesSketchBuilder bldr = new DoublesSketchBuilder();
bldr.setK(k);
UpdateDoublesSketch dqs = bldr.build(WritableMemory.writableWrap(new byte[cap]));
return dqs;
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
print(s+LS);
}
/**
* @param s value to print
*/
static void print(String s) {
//System.err.print(s); //disable here
}
}
| 2,492 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/QuantilesSketchCrossLanguageTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES;
import static org.apache.datasketches.common.TestUtil.CHECK_CPP_HISTORICAL_FILES;
import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES;
import static org.apache.datasketches.common.TestUtil.cppPath;
import static org.apache.datasketches.common.TestUtil.javaPath;
import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Comparator;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.TestUtil;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIterator;
import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIterator;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Serialize binary sketches to be tested by C++ code.
* Test deserialization of binary sketches serialized by C++ code.
*/
public class QuantilesSketchCrossLanguageTest {
private static final String LS = System.getProperty("line.separator");
@Test(groups = {GENERATE_JAVA_FILES})
public void generateDoublesSketch() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000};
for (final int n: nArr) {
final UpdateDoublesSketch sk = DoublesSketch.builder().build();
for (int i = 1; i <= n; i++) sk.update(i);
Files.newOutputStream(javaPath.resolve("quantiles_double_n" + n + "_java.sk")).write(sk.toByteArray());
}
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateItemsSketchWithStrings() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000};
for (final int n: nArr) {
final ItemsSketch<String> sk = ItemsSketch.getInstance(String.class, new Comparator<String>() {
@Override
public int compare(final String s1, final String s2) {
try {
final int i1 = Integer.parseInt(s1);
final int i2 = Integer.parseInt(s2);
return Integer.compare(i1,i2);
} catch (NumberFormatException e) {
throw new RuntimeException(e);
}
}
});
for (int i = 1; i <= n; i++) sk.update(Integer.toString(i));
if (n > 0) {
assertEquals(sk.getMinItem(), "1");
assertEquals(sk.getMaxItem(), Integer.toString(n));
}
Files.newOutputStream(javaPath.resolve("quantiles_string_n" + n + "_java.sk"))
.write(sk.toByteArray(new ArrayOfStringsSerDe()));
}
}
@Test(groups = {CHECK_CPP_FILES})
public void checkDoublesSketch() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] byteArr = Files.readAllBytes(cppPath.resolve("quantiles_double_n" + n + "_cpp.sk"));
final DoublesSketch sk = DoublesSketch.wrap(Memory.wrap(byteArr));
assertTrue(n == 0 ? sk.isEmpty() : !sk.isEmpty());
assertTrue(n > 128 ? sk.isEstimationMode() : !sk.isEstimationMode());
assertEquals(sk.getN(), n);
if (n > 0) {
assertEquals(sk.getMinItem(), 1);
assertEquals(sk.getMaxItem(), n);
QuantilesDoublesSketchIterator it = sk.iterator();
long weight = 0;
while(it.next()) {
assertTrue(it.getQuantile() >= sk.getMinItem());
assertTrue(it.getQuantile() <= sk.getMaxItem());
weight += it.getWeight();
}
assertEquals(weight, n);
}
}
}
@Test(groups = {CHECK_CPP_FILES})
public void checkItemsSketchWithStrings() throws IOException {
// sketch contains numbers in strings to make meaningful assertions
Comparator<String> numericOrder = new Comparator<String>() {
@Override
public int compare(final String s1, final String s2) {
try {
final int i1 = Integer.parseInt(s1);
final int i2 = Integer.parseInt(s2);
return Integer.compare(i1, i2);
} catch (NumberFormatException e) {
throw new RuntimeException(e);
}
}
};
final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] byteArr = Files.readAllBytes(cppPath.resolve("quantiles_string_n" + n + "_cpp.sk"));
final ItemsSketch<String> sk = ItemsSketch.getInstance(
String.class,
Memory.wrap(byteArr),
numericOrder,
new ArrayOfStringsSerDe()
);
assertTrue(n == 0 ? sk.isEmpty() : !sk.isEmpty());
assertTrue(n > 128 ? sk.isEstimationMode() : !sk.isEstimationMode());
assertEquals(sk.getN(), n);
if (n > 0) {
assertEquals(sk.getMinItem(), "1");
assertEquals(sk.getMaxItem(), Integer.toString(n));
QuantilesGenericSketchIterator<String> it = sk.iterator();
long weight = 0;
while(it.next()) {
assertTrue(numericOrder.compare(it.getQuantile(), sk.getMinItem()) >= 0);
assertTrue(numericOrder.compare(it.getQuantile(), sk.getMaxItem()) <= 0);
weight += it.getWeight();
}
assertEquals(weight, n);
}
}
}
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
//fullPath: sketches/src/test/resources/Qk128_n50_v0.3.0.sk
//Median2: 26.0
public void check030_50() {
int n = 50;
String ver = "0.3.0";
double expected = 26;
getAndCheck(ver, n, expected);
}
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
//fullPath: sketches/src/test/resources/Qk128_n1000_v0.3.0.sk
//Median2: 501.0
public void check030_1000() {
int n = 1000;
String ver = "0.3.0";
double expected = 501;
getAndCheck(ver, n, expected);
}
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
//fullPath: sketches/src/test/resources/Qk128_n50_v0.6.0.sk
//Median2: 26.0
public void check060_50() {
int n = 50;
String ver = "0.6.0";
double expected = 26;
getAndCheck(ver, n, expected);
}
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
//fullPath: sketches/src/test/resources/Qk128_n1000_v0.6.0.sk
//Median2: 501.0
public void check060_1000() {
int n = 1000;
String ver = "0.6.0";
double expected = 501;
getAndCheck(ver, n, expected);
}
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
//fullPath: sketches/src/test/resources/Qk128_n50_v0.8.0.sk
//Median2: 26.0
public void check080_50() {
int n = 50;
String ver = "0.8.0";
double expected = 26;
getAndCheck(ver, n, expected);
}
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
//fullPath: sketches/src/test/resources/Qk128_n1000_v0.8.0.sk
//Median2: 501.0
public void check080_1000() {
int n = 1000;
String ver = "0.8.0";
double expected = 501;
getAndCheck(ver, n, expected);
}
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
//fullPath: sketches/src/test/resources/Qk128_n50_v0.8.3.sk
//Median2: 26.0
public void check083_50() {
int n = 50;
String ver = "0.8.3";
double expected = 26;
getAndCheck(ver, n, expected);
}
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
//fullPath: sketches/src/test/resources/Qk128_n1000_v0.8.0.sk
//Median2: 501.0
public void check083_1000() {
int n = 1000;
String ver = "0.8.3";
double expected = 501;
getAndCheck(ver, n, expected);
}
private static void getAndCheck(String ver, int n, double quantile) {
DoublesSketch.rand.setSeed(131); //make deterministic
//create fileName
int k = 128;
double nf = 0.5;
String fileName = String.format("Qk%d_n%d_v%s.sk", k, n, ver);
println("fullName: "+ fileName);
println("Old Median: " + quantile);
//Read File bytes
byte[] byteArr = TestUtil.getResourceBytes(fileName);
Memory srcMem = Memory.wrap(byteArr);
// heapify as update sketch
DoublesSketch qs2 = UpdateDoublesSketch.heapify(srcMem);
//Test the quantile
double q2 = qs2.getQuantile(nf, EXCLUSIVE);
println("New Median: " + q2);
Assert.assertEquals(q2, quantile, 0.0);
// same thing with compact sketch
qs2 = CompactDoublesSketch.heapify(srcMem);
//Test the quantile
q2 = qs2.getQuantile(nf, EXCLUSIVE);
println("New Median: " + q2);
Assert.assertEquals(q2, quantile, 0.0);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
static void println(final Object o) {
if (o == null) { print(LS); }
else { print(o.toString() + LS); }
}
/**
* @param o value to print
*/
static void print(final Object o) {
if (o != null) {
//System.out.print(o.toString()); //disable here
}
}
}
| 2,493 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/DoublesSketchIteratorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIterator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DoublesSketchIteratorTest {
@Test
public void emptySketch() {
DoublesSketch sketch = DoublesSketch.builder().build();
QuantilesDoublesSketchIterator it = sketch.iterator();
Assert.assertFalse(it.next());
}
@Test
public void oneItemSketch() {
UpdateDoublesSketch sketch = DoublesSketch.builder().build();
sketch.update(0);
QuantilesDoublesSketchIterator it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getQuantile(), 0.0);
Assert.assertEquals(it.getWeight(), 1);
Assert.assertFalse(it.next());
}
@Test
public void bigSketches() {
for (int n = 1000; n < 100000; n += 2000) {
UpdateDoublesSketch sketch = DoublesSketch.builder().build();
for (int i = 0; i < n; i++) {
sketch.update(i);
}
QuantilesDoublesSketchIterator it = sketch.iterator();
int count = 0;
int weight = 0;
while (it.next()) {
count++;
weight += (int)it.getWeight();
}
Assert.assertEquals(count, sketch.getNumRetained());
Assert.assertEquals(weight, n);
}
}
}
| 2,494 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/HeapCompactDoublesSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.quantiles.ClassicUtil.LS;
import static org.apache.datasketches.quantiles.PreambleUtil.COMBINED_BUFFER;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class HeapCompactDoublesSketchTest {
@BeforeMethod
public void setUp() {
DoublesSketch.rand.setSeed(32749); // make sketches deterministic for testing
}
@Test
public void heapifyFromUpdateSketch() {
final int k = 4;
final int n = 45;
final UpdateDoublesSketch qs = buildAndLoadQS(k, n);
final byte[] qsBytes = qs.toByteArray();
final Memory qsMem = Memory.wrap(qsBytes);
final HeapCompactDoublesSketch compactQs = HeapCompactDoublesSketch.heapifyInstance(qsMem);
DoublesSketchTest.testSketchEquality(qs, compactQs);
assertNull(compactQs.getMemory());
}
@Test
public void createFromUnsortedUpdateSketch() {
final int k = 4;
final int n = 13;
final UpdateDoublesSketch qs = DoublesSketch.builder().setK(k).build();
for (int i = n; i > 0; --i) {
qs.update(i);
}
final HeapCompactDoublesSketch compactQs = HeapCompactDoublesSketch.createFromUpdateSketch(qs);
// don't expect equal but new base buffer should be sorted
checkBaseBufferIsSorted(compactQs);
}
@Test
public void heapifyFromCompactSketch() {
final int k = 8;
final int n = 177;
final UpdateDoublesSketch qs = buildAndLoadQS(k, n); // assuming reverse ordered inserts
final byte[] qsBytes = qs.compact().toByteArray();
final Memory qsMem = Memory.wrap(qsBytes);
final HeapCompactDoublesSketch compactQs = HeapCompactDoublesSketch.heapifyInstance(qsMem);
DoublesSketchTest.testSketchEquality(qs, compactQs);
}
@Test
public void checkHeapifyUnsortedCompactV2() {
final int k = 64;
final UpdateDoublesSketch qs = DoublesSketch.builder().setK(64).build();
for (int i = 0; i < (3 * k); ++i) {
qs.update(i);
}
assertEquals(qs.getBaseBufferCount(), k);
final byte[] sketchBytes = qs.toByteArray(true);
final WritableMemory mem = WritableMemory.writableWrap(sketchBytes);
// modify to make v2, clear compact flag, and insert a -1 in the middle of the base buffer
PreambleUtil.insertSerVer(mem, 2);
PreambleUtil.insertFlags(mem, 0);
final long tgtAddr = COMBINED_BUFFER + ((Double.BYTES * (long)k) / 2);
mem.putDouble(tgtAddr, -1.0);
assert mem.getDouble(tgtAddr - Double.BYTES) > mem.getDouble(tgtAddr);
// ensure the heapified base buffer is sorted
final HeapCompactDoublesSketch qs2 = HeapCompactDoublesSketch.heapifyInstance(mem);
checkBaseBufferIsSorted(qs2);
}
@Test
public void checkEmpty() {
final int k = PreambleUtil.DEFAULT_K;
final UpdateDoublesSketch qs1 = buildAndLoadQS(k, 0);
final byte[] byteArr = qs1.compact().toByteArray();
final byte[] byteArr2 = qs1.toByteArray(true);
final Memory mem = Memory.wrap(byteArr);
final HeapCompactDoublesSketch qs2 = HeapCompactDoublesSketch.heapifyInstance(mem);
assertTrue(qs2.isEmpty());
assertEquals(byteArr.length, qs1.getSerializedSizeBytes());
assertEquals(byteArr, byteArr2);
try { qs2.getQuantile(0.5); fail(); } catch (IllegalArgumentException e) { }
try { qs2.getQuantiles(new double[] {0.0, 0.5, 1.0}); fail(); } catch (IllegalArgumentException e) { }
try { qs2.getRank(0); fail(); } catch (IllegalArgumentException e) { }
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMemTooSmall1() {
final Memory mem = Memory.wrap(new byte[7]);
HeapCompactDoublesSketch.heapifyInstance(mem);
}
static void checkBaseBufferIsSorted(HeapCompactDoublesSketch qs) {
final double[] combinedBuffer = qs.getCombinedBuffer();
final int bbCount = qs.getBaseBufferCount();
for (int i = 1; i < bbCount; ++i) {
assert combinedBuffer[i - 1] <= combinedBuffer[i];
}
}
static UpdateDoublesSketch buildAndLoadQS(final int k, final int n) {
return buildAndLoadQS(k, n, 0);
}
static UpdateDoublesSketch buildAndLoadQS(final int k, final int n, final int startV) {
final UpdateDoublesSketch qs = DoublesSketch.builder().setK(k).build();
for (int i = 1; i <= n; i++) {
qs.update(startV + i);
}
return qs;
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
print("PRINTING: " + this.getClass().getName() + LS);
}
/**
* @param s value to print
*/
static void println(final String s) {
print(s + LS);
}
/**
* @param s value to print
*/
static void print(final String s) {
//System.err.print(s); //disable here
}
}
| 2,495 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/DoublesUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.quantiles.HeapUpdateDoublesSketchTest.buildAndLoadQS;
import static org.apache.datasketches.quantiles.ClassicUtil.LS;
import org.testng.annotations.Test;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
public class DoublesUtilTest {
@Test
public void checkPrintMemData() {
final int k = 16;
final int n = 1000;
final DoublesSketch qs = buildAndLoadQS(k,n);
byte[] byteArr = qs.toByteArray(false);
Memory mem = Memory.wrap(byteArr);
println(DoublesUtil.memToString(true, true, mem));
byteArr = qs.toByteArray(true);
mem = Memory.wrap(byteArr);
println(DoublesUtil.memToString(true, true, mem));
}
@Test
public void checkPrintMemData2() {
final int k = PreambleUtil.DEFAULT_K;
final int n = 0;
final DoublesSketch qs = buildAndLoadQS(k,n);
final byte[] byteArr = qs.toByteArray();
final Memory mem = Memory.wrap(byteArr);
println(DoublesUtil.memToString(true, true, mem));
}
@Test
public void checkCopyToHeap() {
final int k = 128;
final int n = 400;
// HeapUpdateDoublesSketch
final HeapUpdateDoublesSketch huds = (HeapUpdateDoublesSketch) buildAndLoadQS(k, n);
final HeapUpdateDoublesSketch target1 = DoublesUtil.copyToHeap(huds);
DoublesSketchTest.testSketchEquality(huds, target1);
// DirectUpdateDoublesSketch
final WritableMemory mem1 = WritableMemory.writableWrap(huds.toByteArray());
final DirectUpdateDoublesSketch duds = (DirectUpdateDoublesSketch) UpdateDoublesSketch.wrap(mem1);
final HeapUpdateDoublesSketch target2 = DoublesUtil.copyToHeap(duds);
DoublesSketchTest.testSketchEquality(huds, duds);
DoublesSketchTest.testSketchEquality(duds, target2);
// HeapCompactDoublesSketch
final CompactDoublesSketch hcds = huds.compact();
final HeapUpdateDoublesSketch target3 = DoublesUtil.copyToHeap(hcds);
DoublesSketchTest.testSketchEquality(huds, hcds);
DoublesSketchTest.testSketchEquality(hcds, target3);
// DirectCompactDoublesSketch
final Memory mem2 = Memory.wrap(hcds.toByteArray());
final DirectCompactDoublesSketch dcds = (DirectCompactDoublesSketch) DoublesSketch.wrap(mem2);
final HeapUpdateDoublesSketch target4 = DoublesUtil.copyToHeap(dcds);
DoublesSketchTest.testSketchEquality(huds, dcds);
DoublesSketchTest.testSketchEquality(dcds, target4);
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
print(s + LS);
}
/**
* @param s value to print
*/
static void print(final String s) {
//System.out.print(s); //disable here
}
}
| 2,496 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/KolmogorovSmirnovTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.Random;
import org.testng.annotations.Test;
public class KolmogorovSmirnovTest {
@Test
public void checkDisjointDistribution() {
final int k = 256;
final UpdateDoublesSketch s1 = DoublesSketch.builder().setK(k).build();
final UpdateDoublesSketch s2 = DoublesSketch.builder().setK(k).build();
final Random rand = new Random(1);
final int n = (3 * k) - 1;
for (int i = 0; i < n; ++i) {
final double x = rand.nextGaussian();
s1.update(x + 500);
s2.update(x);
}
//assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s2), 1.0, 1E-6);
println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s2));
}
@Test
public void checkIdenticalDistribution() {
final int k = 256;
final UpdateDoublesSketch s1 = DoublesSketch.builder().setK(k).build();
final Random rand = new Random(1);
final int n = (3 * k) - 1;
for (int i = 0; i < n; ++i) {
final double x = rand.nextGaussian();
s1.update(x);
}
assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s1), 0.0, 0.0);
println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s1));
}
@Test
public void checkSameDistributionDifferentSketches() {
final int k = 256;
final UpdateDoublesSketch s1 = DoublesSketch.builder().setK(k).build();
final UpdateDoublesSketch s2 = DoublesSketch.builder().setK(k).build();
final Random rand = new Random(1);
final int n = (3 * k) - 1;
for (int i = 0; i < n; ++i) {
final double x = rand.nextGaussian();
s1.update(x);
s2.update(x);
}
assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s2), 0, .01);
println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s2));
}
@Test
public void mediumResolution() {
final int k = 2048;
final UpdateDoublesSketch s1 = DoublesSketch.builder().setK(k).build();
final UpdateDoublesSketch s2 = DoublesSketch.builder().setK(k).build();
final double tgtPvalue = .05;
final Random rand = new Random(1);
final int n = (3 * k) - 1;
for (int i = 0; i < n; ++i) {
final double x = rand.nextGaussian();
s1.update(x + .05);
s2.update(x);
}
double D = KolmogorovSmirnov.computeKSDelta(s1, s2);
double thresh = KolmogorovSmirnov.computeKSThreshold(s1, s2, tgtPvalue);
final boolean reject = KolmogorovSmirnov.kolmogorovSmirnovTest(s1, s2, tgtPvalue);
println("pVal = " + tgtPvalue + "\nK = " + k + "\nD = " + D + "\nTh = " + thresh
+ "\nNull Hypoth Rejected = " + reject);
assertFalse(reject);
}
@Test
public void highResolution() {
final int k = 8192;
final UpdateDoublesSketch s1 = DoublesSketch.builder().setK(k).build();
final UpdateDoublesSketch s2 = DoublesSketch.builder().setK(k).build();
final double tgtPvalue = .05;
final Random rand = new Random(1);
final int n = (3 * k) - 1;
for (int i = 0; i < n; ++i) {
final double x = rand.nextGaussian();
s1.update(x + .05);
s2.update(x);
}
double D = KolmogorovSmirnov.computeKSDelta(s1, s2);
double thresh = KolmogorovSmirnov.computeKSThreshold(s1, s2, tgtPvalue);
final boolean reject = KolmogorovSmirnov.kolmogorovSmirnovTest(s1, s2, tgtPvalue);
println("pVal = " + tgtPvalue + "\nK = " + k + "\nD = " + D + "\nTh = " + thresh
+ "\nNull Hypoth Rejected = " + reject);
assertTrue(reject);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,497 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/SerDeCompatibilityTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import java.util.Comparator;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfItemsSerDe;
import org.apache.datasketches.memory.Memory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SerDeCompatibilityTest {
private static final ArrayOfItemsSerDe<Double> serDe = new ArrayOfDoublesSerDe();
@Test
public void itemsToDoubles() {
final ItemsSketch<Double> sketch1 = ItemsSketch.getInstance(Double.class, Comparator.naturalOrder());
for (int i = 1; i <= 500; i++) { sketch1.update((double) i); }
final byte[] bytes = sketch1.toByteArray(serDe);
final UpdateDoublesSketch sketch2;
sketch2 = UpdateDoublesSketch.heapify(Memory.wrap(bytes));
for (int i = 501; i <= 1000; i++) { sketch2.update(i); }
Assert.assertEquals(sketch2.getN(), 1000);
Assert.assertTrue(sketch2.getNumRetained() < 1000);
Assert.assertEquals(sketch2.getMinItem(), 1.0);
Assert.assertEquals(sketch2.getMaxItem(), 1000.0);
// based on ~1.7% normalized rank error for this particular case
Assert.assertEquals(sketch2.getQuantile(0.5), 500.0, 17);
}
@Test
public void doublesToItems() {
final UpdateDoublesSketch sketch1 = DoublesSketch.builder().build(); //SerVer = 3
for (int i = 1; i <= 500; i++) { sketch1.update(i); }
final CompactDoublesSketch cs = sketch1.compact();
DoublesSketchTest.testSketchEquality(sketch1, cs);
//final byte[] bytes = sketch1.compact().toByteArray(); // must be compact
final byte[] bytes = cs.toByteArray(); // must be compact
//reconstruct with ItemsSketch
final ItemsSketch<Double> sketch2 = ItemsSketch.getInstance(Double.class, Memory.wrap(bytes),
Comparator.naturalOrder(), serDe);
for (int i = 501; i <= 1000; i++) { sketch2.update((double) i); }
Assert.assertEquals(sketch2.getN(), 1000);
Assert.assertTrue(sketch2.getNumRetained() < 1000);
Assert.assertEquals((double)sketch2.getMinItem(), 1.0);
Assert.assertEquals((double)sketch2.getMaxItem(), 1000.0);
// based on ~1.7% normalized rank error for this particular case
Assert.assertEquals(sketch2.getQuantile(0.5), 500.0, 17);
}
}
| 2,498 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/quantiles/DirectCompactDoublesSketchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.quantiles;
import static org.apache.datasketches.quantiles.ClassicUtil.LS;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DirectCompactDoublesSketchTest {
@BeforeMethod
public void setUp() {
DoublesSketch.rand.setSeed(32749); // make sketches deterministic for testing
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void wrapFromUpdateSketch() {
final int k = 4;
final int n = 27;
final UpdateDoublesSketch qs = HeapUpdateDoublesSketchTest.buildAndLoadQS(k, n);
final byte[] qsBytes = qs.toByteArray();
final Memory qsMem = Memory.wrap(qsBytes);
DirectCompactDoublesSketch.wrapInstance(qsMem);
fail();
}
@Test
public void createFromUnsortedUpdateSketch() {
final int k = 4;
final int n = 13;
final UpdateDoublesSketch qs = DoublesSketch.builder().setK(k).build();
for (int i = n; i > 0; --i) {
qs.update(i);
}
final WritableMemory dstMem = WritableMemory.writableWrap(new byte[qs.getCurrentCompactSerializedSizeBytes()]);
final DirectCompactDoublesSketch compactQs
= DirectCompactDoublesSketch.createFromUpdateSketch(qs, dstMem);
// don't expect equal but new base buffer should be sorted
final double[] combinedBuffer = compactQs.getCombinedBuffer();
final int bbCount = compactQs.getBaseBufferCount();
for (int i = 1; i < bbCount; ++i) {
assert combinedBuffer[i - 1] < combinedBuffer[i];
}
}
@Test
public void wrapFromCompactSketch() {
final int k = 8;
final int n = 177;
final DirectCompactDoublesSketch qs = buildAndLoadDCQS(k, n); // assuming ordered inserts
final byte[] qsBytes = qs.toByteArray();
final Memory qsMem = Memory.wrap(qsBytes);
final DirectCompactDoublesSketch compactQs = DirectCompactDoublesSketch.wrapInstance(qsMem);
DoublesSketchTest.testSketchEquality(qs, compactQs);
assertEquals(qsBytes.length, compactQs.getSerializedSizeBytes());
final double[] combinedBuffer = compactQs.getCombinedBuffer();
assertEquals(combinedBuffer.length, compactQs.getCombinedBufferItemCapacity());
}
@Test
public void wrapEmptyCompactSketch() {
final CompactDoublesSketch s1 = DoublesSketch.builder().build().compact();
final Memory mem
= Memory.wrap(ByteBuffer.wrap(s1.toByteArray()).order(ByteOrder.nativeOrder()));
final DoublesSketch s2 = DoublesSketch.wrap(mem);
assertTrue(s2.isEmpty());
assertEquals(s2.getN(), 0);
assertTrue(Double.isNaN(s2.isEmpty() ? Double.NaN : s2.getMinItem()));
assertTrue(Double.isNaN(s2.isEmpty() ? Double.NaN : s2.getMaxItem()));
}
@Test
public void checkEmpty() {
final int k = PreambleUtil.DEFAULT_K;
final DirectCompactDoublesSketch qs1 = buildAndLoadDCQS(k, 0);
try { qs1.getQuantile(0.5); fail(); } catch (IllegalArgumentException e) {}
try { qs1.getQuantiles(new double[] {0.0, 0.5, 1.0}); fail(); } catch (IllegalArgumentException e) {}
final double[] combinedBuffer = qs1.getCombinedBuffer();
assertEquals(combinedBuffer.length, 2 * k);
assertNotEquals(combinedBuffer.length, qs1.getCombinedBufferItemCapacity());
}
@Test
public void checkCheckDirectMemCapacity() {
final int k = 128;
DirectCompactDoublesSketch.checkDirectMemCapacity(k, (2 * k) - 1, (4 + (2 * k)) * 8);
DirectCompactDoublesSketch.checkDirectMemCapacity(k, (2 * k) + 1, (4 + (3 * k)) * 8);
DirectCompactDoublesSketch.checkDirectMemCapacity(k, 0, 8);
try {
DirectCompactDoublesSketch.checkDirectMemCapacity(k, 10000, 64);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMemTooSmall() {
final Memory mem = Memory.wrap(new byte[7]);
HeapCompactDoublesSketch.heapifyInstance(mem);
}
static DirectCompactDoublesSketch buildAndLoadDCQS(final int k, final int n) {
return buildAndLoadDCQS(k, n, 0);
}
static DirectCompactDoublesSketch buildAndLoadDCQS(final int k, final int n, final int startV) {
final UpdateDoublesSketch qs = DoublesSketch.builder().setK(k).build();
for (int i = 1; i <= n; i++) {
qs.update(startV + i);
}
final byte[] byteArr = new byte[qs.getCurrentCompactSerializedSizeBytes()];
final WritableMemory mem = WritableMemory.writableWrap(byteArr);
return (DirectCompactDoublesSketch) qs.compact(mem);
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
print("PRINTING: " + this.getClass().getName() + LS);
}
static void println(final String s) {
print(s + LS);
}
/**
* @param s value to print
*/
static void print(final String s) {
//System.err.print(s); //disable here
}
}
| 2,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.