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/hll/HllArrayTest.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.hll;
import static org.apache.datasketches.hll.TgtHllType.HLL_4;
import static org.apache.datasketches.hll.TgtHllType.HLL_6;
import static org.apache.datasketches.hll.TgtHllType.HLL_8;
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.SketchesStateException;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class HllArrayTest {
@Test
public void checkCompositeEst() {
testComposite(4, HLL_8, 1000);
testComposite(5, HLL_8, 1000);
testComposite(6, HLL_8, 1000);
testComposite(13, HLL_8, 10000);
}
@Test
public void checkBigHipGetRse() {
HllSketch sk = new HllSketch(13, HLL_8);
for (int i = 0; i < 10000; i++) {
sk.update(i);
}
}
private static void testComposite(int lgK, TgtHllType tgtHllType, int n) {
Union u = new Union(lgK);
HllSketch sk = new HllSketch(lgK, tgtHllType);
for (int i = 0; i < n; i++) {
u.update(i);
sk.update(i);
}
u.update(sk); //merge
HllSketch res = u.getResult(HLL_8);
res.getCompositeEstimate();
}
@Test
public void toByteArray_Heapify() {
int lgK = 4;
int u = 8;
toByteArrayHeapify(lgK, HLL_4, u, true);
toByteArrayHeapify(lgK, HLL_6, u, false);
toByteArrayHeapify(lgK, HLL_8, u, true);
lgK = 16;
u = (((1 << (lgK - 3))*3)/4) + 100;
toByteArrayHeapify(lgK, HLL_4, u, false);
toByteArrayHeapify(lgK, HLL_6, u, true);
toByteArrayHeapify(lgK, HLL_8, u, false);
lgK = 21;
u = (((1 << (lgK - 3))*3)/4) + 1000;
toByteArrayHeapify(lgK, HLL_4, u, true);
toByteArrayHeapify(lgK, HLL_6, u, false);
toByteArrayHeapify(lgK, HLL_8, u, true);
}
private static void toByteArrayHeapify(int lgK, TgtHllType tgtHllType, int u, boolean direct) {
HllSketch sk1;
WritableMemory wmem = null;
if (direct) {
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, tgtHllType);
wmem = WritableMemory.allocate(bytes);
sk1 = new HllSketch(lgK, tgtHllType, wmem);
} else {
sk1 = new HllSketch(lgK, tgtHllType);
}
for (int i = 0; i < u; i++) {
sk1.update(i);
}
assert sk1.hllSketchImpl instanceof AbstractHllArray;
if (sk1.hllSketchImpl instanceof HllArray) {
assertFalse(sk1.hllSketchImpl.isMemory());
assertFalse(sk1.isSameResource(wmem));
} else { //DirectHllArray
assertTrue(sk1.hllSketchImpl.isMemory());
assertTrue(sk1.isSameResource(wmem));
}
//sk1.update(u);
double est1 = sk1.getEstimate();
assertEquals(est1, u, u * .03);
assertEquals(sk1.getHipEstimate(), est1, 0.0);
//misc calls
sk1.hllSketchImpl.putEmptyFlag(false);
sk1.hllSketchImpl.putRebuildCurMinNumKxQFlag(true);
sk1.hllSketchImpl.putRebuildCurMinNumKxQFlag(false);
byte[] byteArray = sk1.toCompactByteArray();
HllSketch sk2 = HllSketch.heapify(byteArray);
double est2 = sk2.getEstimate();
assertEquals(est2, est1, 0.0);
byteArray = sk1.toUpdatableByteArray();
sk2 = HllSketch.heapify(byteArray);
est2 = sk2.getEstimate();
assertEquals(est2, est1, 0.0);
sk1.reset();
assertEquals(sk1.getEstimate(), 0.0, 0.0);
}
@Test
public void checkHll4Exceptions() {
int lgK = 4;
int k = 1 << lgK;
HllSketch skH4 = new HllSketch(lgK, HLL_4);
for (int i = 0; i < k; i++) { skH4.update(i); }
AbstractHllArray absHllArr = (AbstractHllArray)skH4.hllSketchImpl;
try {
absHllArr.updateSlotNoKxQ(0,0);
fail();
}
catch (SketchesStateException e) { } //OK
}
@Test
public void checkDHll4Exceptions() {
int lgK = 4;
int k = 1 << lgK;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, HLL_4);
HllSketch skD4 = new HllSketch(lgK, HLL_4, WritableMemory.allocate(bytes));
for (int i = 0; i < k; i++) { skD4.update(i); }
AbstractHllArray absHllArr = (AbstractHllArray)skD4.hllSketchImpl;
try {
absHllArr.updateSlotNoKxQ(0,0);
fail();
}
catch (SketchesStateException e) { } //OK
}
@Test
public void checkHll6Exceptions() {
int lgK = 4;
int k = 1 << lgK;
HllSketch skH6 = new HllSketch(lgK, HLL_6);
for (int i = 0; i < k; i++) { skH6.update(i); }
AbstractHllArray absHllArr = (AbstractHllArray)skH6.hllSketchImpl;
try {
absHllArr.getNibble(0);
fail();
}
catch (SketchesStateException e) { } //OK
try {
absHllArr.putNibble(0,0);
fail();
}
catch (SketchesStateException e) { } //OK
try {
absHllArr.updateSlotNoKxQ(0,0);
fail();
}
catch (SketchesStateException e) { } //OK
}
@Test
public void checkDHll6Exceptions() {
int lgK = 4;
int k = 1 << lgK;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, HLL_6);
HllSketch skD6 = new HllSketch(lgK, HLL_6, WritableMemory.allocate(bytes));
for (int i = 0; i < k; i++) { skD6.update(i); }
AbstractHllArray absHllArr = (AbstractHllArray)skD6.hllSketchImpl;
try {
absHllArr.getNibble(0);
fail();
}
catch (SketchesStateException e) { } //OK
try {
absHllArr.putNibble(0,0);
fail();
}
catch (SketchesStateException e) { } //OK
try {
absHllArr.updateSlotNoKxQ(0,0);
fail();
}
catch (SketchesStateException e) { } //OK
}
@Test
public void checkHll8Exceptions() {
int lgK = 4;
int k = 1 << lgK;
HllSketch skH6 = new HllSketch(lgK, HLL_8);
for (int i = 0; i < k; i++) { skH6.update(i); }
AbstractHllArray absHllArr = (AbstractHllArray)skH6.hllSketchImpl;
try {
absHllArr.getNibble(0);
fail();
}
catch (SketchesStateException e) { } //OK
try {
absHllArr.putNibble(0,0);
fail();
}
catch (SketchesStateException e) { } //OK
}
@Test
public void checkDHll8Exceptions() {
int lgK = 4;
int k = 1 << lgK;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, HLL_8);
HllSketch skD6 = new HllSketch(lgK, HLL_8, WritableMemory.allocate(bytes));
for (int i = 0; i < k; i++) { skD6.update(i); }
AbstractHllArray absHllArr = (AbstractHllArray)skD6.hllSketchImpl;
try {
absHllArr.getNibble(0);
fail();
}
catch (SketchesStateException e) { } //OK
try {
absHllArr.putNibble(0,0);
fail();
}
catch (SketchesStateException e) { } //OK
}
@Test
public void checkIsCompact() {
HllSketch sk = new HllSketch(4);
for (int i = 0; i < 8; i++) { sk.update(i); }
assertFalse(sk.isCompact());
}
@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,300 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/DirectCouponListTest.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.hll;
import static org.apache.datasketches.hll.PreambleUtil.LG_ARR_BYTE;
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 org.testng.annotations.Test;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableHandle;
import org.apache.datasketches.memory.WritableMemory;
/**
* @author Lee Rhodes
*/
public class DirectCouponListTest {
@Test
public void promotionTests() {
//true means convert to compact array
promotions(8, 7, TgtHllType.HLL_8, true, CurMode.LIST);
promotions(8, 7, TgtHllType.HLL_8, false, CurMode.LIST);
promotions(8, 24, TgtHllType.HLL_8, true, CurMode.SET);
promotions(8, 24, TgtHllType.HLL_8, false, CurMode.SET);
promotions(8, 25, TgtHllType.HLL_8, true, CurMode.HLL);
promotions(8, 25, TgtHllType.HLL_8, false, CurMode.HLL);
promotions(8, 25, TgtHllType.HLL_6, true, CurMode.HLL);
promotions(8, 25, TgtHllType.HLL_6, false, CurMode.HLL);
promotions(8, 25, TgtHllType.HLL_4, true, CurMode.HLL);
promotions(8, 25, TgtHllType.HLL_4, false, CurMode.HLL);
promotions(4, 7, TgtHllType.HLL_8, true, CurMode.LIST);
promotions(4, 7, TgtHllType.HLL_8, false, CurMode.LIST);
promotions(4, 8, TgtHllType.HLL_8, true, CurMode.HLL);
promotions(4, 8, TgtHllType.HLL_8, false, CurMode.HLL);
promotions(4, 8, TgtHllType.HLL_6, true, CurMode.HLL);
promotions(4, 8, TgtHllType.HLL_6, false, CurMode.HLL);
promotions(4, 8, TgtHllType.HLL_4, true, CurMode.HLL);
promotions(4, 8, TgtHllType.HLL_4, false, CurMode.HLL);
promotions(4, 25, TgtHllType.HLL_4, true, CurMode.HLL);
promotions(4, 25, TgtHllType.HLL_4, false, CurMode.HLL);
}
private static void promotions(int lgConfigK, int n, TgtHllType tgtHllType, boolean compact,
CurMode tgtMode) {
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType);
HllSketch hllSketch;
//println("DIRECT");
byte[] barr1;
WritableMemory wmem = null;
try (WritableHandle hand = WritableMemory.allocateDirect(bytes)) {
wmem = hand.getWritable();
//byte[] byteArr = new byte[bytes];
//WritableMemory wmem = WritableMemory.wrap(byteArr);
hllSketch = new HllSketch(lgConfigK, tgtHllType, wmem);
assertTrue(hllSketch.isEmpty());
for (int i = 0; i < n; i++) {
hllSketch.update(i);
}
//println(hllSketch.toString(true, true, false, false));
assertFalse(hllSketch.isEmpty());
assertEquals(hllSketch.getCurMode(), tgtMode);
assertTrue(hllSketch.isMemory());
assertTrue(hllSketch.isOffHeap());
assertTrue(hllSketch.isSameResource(wmem));
//convert direct sketch to byte[]
barr1 = (compact) ? hllSketch.toCompactByteArray() : hllSketch.toUpdatableByteArray();
//println(PreambleUtil.toString(barr1));
hllSketch.reset();
assertTrue(hllSketch.isEmpty());
} catch (final Exception e) {
throw new RuntimeException(e);
}
//println("HEAP");
HllSketch hllSketch2 = new HllSketch(lgConfigK, tgtHllType);
for (int i = 0; i < n; i++) {
hllSketch2.update(i);
}
//println(hllSketch2.toString(true, true, false, false));
//println(PreambleUtil.toString(barr2));
assertEquals(hllSketch2.getCurMode(), tgtMode);
assertFalse(hllSketch2.isMemory());
assertFalse(hllSketch2.isOffHeap());
assertFalse(hllSketch2.isSameResource(wmem));
byte[] barr2 = (compact) ? hllSketch2.toCompactByteArray() : hllSketch2.toUpdatableByteArray();
assertEquals(barr1.length, barr2.length, barr1.length + ", " + barr2.length);
//printDiffs(barr1, barr2);
assertEquals(barr1, barr2);
}
@SuppressWarnings("unused") //only used when above printlns are enabled.
private static void printDiffs(byte[] arr1, byte[] arr2) {
int len1 = arr1.length;
int len2 = arr2.length;
int minLen = Math.min(len1, len2);
for (int i = 0; i < minLen; i++) {
int v1 = arr1[i] & 0XFF;
int v2 = arr2[i] & 0XFF;
if (v1 == v2) { continue; }
println(i + ", " + v1 + ", " + v2);
}
}
@Test
public void checkCouponToByteArray() {
int lgK = 8;
TgtHllType type = TgtHllType.HLL_8;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = new HllSketch(lgK, type, wmem);
int i;
for (i = 0; i < 7; i++) { sk.update(i); } //LIST
//toCompactMemArr from compact mem
byte[] compactByteArr = sk.toCompactByteArray();
Memory compactMem = Memory.wrap(compactByteArr);
HllSketch skCompact = HllSketch.wrap(compactMem);
byte[] compactByteArr2 = skCompact.toCompactByteArray();
assertEquals(compactByteArr2, compactByteArr);
//now check to UpdatableByteArr from compact mem
byte[] updatableByteArr = sk.toUpdatableByteArray();
byte[] updatableByteArr2 = skCompact.toUpdatableByteArray();
assertEquals(updatableByteArr2.length, updatableByteArr.length);
assertEquals(skCompact.getEstimate(), sk.getEstimate());
sk.update(i); //SET
//toCompactMemArr from compact mem
compactByteArr = sk.toCompactByteArray();
compactMem = Memory.wrap(compactByteArr);
skCompact = HllSketch.wrap(compactMem);
compactByteArr2 = skCompact.toCompactByteArray();
assertEquals(compactByteArr2, compactByteArr);
//now check to UpdatableByteArr from compact mem
updatableByteArr = sk.toUpdatableByteArray();
updatableByteArr2 = skCompact.toUpdatableByteArray();
assertEquals(updatableByteArr2.length, updatableByteArr.length);
assertEquals(skCompact.getEstimate(), sk.getEstimate());
}
@Test
public void checkDirectGetCouponIntArr() {
int lgK = 8;
TgtHllType type = TgtHllType.HLL_8;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = new HllSketch(lgK, type, wmem);
AbstractCoupons absCoup = (AbstractCoupons)sk.hllSketchImpl;
assertNull(absCoup.getCouponIntArr());
}
@Test
public void checkBasicGetLgCouponArrInts() {
int lgK = 8;
TgtHllType type = TgtHllType.HLL_8;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = new HllSketch(lgK, type, wmem);
for (int i = 0; i < 7; i++) { sk.update(i); }
assertEquals(sk.getCurMode(), CurMode.LIST);
assertEquals(((AbstractCoupons) sk.hllSketchImpl).getLgCouponArrInts(), 3);
sk.update(7);
assertEquals(sk.getCurMode(), CurMode.SET);
assertEquals(((AbstractCoupons) sk.hllSketchImpl).getLgCouponArrInts(), 5);
sk.reset();
for (int i = 0; i < 7; i++) { sk.update(i); }
byte lgArr = wmem.getByte(LG_ARR_BYTE);
wmem.putByte(LG_ARR_BYTE, (byte) 0); //corrupt to 0
assertEquals(((AbstractCoupons) sk.hllSketchImpl).getLgCouponArrInts(), 3);
wmem.putByte(LG_ARR_BYTE, lgArr); //put correct value back
sk.update(7);
assertEquals(sk.getCurMode(), CurMode.SET);
assertEquals(sk.hllSketchImpl.curMode, CurMode.SET);
wmem.putByte(LG_ARR_BYTE, (byte) 0); //corrupt to 0 again
assertEquals(((AbstractCoupons) sk.hllSketchImpl).getLgCouponArrInts(), 5);
}
@Test
public void checkHeapifyGetLgCouponArrInts() {
int lgK = 8;
TgtHllType type = TgtHllType.HLL_8;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = new HllSketch(lgK, type, wmem);
for (int i = 0; i < 8; i++) { sk.update(i); }
assertEquals(sk.getCurMode(), CurMode.SET);
double est1 = sk.getEstimate();
wmem.putByte(LG_ARR_BYTE, (byte) 0); //corrupt to 0
HllSketch sk2 = HllSketch.heapify(wmem);
double est2 = sk2.getEstimate();
assertEquals(est2, est1, 0.0);
//println(sk2.toString(true, true, true, true));
//println(PreambleUtil.toString(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,301 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/IsomorphicTest.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.hll;
import static org.apache.datasketches.hll.CurMode.HLL;
import static org.apache.datasketches.hll.CurMode.LIST;
import static org.apache.datasketches.hll.CurMode.SET;
import static org.apache.datasketches.hll.TgtHllType.HLL_4;
import static org.apache.datasketches.hll.TgtHllType.HLL_6;
import static org.apache.datasketches.hll.TgtHllType.HLL_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
@SuppressWarnings("unused")
public class IsomorphicTest {
long v = 0;
@Test
//Merges a type1 to an empty union (heap, HLL_8), and gets result as type1, checks binary equivalence
public void isomorphicUnionUpdatableHeap() {
for (int lgK = 4; lgK <= 21; lgK++) { //All LgK
for (int cm = 0; cm <= 2; cm++) { //List, Set, Hll
if ((lgK < 8) && (cm == 1)) { continue; } //lgk < 8 list transistions directly to HLL
CurMode curMode = CurMode.fromOrdinal(cm);
for (int t = 0; t <= 2; t++) { //HLL_4, HLL_6, HLL_8
TgtHllType tgtHllType1 = TgtHllType.fromOrdinal(t);
HllSketch sk1 = buildHeapSketch(lgK, tgtHllType1, curMode);
byte[] sk1bytes = sk1.toUpdatableByteArray(); //UPDATABLE
Union union = buildHeapUnion(lgK, null); //UNION
union.update(sk1);
HllSketch sk2 = union.getResult(tgtHllType1);
byte[] sk2bytes = sk2.toUpdatableByteArray(); //UPDATABLE
String comb = "LgK=" + lgK + ", CurMode=" + curMode.toString() + ", Type:" + tgtHllType1;
checkArrays(sk1bytes, sk2bytes, comb, false);
}
}
}
}
@Test
//Merges a type1 to an empty union (heap, HLL_8), and gets result as type1, checks binary equivalence
public void isomorphicUnionCompactHeap() {
for (int lgK = 4; lgK <= 21; lgK++) { //All LgK
for (int cm = 0; cm <= 2; cm++) { //List, Set, Hll
if ((lgK < 8) && (cm == 1)) { continue; } //lgk < 8 list transistions directly to HLL
CurMode curMode = CurMode.fromOrdinal(cm);
for (int t = 0; t <= 2; t++) { //HLL_4, HLL_6, HLL_8
TgtHllType tgtHllType1 = TgtHllType.fromOrdinal(t);
HllSketch sk1 = buildHeapSketch(lgK, tgtHllType1, curMode);
byte[] sk1bytes = sk1.toCompactByteArray(); //COMPACT
Union union = buildHeapUnion(lgK, null); //UNION
union.update(sk1);
HllSketch sk2 = union.getResult(tgtHllType1);
byte[] sk2bytes = sk2.toCompactByteArray(); //COMPACT
String comb = "LgK=" + lgK + ", CurMode=" + curMode.toString() + ", Type:" + tgtHllType1;
checkArrays(sk1bytes, sk2bytes, comb, false);
}
}
}
}
@Test
//Converts a type1 to a different type and converts back to type1 to check binary equivalence.
public void isomorphicCopyAsUpdatableHeap() {
for (int lgK = 4; lgK <= 21; lgK++) { //All LgK
for (int cm = 0; cm <= 2; cm++) { //List, Set, Hll
if ((lgK < 8) && (cm == 1)) { continue; } //lgk < 8 list transistions directly to HLL
CurMode curMode = CurMode.fromOrdinal(cm);
for (int t1 = 0; t1 <= 2; t1++) { //HLL_4, HLL_6, HLL_8
TgtHllType tgtHllType1 = TgtHllType.fromOrdinal(t1);
HllSketch sk1 = buildHeapSketch(lgK, tgtHllType1, curMode);
byte[] sk1bytes = sk1.toUpdatableByteArray(); //UPDATABLE
for (int t2 = 0; t2 <= 2; t2++) { //HLL_4, HLL_6, HLL_8
if (t2 == t1) { continue; }
TgtHllType tgtHllType2 = TgtHllType.fromOrdinal(t2);
HllSketch sk2 = sk1.copyAs(tgtHllType2); //COPY AS
HllSketch sk1B = sk2.copyAs(tgtHllType1); //COPY AS
byte[] sk1Bbytes = sk1B.toUpdatableByteArray(); //UPDATABLE
String comb = "LgK= " + lgK + ", CurMode= " + curMode.toString()
+ ", Type1: " + tgtHllType1 + ", Type2: " + tgtHllType2;
checkArrays(sk1bytes, sk1Bbytes, comb, false);
}
}
}
}
}
@Test
//Converts a type1 to a different type and converts back to type1 to check binary equivalence.
public void isomorphicCopyAsCompactHeap() {
for (int lgK = 4; lgK <= 21; lgK++) { //All LgK
for (int cm = 0; cm <= 2; cm++) { //List, Set, Hll
if ((lgK < 8) && (cm == 1)) { continue; } //lgk < 8 list transistions directly to HLL
CurMode curMode = CurMode.fromOrdinal(cm);
for (int t1 = 0; t1 <= 2; t1++) { //HLL_4, HLL_6, HLL_8
TgtHllType tgtHllType1 = TgtHllType.fromOrdinal(t1);
HllSketch sk1 = buildHeapSketch(lgK, tgtHllType1, curMode);
byte[] sk1bytes = sk1.toCompactByteArray(); //COMPACT
for (int t2 = 0; t2 <= 2; t2++) { //HLL_4, HLL_6, HLL_8
if (t2 == t1) { continue; }
TgtHllType tgtHllType2 = TgtHllType.fromOrdinal(t2);
HllSketch sk2 = sk1.copyAs(tgtHllType2); //COPY AS
HllSketch sk3 = sk2.copyAs(tgtHllType1); //COPY AS
byte[] sk3bytes = sk3.toCompactByteArray(); //COMPACT
String comb = "LgK= " + lgK + ", CurMode= " + curMode.toString()
+ ", Type1: " + tgtHllType1 + ", Type2: " + tgtHllType2;
checkArrays(sk1bytes, sk3bytes, comb, false);
}
}
}
}
}
@Test
//Compares two HLL to HLL merges. The input sketch varies by tgtHllType.
//The LgKs can be equal or the source sketch is one larger.
//The result of the union is converted to HLL_8 and checked between different combinations of
//heap, memory for binary equivalence.
public void isomorphicHllMerges() {
for (int uLgK = 4; uLgK <= 20; uLgK++) { //All LgK
int skLgK = uLgK;
for (int t1 = 0; t1 <= 2; t1++) { //HLL_4, HLL_6, HLL_8
TgtHllType tgtHllType = TgtHllType.fromOrdinal(t1);
innerLoop(uLgK, skLgK, tgtHllType);
}
skLgK = uLgK + 1;
for (int t1 = 0; t1 <= 2; t1++) { //HLL_4, HLL_6, HLL_8
TgtHllType tgtHllType = TgtHllType.fromOrdinal(t1);
innerLoop(uLgK, skLgK, tgtHllType);
}
}
}
private static void innerLoop(int uLgK, int skLgK, TgtHllType tgtHllType) {
Union u;
HllSketch sk, skOut;
//CASE 1 Heap Union, Heap sketch
u = buildHeapUnionHllMode(uLgK, 0);
sk = buildHeapSketchHllMode(skLgK, tgtHllType, 1 << uLgK);
u.update(sk);
byte[] bytesOut1 = u.getResult(HLL_8).toUpdatableByteArray();
//CASE 2 Heap Union, Memory sketch
u = buildHeapUnionHllMode(uLgK, 0);
sk = buildMemorySketchHllMode(skLgK, tgtHllType, 1 << uLgK);
u.update(sk);
byte[] bytesOut2 = u.getResult(HLL_8).toUpdatableByteArray();
//println("Uheap/SkHeap HIP: " + bytesToDouble(bytesOut1, 8)); //HipAccum
//println("Uheap/SkMemory HIP: " + bytesToDouble(bytesOut2, 8)); //HipAccum
String comb = "uLgK: " + uLgK + ", skLgK: " + skLgK
+ ", SkType: " + tgtHllType.toString()
+ ", Case1: Heap Union, Heap sketch; Case2: /Heap Union, Memory sketch";
checkArrays(bytesOut1, bytesOut2, comb, false);
//CASE 3 Offheap Union, Heap sketch
u = buildMemoryUnionHllMode(uLgK, 0);
sk = buildHeapSketchHllMode(skLgK, tgtHllType, 1 << uLgK);
u.update(sk);
byte[] bytesOut3 = u.getResult(HLL_8).toUpdatableByteArray();
//println("Uheap/SkMemory HIP: " + bytesToDouble(bytesOut2, 8)); //HipAccum
//println("Umemory/SkHeap HIP: " + bytesToDouble(bytesOut3, 8)); //HipAccum
comb = "LgK: " + uLgK + ", skLgK: " + skLgK
+ ", SkType: " + tgtHllType.toString()
+ ", Case2: Heap Union, Memory sketch; Case3: /Memory Union, Heap sketch";
checkArrays(bytesOut2, bytesOut3, comb, false);
//Case 4 Memory Union, Memory sketch
u = buildMemoryUnionHllMode(uLgK, 0);
sk = buildMemorySketchHllMode(skLgK, tgtHllType, 1 << uLgK);
u.update(sk);
byte[] bytesOut4 = u.getResult(HLL_8).toUpdatableByteArray();
comb = "LgK: " + uLgK + ", skLgK: " + skLgK
+ ", SkType: " + tgtHllType.toString()
+ ", Case2: Heap Union, Memory sketch; Case4: /Memory Union, Memory sketch";
checkArrays(bytesOut2, bytesOut4, comb, false);
}
@Test
//Creates a binary reference: HLL_8 merged with union, HLL_8 result binary.
//Case 1: HLL_6 merged with a union, HLL_8 result binary compared with the reference.
//Case 2: HLL_4 merged with a union, Hll_8 result binary compared with the reference.
//Both Case 1 and 2 should differ in the binary output compared with the reference only for the
//HllAccum register.
public void isomorphicHllMerges2() {
byte[] bytesOut8, bytesOut6, bytesOut4;
String comb;
Union u;
HllSketch sk;
for (int lgK = 4; lgK <= 4; lgK++) { //All LgK
u = buildHeapUnionHllMode(lgK, 0);
sk = buildHeapSketchHllMode(lgK, HLL_8, 1 << lgK);
u.update(sk);
bytesOut8 = u.getResult(HLL_8).toUpdatableByteArray(); //The reference
u = buildHeapUnionHllMode(lgK, 0);
sk = buildHeapSketchHllMode(lgK, HLL_6, 1 << lgK);
u.update(sk);
bytesOut6 = u.getResult(HLL_8).toUpdatableByteArray();//should be identical except for HllAccum
comb = "LgK: " + lgK + ", SkType: HLL_6, Compared with SkType HLL_8";
checkArrays(bytesOut8, bytesOut6, comb, false);
u = buildHeapUnionHllMode(lgK, 0);
sk = buildHeapSketchHllMode(lgK, HLL_4, 1 << lgK);
u.update(sk);
bytesOut4 = u.getResult(HLL_8).toUpdatableByteArray();//should be identical except for HllAccum
comb = "LgK: " + lgK + ", SkType: HLL_4, Compared with SkType HLL_8";
checkArrays(bytesOut8, bytesOut4, comb, false);
}
}
private static void checkArrays(byte[] sk1, byte[] sk2, String comb, boolean omitHipAccum) {
int len = sk1.length;
if (len != sk2.length) {
println("Sketch images not the same length: " + comb);
return;
}
print(comb + ": ");
for (int i = 0; i < len; i++) {
if (omitHipAccum && (i >= 8) && (i <= 15)) { continue; }
if (sk1[i] == sk2[i]) { continue; }
print(i + " ");
fail();
}
println("");
}
//BUILDERS
private Union buildHeapUnion(int lgMaxK, CurMode curMode) {
Union u = new Union(lgMaxK);
int n = (curMode == null) ? 0 : getN(lgMaxK, curMode);
for (int i = 0; i < n; i++) { u.update(i + v); }
v += n;
return u;
}
private Union buildMemoryUnion(int lgMaxK, CurMode curMode) {
final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgMaxK, TgtHllType.HLL_8);
WritableMemory wmem = WritableMemory.allocate(bytes);
Union u = new Union(lgMaxK, wmem);
int n = (curMode == null) ? 0 : getN(lgMaxK, curMode);
for (int i = 0; i < n; i++) { u.update(i + v); }
v += n;
return u;
}
private HllSketch buildHeapSketch(int lgK, TgtHllType tgtHllType, CurMode curMode) {
HllSketch sk = new HllSketch(lgK, tgtHllType);
int n = (curMode == null) ? 0 : getN(lgK, curMode);
for (int i = 0; i < n; i++) { sk.update(i + v); }
v += n;
return sk;
}
private HllSketch buildMemorySketch(int lgK, TgtHllType tgtHllType, CurMode curMode) {
final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK,tgtHllType);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = new HllSketch(lgK, tgtHllType, wmem);
int n = (curMode == null) ? 0 : getN(lgK, curMode);
for (int i = 0; i < n; i++) { sk.update(i + v); }
v += n;
return sk;
}
private static Union buildHeapUnionHllMode(int lgMaxK, int startN) {
Union u = new Union(lgMaxK);
int n = getN(lgMaxK, HLL);
for (int i = 0; i < n; i++) { u.update(i + startN); }
return u;
}
private static Union buildMemoryUnionHllMode(int lgMaxK, int startN) {
final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgMaxK, TgtHllType.HLL_8);
WritableMemory wmem = WritableMemory.allocate(bytes);
Union u = new Union(lgMaxK, wmem);
int n = getN(lgMaxK, HLL);
for (int i = 0; i < n; i++) { u.update(i + startN); }
return u;
}
private static HllSketch buildHeapSketchHllMode(int lgK, TgtHllType tgtHllType, int startN) {
HllSketch sk = new HllSketch(lgK, tgtHllType);
int n = getN(lgK, HLL);
for (int i = 0; i < n; i++) { sk.update(i + startN); }
return sk;
}
private static HllSketch buildMemorySketchHllMode(int lgK, TgtHllType tgtHllType, int startN) {
final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK,tgtHllType);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = new HllSketch(lgK, tgtHllType, wmem);
int n = getN(lgK, HLL);
for (int i = 0; i < n; i++) { sk.update(i + startN); }
return sk;
}
//if lgK >= 8, curMode != SET!
private static int getN(int lgK, CurMode curMode) {
if (curMode == LIST) { return 4; }
if (curMode == SET) { return 1 << (lgK - 4); }
return ((lgK < 8) && (curMode == HLL)) ? (1 << lgK) : 1 << (lgK - 3);
}
@Test
public void checkCurMinConversion() {
TgtHllType hll8 = HLL_8;
TgtHllType hll4 = HLL_4;
for (int lgK = 4; lgK <= 21; lgK++) {
HllSketch sk8 = new HllSketch(lgK, hll8);
//The Coupon Collector Problem predicts that all slots will be filled by k Log(k).
int n = (1 << lgK) * lgK;
for (int i = 0; i < n; i++) { sk8.update(i); }
double est8 = sk8.getEstimate();
AbstractHllArray aharr8 = (AbstractHllArray)sk8.hllSketchImpl;
int curMin8 = aharr8.getCurMin();
int numAtCurMin8 = aharr8.getNumAtCurMin();
HllSketch sk4 = sk8.copyAs(hll4);
AbstractHllArray aharr4 = (AbstractHllArray)sk4.hllSketchImpl;
int curMin4 = ((AbstractHllArray)sk4.hllSketchImpl).getCurMin();
int numAtCurMin4 =aharr4.getNumAtCurMin();
double est4 = sk4.getEstimate();
assertEquals(est4, est8, 0.0);
assertEquals(curMin4, 1);
//println("Est 8 = " + est8 + ", CurMin = " + curMin8 + ", #CurMin + " + numAtCurMin8);
//println("Est 4 = " + est4 + ", CurMin = " + curMin4 + ", #CurMin + " + numAtCurMin4);
}
}
private static double bytesToDouble(byte[] arr, int offset) {
long v = 0;
for (int i = offset; i < (offset + 8); i++) {
v |= (arr[i] & 0XFFL) << (i * 8);
}
return Double.longBitsToDouble(v);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param o value to print
*/
static void println(Object o) {
print(o.toString() + "\n");
}
/**
* @param o value to print
*/
static void print(Object o) {
//System.out.print(o.toString()); //disable here
}
/**
* @param fmt format
* @param args arguments
*/
static void printf(String fmt, Object...args) {
//System.out.printf(fmt, args); //disable here
}
}
| 2,302 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/DirectAuxHashMapTest.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.hll;
import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS;
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 java.util.HashMap;
import org.apache.datasketches.common.SketchesStateException;
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;
/**
* @author Lee Rhodes
*/
public class DirectAuxHashMapTest {
@Test
public void checkGrow() {
int lgConfigK = 4;
TgtHllType tgtHllType = TgtHllType.HLL_4;
int n = 8; //put lgConfigK == 4 into HLL mode
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType);
HllSketch hllSketch;
try (WritableHandle handle = WritableMemory.allocateDirect(bytes,
ByteOrder.nativeOrder(), new DefaultMemoryRequestServer())) {
WritableMemory wmem = handle.getWritable();
hllSketch = new HllSketch(lgConfigK, tgtHllType, wmem);
for (int i = 0; i < n; i++) {
hllSketch.update(i);
}
hllSketch.couponUpdate(HllUtil.pair(7, 15)); //mock extreme values
hllSketch.couponUpdate(HllUtil.pair(8, 15));
hllSketch.couponUpdate(HllUtil.pair(9, 15));
//println(hllSketch.toString(true, true, true, true));
DirectHllArray dha = (DirectHllArray) hllSketch.hllSketchImpl;
assertEquals(dha.getAuxHashMap().getLgAuxArrInts(), 2);
assertTrue(hllSketch.isMemory());
assertTrue(hllSketch.isOffHeap());
assertTrue(hllSketch.isSameResource(wmem));
//Check heapify
byte[] byteArray = hllSketch.toCompactByteArray();
HllSketch hllSketch2 = HllSketch.heapify(byteArray);
HllArray ha = (HllArray) hllSketch2.hllSketchImpl;
assertEquals(ha.getAuxHashMap().getLgAuxArrInts(), 2);
assertEquals(ha.getAuxHashMap().getAuxCount(), 3);
//Check wrap
byteArray = hllSketch.toUpdatableByteArray();
WritableMemory wmem2 = WritableMemory.writableWrap(byteArray);
hllSketch2 = HllSketch.writableWrap(wmem2);
//println(hllSketch2.toString(true, true, true, true));
DirectHllArray dha2 = (DirectHllArray) hllSketch2.hllSketchImpl;
assertEquals(dha2.getAuxHashMap().getLgAuxArrInts(), 2);
assertEquals(dha2.getAuxHashMap().getAuxCount(), 3);
//Check grow to on-heap
hllSketch.couponUpdate(HllUtil.pair(10, 15)); //puts it over the edge, must grow
//println(hllSketch.toString(true, true, true, true));
dha = (DirectHllArray) hllSketch.hllSketchImpl;
assertEquals(dha.getAuxHashMap().getLgAuxArrInts(), 3);
assertEquals(dha.getAuxHashMap().getAuxCount(), 4);
assertTrue(hllSketch.isMemory());
assertFalse(hllSketch.isOffHeap());
assertFalse(hllSketch.isSameResource(wmem));
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void checkDiffToByteArr() {
int lgK = 12; //this combination should create an Aux with ~18 exceptions
int lgU = 19;
TgtHllType type = TgtHllType.HLL_4;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type);
byte[] memByteArr = new byte[bytes];
WritableMemory wmem = WritableMemory.writableWrap(memByteArr);
HllSketch heapSk = new HllSketch(lgK, type);
HllSketch dirSk = new HllSketch(lgK, type, wmem);
for (int i = 0; i < (1 << lgU); i++) {
heapSk.update(i);
dirSk.update(i); //problem starts here.
}
AbstractHllArray heapHllArr = (AbstractHllArray) heapSk.hllSketchImpl;
AbstractHllArray dirHllArr = (AbstractHllArray) dirSk.hllSketchImpl;
assert dirHllArr instanceof DirectHllArray;
AuxHashMap heapAux = heapHllArr.getAuxHashMap();
assert heapAux instanceof HeapAuxHashMap;
AuxHashMap dirAux = dirHllArr.getAuxHashMap();
assert dirAux instanceof DirectAuxHashMap; //TOOD FAILS!
println("HeapAuxCount: " + heapAux.getAuxCount());
println("DirAuxCount: " + dirAux.getAuxCount());
int heapCurMin = heapHllArr.getCurMin();
int dirCurMin = dirHllArr.getCurMin();
println("HeapCurMin: " + heapCurMin);
println("DirCurMin: " + dirCurMin);
PairIterator auxItr;
auxItr = heapHllArr.getAuxIterator();
println("\nHeap Pairs");
//println(itr.getHeader());
while (auxItr.nextValid()) {
println("" + auxItr.getPair());
}
auxItr = dirHllArr.getAuxIterator();
println("\nDirect Pairs");
//println(itr.getHeader());
while (auxItr.nextValid()) {
println(""+ auxItr.getPair());
}
PairIterator hllItr;
hllItr = heapSk.iterator();
println("Heap HLL arr");
println(hllItr.getHeader());
while (hllItr.nextValid()) {
if ((hllItr.getValue() - heapCurMin) > 14) {
println(hllItr.getString() + ", " + hllItr.getPair());
}
}
hllItr = dirSk.iterator();
println("Direct HLL arr");
println(hllItr.getHeader());
while (hllItr.nextValid()) {
if ((hllItr.getValue() - dirCurMin) > 14) {
println(hllItr.getString() + ", " + hllItr.getPair());
}
}
byte[] heapImg = heapSk.toUpdatableByteArray();
Memory heapImgMem = Memory.wrap(heapImg);
byte[] dirImg = dirSk.toUpdatableByteArray();
Memory dirImgMem = Memory.wrap(dirImg);
println("heapLen: " + heapImg.length + ", dirLen: " + dirImg.length
+ ", memObjLen: "+memByteArr.length);
int auxStart = 40 + (1 << (lgK -1));
println("AuxStart: " + auxStart);
println(String.format("%14s%14s%14s", "dir wmem", "heap to b[]", "direct to b[]"));
for (int i = auxStart; i < heapImg.length; i += 4) {
println(String.format("%14d%14d%14d",
wmem.getInt(i), heapImgMem.getInt(i), dirImgMem.getInt(i)));
assert memByteArr[i] == heapImg[i];
assert heapImg[i] == dirImg[i] : "i: " + i;
}
assertEquals(heapImg, dirImg);
}
@Test
public void exerciseHeapAndDirectAux() {
initSketchAndMap(true, true); //direct, compact
initSketchAndMap(false, true); //heap, compact
initSketchAndMap(true, false); //direct, updatable
initSketchAndMap(false, false); //heap, updatable
}
static void initSketchAndMap(boolean direct, boolean compact) {
int lgK = 15; //this combination should create an Aux with ~18 exceptions
int lgU = 20;
println("HLL_4, lgK: " + lgK + ", lgU: " + lgU);
HashMap<Integer, Integer> map = new HashMap<>();
//create sketch
HllSketch sketch;
if (direct) {
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, TgtHllType.HLL_4);
WritableMemory wmem = WritableMemory.allocate(bytes);
sketch = new HllSketch(lgK, TgtHllType.HLL_4, wmem);
} else {
sketch = new HllSketch(lgK, TgtHllType.HLL_4);
}
for (int i = 0; i < (1 << lgU); i++) { sketch.update(i); }
//check Ser Bytes
assertEquals(sketch.getUpdatableSerializationBytes(), 40 + (1 << (lgK - 1))
+ (4 << LG_AUX_ARR_INTS[lgK]) );
//extract the auxHashMap entries into a HashMap for easy checking
//extract direct aux iterator
AbstractHllArray absDirectHllArr = (AbstractHllArray) sketch.hllSketchImpl;
//the auxHashMap must exist for this test
AuxHashMap auxMap = absDirectHllArr.getAuxHashMap();
int auxCount = auxMap.getAuxCount();
assertEquals(auxMap.getCompactSizeBytes(), auxCount << 2);
int auxArrInts = 1 << auxMap.getLgAuxArrInts();
assertEquals(auxMap.getUpdatableSizeBytes(), auxArrInts << 2);
PairIterator itr = absDirectHllArr.getAuxIterator();
println("Source Aux Array.");
println(itr.getHeader());
while (itr.nextValid()) {
map.put(itr.getSlot(), itr.getValue()); //create the aux reference map
println(itr.getString());
}
double est = sketch.getEstimate();
println("\nHLL Array of original sketch: should match Source Aux Array.");
checkHllArr(sketch, map); //check HLL arr consistencies
//serialize the direct sk as compact
byte[] byteArr = (compact) ? sketch.toCompactByteArray() : sketch.toUpdatableByteArray();
//Heapify the byteArr image & check estimate
HllSketch heapSk = HllSketch.heapify(Memory.wrap(byteArr));
assertEquals(heapSk.getEstimate(), est, 0.0);
println("\nAux Array of heapified serialized sketch.");
checkAux(heapSk, map); //check Aux consistencies
println("\nHLL Array of heapified serialized sketch.");
checkHllArr(heapSk, map); //check HLL arr consistencies
//Wrap the image as read-only & check estimate
HllSketch wrapSk = HllSketch.wrap(Memory.wrap(byteArr));
assertEquals(wrapSk.getEstimate(), est, 0.0);
println("\nAux Array of wrapped RO serialized sketch.");
checkAux(wrapSk, map);
println("\nHLL Array of wrapped RO serialized sketch.");
checkHllArr(wrapSk, map);
println(wrapSk.toString(false, false, true, true));
}
//check HLL array consistencies with the map
static void checkHllArr(HllSketch sk, HashMap<Integer,Integer> map) {
//extract aux iterator, which must exist for this test
AbstractHllArray absHllArr = (AbstractHllArray) sk.hllSketchImpl;
int curMin = absHllArr.getCurMin();
//println("CurMin: " + curMin);
PairIterator hllArrItr = sk.iterator();
println(hllArrItr.getHeader());
while (hllArrItr.nextValid()) {
final int hllArrVal = hllArrItr.getValue();
if ((hllArrItr.getValue() - curMin) > 14) {
final int mapVal = map.get(hllArrItr.getSlot());
println(hllArrItr.getString());
assertEquals(hllArrVal, mapVal);
}
}
}
//Check Aux consistencies to the map
static void checkAux(HllSketch sk, HashMap<Integer,Integer> map) {
AbstractHllArray absHllArr = (AbstractHllArray) sk.hllSketchImpl;
//extract aux iterator, which must exist for this test
PairIterator heapAuxItr = absHllArr.getAuxIterator();
println(heapAuxItr.getHeader());
while (heapAuxItr.nextValid()) {
final int afterVal = heapAuxItr.getValue();
if (afterVal > 14) {
println(heapAuxItr.getString());
int auxSlot = heapAuxItr.getSlot();
assert map.containsKey(auxSlot);
final int beforeVal = map.get(heapAuxItr.getSlot());
assertEquals(afterVal, beforeVal);
}
}
}
@Test
public void checkDirectReadOnlyCompactAux() {
int lgK = 15; //this combination should create an Aux with ~18 exceptions
int lgU = 20;
HllSketch sk = new HllSketch(lgK, TgtHllType.HLL_4);
for (int i = 0; i < (1 << lgU); i++) { sk.update(i); }
}
@Test
public void checkMustReplace() {
int lgK = 7;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, TgtHllType.HLL_4);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = new HllSketch(lgK, TgtHllType.HLL_4, wmem);
for (int i = 0; i < 25; i++) { sk.update(i); }
DirectHllArray dHllArr = (DirectHllArray) sk.hllSketchImpl;
AuxHashMap map = dHllArr.getNewAuxHashMap();
map.mustAdd(100, 5);
int val = map.mustFindValueFor(100);
assertEquals(val, 5);
map.mustReplace(100, 10);
val = map.mustFindValueFor(100);
assertEquals(val, 10);
assertTrue(map.isMemory());
assertFalse(map.isOffHeap());
assertNull(map.copy());
assertNull(map.getAuxIntArr());
try {
map.mustAdd(100, 12);
fail();
} catch (SketchesStateException e) {
//expected
}
try {
map.mustFindValueFor(101);
fail();
} catch (SketchesStateException e) {
//expected
}
try {
map.mustReplace(101, 5);
fail();
} catch (SketchesStateException e) {
//expected
}
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,303 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/BaseHllSketchTest.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.hll;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
import org.apache.datasketches.memory.WritableMemory;
import java.nio.ByteBuffer;
/**
* @author Lee Rhodes
*
*/
public class BaseHllSketchTest {
@Test
public void checkUpdateTypes() {
HllSketch sk = new HllSketch(10);
byte[] byteArr = null;
sk.update(byteArr);
sk.update(new byte[] {});
sk.update(new byte[] {0, 1, 2, 3});
ByteBuffer byteBuf = null;
sk.update(byteBuf);
sk.update(ByteBuffer.wrap(new byte[] {}));
sk.update(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}));
char[] charArr = null;
sk.update(charArr);
sk.update(new char[] {});
sk.update(new char[] {0, 1, 2, 3});
sk.update(1.0);
sk.update(-0.0);
int[] intArr = null;
sk.update(intArr);
sk.update(new int[] {});
sk.update(new int[] {0, 1, 2, 3});
sk.update(1234L);
long[] longArr = null;
sk.update(longArr);
sk.update(new long[] {});
sk.update(new long[] {0, 1, 2, 3});
String s = null;
sk.update(s);
s = "";
sk.update(s);
sk.update("1234");
Union u = new Union(10);
byte[] byteArr1 = null;
u.update(byteArr1);
u.update(new byte[] {});
u.update(new byte[] {0, 1, 2, 3});
ByteBuffer byteBuf1 = null;
u.update(byteBuf1);
u.update(ByteBuffer.wrap(new byte[] {}));
u.update(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}));
char[] charArr1 = null;
u.update(charArr1);
u.update(new char[] {});
u.update(new char[] {0, 1, 2, 3});
u.update(1.0);
u.update(-0.0);
int[] intArr1 = null;
u.update(intArr1);
u.update(new int[] {});
u.update(new int[] {0, 1, 2, 3});
u.update(1234L);
long[] longArr1 = null;
u.update(longArr1);
u.update(new long[] {});
u.update(new long[] {0, 1, 2, 3});
String s1 = null;
u.update(s1);
s1 = "";
u.update(s);
u.update("1234");
}
@Test
public void misc() {
HllSketch sk = new HllSketch(10, TgtHllType.HLL_4);
assertTrue(sk.isEstimationMode());
sk.reset();
assertEquals(BaseHllSketch.getSerializationVersion(), PreambleUtil.SER_VER);
WritableMemory wmem = WritableMemory.writableWrap(sk.toCompactByteArray());
assertEquals(BaseHllSketch.getSerializationVersion(wmem), PreambleUtil.SER_VER);
}
@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,304 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/HllSketchCrossLanguageTest.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.hll;
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.apache.datasketches.hll.TgtHllType.HLL_4;
import static org.apache.datasketches.hll.TgtHllType.HLL_6;
import static org.apache.datasketches.hll.TgtHllType.HLL_8;
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.testng.annotations.Test;
/**
* Serialize binary sketches to be tested by C++ code.
* Test deserialization of binary sketches serialized by C++ code.
*/
public class HllSketchCrossLanguageTest {
@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 HllSketch hll4 = new HllSketch(HllSketch.DEFAULT_LG_K, HLL_4);
final HllSketch hll6 = new HllSketch(HllSketch.DEFAULT_LG_K, HLL_6);
final HllSketch hll8 = new HllSketch(HllSketch.DEFAULT_LG_K, HLL_8);
for (int i = 0; i < n; i++) hll4.update(i);
for (int i = 0; i < n; i++) hll6.update(i);
for (int i = 0; i < n; i++) hll8.update(i);
Files.newOutputStream(javaPath.resolve("hll4_n" + n + "_java.sk")).write(hll4.toCompactByteArray());
Files.newOutputStream(javaPath.resolve("hll6_n" + n + "_java.sk")).write(hll6.toCompactByteArray());
Files.newOutputStream(javaPath.resolve("hll8_n" + n + "_java.sk")).write(hll8.toCompactByteArray());
}
}
@Test(groups = {CHECK_CPP_FILES})
public void hll4() throws IOException {
final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("hll4_n" + n + "_cpp.sk"));
final HllSketch sketch = HllSketch.heapify(Memory.wrap(bytes));
assertEquals(sketch.getLgConfigK(), 12);
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
assertEquals(sketch.getEstimate(), n, n * 0.02);
}
}
@Test(groups = {CHECK_CPP_FILES})
public void hll6() throws IOException {
final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("hll6_n" + n + "_cpp.sk"));
final HllSketch sketch = HllSketch.heapify(Memory.wrap(bytes));
assertEquals(sketch.getLgConfigK(), 12);
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
assertEquals(sketch.getEstimate(), n, n * 0.02);
}
}
@Test(groups = {CHECK_CPP_FILES})
public void hll8() throws IOException {
final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("hll8_n" + n + "_cpp.sk"));
final HllSketch sketch = HllSketch.heapify(Memory.wrap(bytes));
assertEquals(sketch.getLgConfigK(), 12);
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
assertEquals(sketch.getEstimate(), n, n * 0.02);
}
}
}
| 2,305 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/DirectHllSketchTest.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.hll;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.HashSet;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesReadOnlyException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class DirectHllSketchTest {
@Test
public void checkNoWriteAccess() {
noWriteAccess(TgtHllType.HLL_4, 7);
noWriteAccess(TgtHllType.HLL_4, 24);
noWriteAccess(TgtHllType.HLL_4, 25);
noWriteAccess(TgtHllType.HLL_6, 25);
noWriteAccess(TgtHllType.HLL_8, 25);
}
private static void noWriteAccess(TgtHllType tgtHllType, int n) {
int lgConfigK = 8;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = new HllSketch(lgConfigK, tgtHllType, wmem);
for (int i = 0; i < n; i++) { sk.update(i); }
HllSketch sk2 = HllSketch.wrap(wmem);
try {
sk2.update(1);
fail();
} catch (SketchesReadOnlyException e) {
//expected
}
}
@Test
public void checkCompactToUpdatable() {
int lgConfigK = 15;
int n = 1 << 20;
TgtHllType type = TgtHllType.HLL_4;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, type);
WritableMemory wmem = WritableMemory.allocate(bytes);
//create first direct updatable sketch
HllSketch sk = new HllSketch(lgConfigK, type, wmem);
for (int i = 0; i < n; i++) { sk.update(i); }
//Create compact byte arr
byte[] cByteArr = sk.toCompactByteArray(); //16496 = (auxStart)16424 + 72
Memory cmem = Memory.wrap(cByteArr);
//Create updatable byte arr
byte[] uByteArr = sk.toUpdatableByteArray(); //16936 = (auxStart)16424 + 512
//get auxStart and auxArrInts for updatable
AbstractHllArray absArr = (AbstractHllArray)sk.hllSketchImpl;
int auxStart = absArr.auxStart;
int auxArrInts = 1 << absArr.getAuxHashMap().getLgAuxArrInts();
//hash set to check result
HashSet<Integer> set = new HashSet<>();
//create HashSet of values
PairIterator itr = new IntMemoryPairIterator(uByteArr, auxStart, auxArrInts, lgConfigK);
//println(itr.getHeader());
int validCount = 0;
while (itr.nextValid()) {
set.add(itr.getPair());
validCount++;
//println(itr.getString());
}
//Wrap the compact image as read-only
HllSketch sk2 = HllSketch.wrap(cmem); //cmem is 16496
//serialize it to updatable image
byte[] uByteArr2 = sk2.toUpdatableByteArray();
PairIterator itr2 = new IntMemoryPairIterator(uByteArr2, auxStart, auxArrInts, lgConfigK);
//println(itr2.getHeader());
int validCount2 = 0;
while (itr2.nextValid()) {
boolean exists = set.contains(itr2.getPair());
if (exists) { validCount2++; }
//println(itr2.getString());
}
assertEquals(validCount, validCount2);
}
@Test
public void checkPutKxQ1_Misc() {
int bytes = HllSketch.getMaxUpdatableSerializationBytes(4, TgtHllType.HLL_4);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = new HllSketch(4, TgtHllType.HLL_4, wmem);
for (int i = 0; i < 8; i++) { sk.update(i); }
assertTrue(sk.getCurMode() == CurMode.HLL);
AbstractHllArray absArr = (AbstractHllArray)sk.hllSketchImpl;
absArr.putKxQ1(1.0);
assertEquals(absArr.getKxQ1(), 1.0);
absArr.putKxQ1(0.0);
Memory mem = wmem;
HllSketch sk2 = HllSketch.wrap(mem);
try {
sk2.reset();
fail();
} catch (SketchesArgumentException e) {
//expected
}
}
@Test
public void checkToCompactByteArr() {
int bytes = HllSketch.getMaxUpdatableSerializationBytes(4, TgtHllType.HLL_4);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = new HllSketch(4, TgtHllType.HLL_4, wmem);
for (int i = 0; i < 8; i++) { sk.update(i); }
byte[] compByteArr = sk.toCompactByteArray();
Memory compMem = Memory.wrap(compByteArr);
HllSketch sk2 = HllSketch.wrap(compMem);
byte[] compByteArr2 = sk2.toCompactByteArray();
assertEquals(compByteArr2, compByteArr);
}
@Test
public void checkToUpdatableByteArr() {
int bytes = HllSketch.getMaxUpdatableSerializationBytes(4, TgtHllType.HLL_4);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = new HllSketch(4, TgtHllType.HLL_4, wmem);
for (int i = 0; i < 8; i++) { sk.update(i); }
byte[] udByteArr = sk.toUpdatableByteArray();
byte[] compByteArr = sk.toCompactByteArray();
Memory compMem = Memory.wrap(compByteArr);
HllSketch sk2 = HllSketch.wrap(compMem);
byte[] udByteArr2 = sk2.toUpdatableByteArray();
assertEquals(udByteArr2, udByteArr);
}
@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,306 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/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.hll;
import static org.apache.datasketches.hll.PreambleUtil.EMPTY_FLAG_MASK;
import static org.apache.datasketches.hll.PreambleUtil.FAMILY_BYTE;
import static org.apache.datasketches.hll.PreambleUtil.SER_VER_BYTE;
import static org.apache.datasketches.hll.PreambleUtil.extractFlags;
import static org.apache.datasketches.hll.PreambleUtil.insertFamilyId;
import static org.apache.datasketches.hll.PreambleUtil.insertPreInts;
import static org.apache.datasketches.hll.PreambleUtil.insertSerVer;
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.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class PreambleUtilTest {
//@Test
public void preambleToString() { // Check Visually
int bytes = HllSketch.getMaxUpdatableSerializationBytes(8, TgtHllType.HLL_4);
byte[] byteArr1 = new byte[bytes];
WritableMemory wmem1 = WritableMemory.writableWrap(byteArr1);
HllSketch sk = new HllSketch(8, TgtHllType.HLL_4, wmem1);
byte[] byteArr2 = sk.toCompactByteArray();
WritableMemory wmem2 = WritableMemory.writableWrap(byteArr2);
assertEquals(sk.getCurMode(), CurMode.LIST);
assertTrue(sk.isEmpty());
String s = HllSketch.toString(byteArr2); //empty sketch output
println(s);
println("LgArr: " + PreambleUtil.extractLgArr(wmem2));
println("Empty: " + PreambleUtil.extractEmptyFlag(wmem2));
println("Serialization Bytes: " + wmem2.getCapacity());
for (int i = 0; i < 7; i++) { sk.update(i); }
byteArr2 = sk.toCompactByteArray();
wmem2 = WritableMemory.writableWrap(byteArr2);
assertEquals(sk.getCurMode(), CurMode.LIST);
assertFalse(sk.isEmpty());
s = HllSketch.toString(byteArr2);
println(s);
println("LgArr: " + PreambleUtil.extractLgArr(wmem2));
println("Empty: " + PreambleUtil.extractEmptyFlag(wmem2));
println("Serialization Bytes: " + wmem2.getCapacity());
for (int i = 7; i < 24; i++) { sk.update(i); }
byteArr2 = sk.toCompactByteArray();
wmem2 = WritableMemory.writableWrap(byteArr2);
assertEquals(sk.getCurMode(), CurMode.SET);
s = HllSketch.toString(byteArr2);
println(s);
println("LgArr: " + PreambleUtil.extractLgArr(wmem2));
println("Empty: " + PreambleUtil.extractEmptyFlag(wmem2));
println("Serialization Bytes: " + wmem2.getCapacity());
sk.update(24);
byteArr2 = sk.toCompactByteArray();
wmem2 = WritableMemory.writableWrap(byteArr2);
assertEquals(sk.getCurMode(), CurMode.HLL);
s = HllSketch.toString(Memory.wrap(byteArr2));
println(s);
println("LgArr: " + PreambleUtil.extractLgArr(wmem2));
println("Empty: " + PreambleUtil.extractEmptyFlag(wmem2));
println("Serialization Bytes: " + wmem2.getCapacity());
}
@Test
public void checkCompactFlag() {
HllSketch sk = new HllSketch(7);
byte[] memObj = sk.toCompactByteArray();
WritableMemory wmem = WritableMemory.writableWrap(memObj);
boolean compact = PreambleUtil.extractCompactFlag(wmem);
assertTrue(compact);
PreambleUtil.insertCompactFlag(wmem, false);
compact = PreambleUtil.extractCompactFlag(wmem);
assertFalse(compact);
}
@SuppressWarnings("unused")
@Test
public void checkCorruptMemoryInput() {
HllSketch sk = new HllSketch(12);
byte[] memObj = sk.toCompactByteArray();
WritableMemory wmem = WritableMemory.writableWrap(memObj);
long memAdd = wmem.getCumulativeOffset(0);
HllSketch bad;
//checkFamily
try {
wmem.putByte(FAMILY_BYTE, (byte) 0); //corrupt, should be 7
bad = HllSketch.heapify(wmem);
fail();
} catch (SketchesArgumentException e) { /* OK */ }
insertFamilyId(wmem); //corrected
//check SerVer
try {
wmem.putByte(SER_VER_BYTE, (byte) 0); //corrupt, should be 1
bad = HllSketch.heapify(wmem);
fail();
} catch (SketchesArgumentException e) { /* OK */ }
insertSerVer(wmem); //corrected
//check bad PreInts
try {
insertPreInts(wmem, 0); //corrupt, should be 2
bad = HllSketch.heapify(wmem);
fail();
} catch (SketchesArgumentException e) { /* OK */ }
insertPreInts(wmem, 2); //corrected
//check wrong PreInts and LIST
try {
insertPreInts(wmem, 3); //corrupt, should be 2
bad = HllSketch.heapify(wmem);
fail();
} catch (SketchesArgumentException e) { /* OK */ }
insertPreInts(wmem, 2); //corrected
//move to Set mode
for (int i = 1; i <= 15; i++) { sk.update(i); }
memObj = sk.toCompactByteArray();
wmem = WritableMemory.writableWrap(memObj);
memAdd = wmem.getCumulativeOffset(0);
//check wrong PreInts and SET
try {
insertPreInts(wmem, 2); //corrupt, should be 3
bad = HllSketch.heapify(wmem);
fail();
} catch (SketchesArgumentException e) { /* OK */ }
insertPreInts(wmem, 3); //corrected
//move to HLL mode
for (int i = 15; i <= 1000; i++) { sk.update(i); }
memObj = sk.toCompactByteArray();
wmem = WritableMemory.writableWrap(memObj);
memAdd = wmem.getCumulativeOffset(0);
//check wrong PreInts and HLL
try {
insertPreInts(wmem, 2); //corrupt, should be 10
bad = HllSketch.heapify(wmem);
fail();
} catch (SketchesArgumentException e) { /* OK */ }
insertPreInts(wmem, 10); //corrected
}
@SuppressWarnings("unused")
@Test
public void checkExtractFlags() {
int bytes = HllSketch.getMaxUpdatableSerializationBytes(4, TgtHllType.HLL_4);
WritableMemory wmem = WritableMemory.allocate(bytes);
Object memObj = wmem.getArray();
long memAdd = wmem.getCumulativeOffset(0L);
HllSketch sk = new HllSketch(4, TgtHllType.HLL_4, wmem);
int flags = extractFlags(wmem);
assertEquals(flags, EMPTY_FLAG_MASK);
}
@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,307 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/ToFromByteArrayTest.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.hll;
import static org.apache.datasketches.hll.TgtHllType.HLL_4;
import static org.apache.datasketches.hll.TgtHllType.HLL_6;
import static org.apache.datasketches.hll.TgtHllType.HLL_8;
import static org.testng.Assert.assertEquals;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class ToFromByteArrayTest {
static final int[] nArr = new int[] {1, 3, 10, 30, 100, 300, 1000, 3000, 10000, 30000};
@Test
public void checkToFromSketch1() {
for (int i = 0; i < 10; i++) {
int n = nArr[i];
for (int lgK = 4; lgK <= 13; lgK++) {
toFrom1(lgK, HLL_4, n);
toFrom1(lgK, HLL_6, n);
toFrom1(lgK, HLL_8, n);
}
println("=======");
}
}
private static void toFrom1(int lgConfigK, TgtHllType tgtHllType, int n) {
HllSketch src = new HllSketch(lgConfigK, tgtHllType);
for (int i = 0; i < n; i++) {
src.update(i);
}
//println("n: " + n + ", lgK: " + lgK + ", type: " + tgtHllType);
//printSketch(src, "SRC");
byte[] byteArr1 = src.toCompactByteArray(); //compact
HllSketch dst = HllSketch.heapify(byteArr1); //using byte[] interface
//printSketch(dst, "DST");
assertEquals(dst.getEstimate(), src.getEstimate(), 0.0);
byte[] byteArr2 = src.toUpdatableByteArray(); //updatable
Memory mem2 = Memory.wrap(byteArr2);
HllSketch dst2 = HllSketch.heapify(mem2); //using Memory interface
//printSketch(dst, "DST");
assertEquals(dst2.getEstimate(), src.getEstimate(), 0.0);
WritableMemory mem3 = WritableMemory.writableWrap(byteArr2);
HllSketch dst3 = HllSketch.heapify(mem3); //using WritableMemory interface
//printSketch(dst, "DST");
assertEquals(dst3.getEstimate(), src.getEstimate(), 0.0);
}
@Test
public void checkToFromSketch2() {
for (int i = 0; i < 10; i++) {
int n = nArr[i];
for (int lgK = 4; lgK <= 13; lgK++) {
toFrom2(lgK, HLL_4, n);
toFrom2(lgK, HLL_6, n);
toFrom2(lgK, HLL_8, n);
}
println("=======");
}
}
//Test direct
private static void toFrom2(int lgConfigK, TgtHllType tgtHllType, int n) {
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType);
byte[] byteArray = new byte[bytes];
WritableMemory wmem = WritableMemory.writableWrap(byteArray);
HllSketch src = new HllSketch(lgConfigK, tgtHllType, wmem);
for (int i = 0; i < n; i++) {
src.update(i);
}
//println("n: " + n + ", lgK: " + lgConfigK + ", type: " + tgtHllType);
//printSketch(src, "Source");
//Heapify compact
byte[] compactByteArr = src.toCompactByteArray(); //compact
HllSketch dst = HllSketch.heapify(compactByteArr); //using byte[] interface
//printSketch(dst, "Heapify From Compact");
assertEquals(dst.getEstimate(), src.getEstimate(), 0.0);
//Heapify updatable
byte[] updatableByteArr = src.toUpdatableByteArray();
WritableMemory wmem2 = WritableMemory.writableWrap(updatableByteArr);
HllSketch dst2 = HllSketch.heapify(wmem2); //using Memory interface
//printSketch(dst2, "Heapify From Updatable");
assertEquals(dst2.getEstimate(), src.getEstimate(), 0.0);
//Wrap updatable
WritableMemory wmem3 = WritableMemory.allocate(bytes);
wmem2.copyTo(0, wmem3, 0, wmem2.getCapacity());
HllSketch dst3 = HllSketch.writableWrap(wmem3);
//printSketch(dst3, "WritableWrap From Updatable");
assertEquals(dst3.getEstimate(), src.getEstimate(), 0.0);
//Wrap updatable as Read-Only
HllSketch dst4 = HllSketch.wrap(wmem3);
assertEquals(dst4.getEstimate(), src.getEstimate(), 0.0);
}
// static void printSketch(HllSketch sketch, String name) {
// println(name +":\n" + sketch.toString(true, true, true, false));
// }
@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,308 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/HllSketchTest.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.hll;
import static org.apache.datasketches.hll.HllSketch.getMaxUpdatableSerializationBytes;
import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS;
import static org.apache.datasketches.hll.HllUtil.LG_INIT_LIST_SIZE;
import static org.apache.datasketches.hll.HllUtil.LG_INIT_SET_SIZE;
import static org.apache.datasketches.hll.PreambleUtil.HASH_SET_INT_ARR_START;
import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START;
import static org.apache.datasketches.hll.PreambleUtil.LIST_INT_ARR_START;
import static org.apache.datasketches.hll.TgtHllType.HLL_4;
import static org.apache.datasketches.hll.TgtHllType.HLL_6;
import static org.apache.datasketches.hll.TgtHllType.HLL_8;
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.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class HllSketchTest {
@Test
public void checkCopies() {
runCheckCopy(14, HLL_4, null);
runCheckCopy(8, HLL_6, null);
runCheckCopy(8, HLL_8, null);
int bytes = getMaxUpdatableSerializationBytes(14, TgtHllType.HLL_8);
WritableMemory wmem = WritableMemory.allocate(bytes);
runCheckCopy(14, HLL_4, wmem);
runCheckCopy(8, HLL_6, wmem);
runCheckCopy(8, HLL_8, wmem);
}
private static void runCheckCopy(int lgConfigK, TgtHllType tgtHllType, WritableMemory wmem) {
HllSketch sk;
if (wmem == null) { //heap
sk = new HllSketch(lgConfigK, tgtHllType);
} else { //direct
sk = new HllSketch(lgConfigK, tgtHllType, wmem);
}
for (int i = 0; i < 7; i++) {
sk.update(i);
}
assertEquals(sk.getCurMode(), CurMode.LIST);
HllSketch skCopy = sk.copy();
assertEquals(skCopy.getCurMode(), CurMode.LIST);
HllSketchImpl impl1 = sk.hllSketchImpl;
HllSketchImpl impl2 = skCopy.hllSketchImpl;
AbstractCoupons absCoupons1 = (AbstractCoupons) sk.hllSketchImpl;
AbstractCoupons absCoupons2 = (AbstractCoupons) skCopy.hllSketchImpl;
assertEquals(absCoupons1.getCouponCount(), absCoupons2.getCouponCount());
assertEquals(impl1.getEstimate(), impl2.getEstimate(), 0.0);
assertFalse(impl1 == impl2);
for (int i = 7; i < 24; i++) {
sk.update(i);
}
assertEquals(sk.getCurMode(), CurMode.SET);
skCopy = sk.copy();
assertEquals(skCopy.getCurMode(), CurMode.SET);
impl1 = sk.hllSketchImpl;
impl2 = skCopy.hllSketchImpl;
absCoupons1 = (AbstractCoupons) sk.hllSketchImpl;
absCoupons2 = (AbstractCoupons) skCopy.hllSketchImpl;
assertEquals(absCoupons1.getCouponCount(), absCoupons2.getCouponCount());
assertEquals(impl1.getEstimate(), impl2.getEstimate(), 0.0);
assertFalse(impl1 == impl2);
final int u = (sk.getTgtHllType() == TgtHllType.HLL_4) ? 100000 : 25;
for (int i = 24; i < u; i++) {
sk.update(i);
}
sk.getCompactSerializationBytes();
assertEquals(sk.getCurMode(), CurMode.HLL);
skCopy = sk.copy();
assertEquals(skCopy.getCurMode(), CurMode.HLL);
impl1 = sk.hllSketchImpl;
impl2 = skCopy.hllSketchImpl;
assertEquals(impl1.getEstimate(), impl2.getEstimate(), 0.0);
assertFalse(impl1 == impl2);
}
@Test
public void checkCopyAs() {
copyAs(HLL_4, HLL_4, false);
copyAs(HLL_4, HLL_6, false);
copyAs(HLL_4, HLL_8, false);
copyAs(HLL_6, HLL_4, false);
copyAs(HLL_6, HLL_6, false);
copyAs(HLL_6, HLL_8, false);
copyAs(HLL_8, HLL_4, false);
copyAs(HLL_8, HLL_6, false);
copyAs(HLL_8, HLL_8, false);
copyAs(HLL_4, HLL_4, true);
copyAs(HLL_4, HLL_6, true);
copyAs(HLL_4, HLL_8, true);
copyAs(HLL_6, HLL_4, true);
copyAs(HLL_6, HLL_6, true);
copyAs(HLL_6, HLL_8, true);
copyAs(HLL_8, HLL_4, true);
copyAs(HLL_8, HLL_6, true);
copyAs(HLL_8, HLL_8, true);
}
private static void copyAs(TgtHllType srcType, TgtHllType dstType, boolean direct) {
int lgK = 8;
int n1 = 7;
int n2 = 24;
int n3 = 1000;
int base = 0;
int bytes = getMaxUpdatableSerializationBytes(lgK, srcType);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch src = (direct) ? new HllSketch(lgK, srcType, wmem) : new HllSketch(lgK, srcType);
for (int i = 0; i < n1; i++) { src.update(i + base); }
HllSketch dst = src.copyAs(dstType);
assertEquals(dst.getEstimate(), src.getEstimate(), 0.0);
for (int i = n1; i < n2; i++) { src.update(i); }
dst = src.copyAs(dstType);
assertEquals(dst.getEstimate(), src.getEstimate(), 0.0);
for (int i = n2; i < n3; i++) { src.update(i); }
dst = src.copyAs(dstType);
assertEquals(dst.getEstimate(), src.getEstimate(), 0.0);
}
@Test
public void checkMisc1() {
misc(false);
misc(true);
}
private static void misc(boolean direct) {
int lgConfigK = 8;
TgtHllType srcType = TgtHllType.HLL_8;
int bytes = getMaxUpdatableSerializationBytes(lgConfigK, srcType);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = (direct)
? new HllSketch(lgConfigK, srcType, wmem) : new HllSketch(lgConfigK, srcType);
for (int i = 0; i < 7; i++) { sk.update(i); } //LIST
AbstractCoupons absCoupons = (AbstractCoupons) sk.hllSketchImpl;
assertEquals(absCoupons.getCouponCount(), 7);
assertEquals(sk.getCompactSerializationBytes(), 36);
assertEquals(sk.getUpdatableSerializationBytes(), 40);
for (int i = 7; i < 24; i++) { sk.update(i); } //SET
absCoupons = (AbstractCoupons) sk.hllSketchImpl;
assertEquals(absCoupons.getCouponCount(), 24);
assertEquals(sk.getCompactSerializationBytes(), 108);
assertEquals(sk.getUpdatableSerializationBytes(), 140);
sk.update(24); //HLL
AbstractHllArray absHll = (AbstractHllArray) sk.hllSketchImpl;
assertNull(absHll.getAuxIterator());
assertEquals(absHll.getCurMin(), 0);
assertEquals(absHll.getHipAccum(), 25.0, 25 * .02);
assertTrue(absHll.getNumAtCurMin() >= 0);
assertEquals(sk.getUpdatableSerializationBytes(), 40 + 256);
assertEquals(absHll.getMemDataStart(), 40);
assertEquals(absHll.getPreInts(), 10);
final int hllBytes = PreambleUtil.HLL_BYTE_ARR_START + (1 << lgConfigK);
assertEquals(sk.getCompactSerializationBytes(), hllBytes);
assertEquals(getMaxUpdatableSerializationBytes(lgConfigK, TgtHllType.HLL_8), hllBytes);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkNumStdDev() {
HllUtil.checkNumStdDev(0);
}
@Test
public void checkSerSizes() {
checkSerSizes(8, TgtHllType.HLL_8, false);
checkSerSizes(8, TgtHllType.HLL_8, true);
checkSerSizes(8, TgtHllType.HLL_6, false);
checkSerSizes(8, TgtHllType.HLL_6, true);
checkSerSizes(8, TgtHllType.HLL_4, false);
checkSerSizes(8, TgtHllType.HLL_4, true);
}
private static void checkSerSizes(int lgConfigK, TgtHllType tgtHllType, boolean direct) {
int bytes = getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = (direct)
? new HllSketch(lgConfigK, tgtHllType, wmem) : new HllSketch(lgConfigK, tgtHllType);
int i;
//LIST
for (i = 0; i < 7; i++) { sk.update(i); }
int expected = LIST_INT_ARR_START + (i << 2);
assertEquals(sk.getCompactSerializationBytes(), expected);
expected = LIST_INT_ARR_START + (4 << LG_INIT_LIST_SIZE);
assertEquals(sk.getUpdatableSerializationBytes(), expected);
//SET
for (i = 7; i < 24; i++) { sk.update(i); }
expected = HASH_SET_INT_ARR_START + (i << 2);
assertEquals(sk.getCompactSerializationBytes(), expected);
expected = HASH_SET_INT_ARR_START + (4 << LG_INIT_SET_SIZE);
assertEquals(sk.getUpdatableSerializationBytes(), expected);
//HLL
sk.update(i);
assertEquals(sk.getCurMode(), CurMode.HLL);
AbstractHllArray absHll = (AbstractHllArray) sk.hllSketchImpl;
int auxCountBytes = 0;
int auxArrBytes = 0;
if (absHll.tgtHllType == HLL_4) {
AuxHashMap auxMap = absHll.getAuxHashMap();
if (auxMap != null) {
auxCountBytes = auxMap.getAuxCount() << 2;
auxArrBytes = 4 << auxMap.getLgAuxArrInts();
} else {
auxArrBytes = 4 << LG_AUX_ARR_INTS[lgConfigK];
}
}
int hllArrBytes = absHll.getHllByteArrBytes();
expected = HLL_BYTE_ARR_START + hllArrBytes + auxCountBytes;
assertEquals(sk.getCompactSerializationBytes(), expected);
expected = HLL_BYTE_ARR_START + hllArrBytes + auxArrBytes;
assertEquals(sk.getUpdatableSerializationBytes(), expected);
int fullAuxBytes = (tgtHllType == TgtHllType.HLL_4) ? (4 << LG_AUX_ARR_INTS[lgConfigK]) : 0;
expected = HLL_BYTE_ARR_START + hllArrBytes + fullAuxBytes;
assertEquals(getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType), expected);
}
@SuppressWarnings("unused")
@Test
public void checkConfigKLimits() {
try {
HllSketch sk = new HllSketch(HllUtil.MIN_LOG_K - 1);
fail();
} catch (SketchesArgumentException e) {
//expected
}
try {
HllSketch sk = new HllSketch(HllUtil.MAX_LOG_K + 1);
fail();
} catch (SketchesArgumentException e) {
//expected
}
}
@Test
public void exerciseToStringDetails() {
HllSketch sk = new HllSketch(15, TgtHllType.HLL_4);
for (int i = 0; i < 25; i++) { sk.update(i); }
println(sk.toString(false, true, true, true)); //SET mode
for (int i = 25; i < (1 << 12); i++) { sk.update(i); }
println(sk.toString(false, true, true, true)); //HLL mode no Aux
for (int i = (1 << 12); i < (1 << 15); i++) { sk.update(i); } //Aux with exceptions
println(sk.toString(false, true, true, true));
println(sk.toString(false, true, true, false));
println(sk.toString(false, true, true));
sk = new HllSketch(8, TgtHllType.HLL_6);
for (int i = 0; i < 25; i++) { sk.update(i); }
println(sk.toString(false, true, true, true));
}
@SuppressWarnings("unused")
@Test
public void checkMemoryNotLargeEnough() {
int bytes = getMaxUpdatableSerializationBytes(8, TgtHllType.HLL_8);
WritableMemory wmem = WritableMemory.allocate(bytes -1);
try {
HllSketch sk = new HllSketch(8, TgtHllType.HLL_8, wmem);
fail();
} catch (SketchesArgumentException e) {
//OK
}
}
@Test
public void checkEmptyCoupon() {
int lgK = 8;
TgtHllType type = TgtHllType.HLL_8;
HllSketch sk = new HllSketch(lgK, type);
for (int i = 0; i < 20; i++) { sk.update(i); } //SET mode
sk.couponUpdate(0);
assertEquals(sk.getEstimate(), 20.0, 0.001);
}
@Test
public void checkCompactFlag() {
int lgK = 8;
//LIST: follows the toByteArray request
assertEquals(checkCompact(lgK, 7, HLL_8, false, false), false);
assertEquals(checkCompact(lgK, 7, HLL_8, false, true), true);
assertEquals(checkCompact(lgK, 7, HLL_8, false, false), false);
assertEquals(checkCompact(lgK, 7, HLL_8, false, true), true);
assertEquals(checkCompact(lgK, 7, HLL_8, true, false), false);
assertEquals(checkCompact(lgK, 7, HLL_8, true, true), true);
assertEquals(checkCompact(lgK, 7, HLL_8, true, false), false);
assertEquals(checkCompact(lgK, 7, HLL_8, true, true), true);
//SET: follows the toByteArray request
assertEquals(checkCompact(lgK, 24, HLL_8, false, false), false);
assertEquals(checkCompact(lgK, 24, HLL_8, false, true), true);
assertEquals(checkCompact(lgK, 24, HLL_8, false, false), false);
assertEquals(checkCompact(lgK, 24, HLL_8, false, true), true);
assertEquals(checkCompact(lgK, 24, HLL_8, true, false), false);
assertEquals(checkCompact(lgK, 24, HLL_8, true, true), true);
assertEquals(checkCompact(lgK, 24, HLL_8, true, false), false);
assertEquals(checkCompact(lgK, 24, HLL_8, true, true), true);
//HLL8: always updatable
assertEquals(checkCompact(lgK, 25, HLL_8, false, false), false);
assertEquals(checkCompact(lgK, 25, HLL_8, false, true), false);
assertEquals(checkCompact(lgK, 25, HLL_8, false, false), false);
assertEquals(checkCompact(lgK, 25, HLL_8, false, true), false);
assertEquals(checkCompact(lgK, 25, HLL_8, true, false), false);
assertEquals(checkCompact(lgK, 25, HLL_8, true, true), false);
assertEquals(checkCompact(lgK, 25, HLL_8, true, false), false);
assertEquals(checkCompact(lgK, 25, HLL_8, true, true), false);
//HLL6: always updatable
assertEquals(checkCompact(lgK, 25, HLL_6, false, false), false);
assertEquals(checkCompact(lgK, 25, HLL_6, false, true), false);
assertEquals(checkCompact(lgK, 25, HLL_6, false, false), false);
assertEquals(checkCompact(lgK, 25, HLL_6, false, true), false);
assertEquals(checkCompact(lgK, 25, HLL_6, true, false), false);
assertEquals(checkCompact(lgK, 25, HLL_6, true, true), false);
assertEquals(checkCompact(lgK, 25, HLL_6, true, false), false);
assertEquals(checkCompact(lgK, 25, HLL_6, true, true), false);
//HLL:4 follows the toByteArray request
assertEquals(checkCompact(lgK, 25, HLL_4, false, false), false);
assertEquals(checkCompact(lgK, 25, HLL_4, false, true), true);
assertEquals(checkCompact(lgK, 25, HLL_4, false, false), false);
assertEquals(checkCompact(lgK, 25, HLL_4, false, true), true);
assertEquals(checkCompact(lgK, 25, HLL_4, true, false), false);
assertEquals(checkCompact(lgK, 25, HLL_4, true, true), true);
assertEquals(checkCompact(lgK, 25, HLL_4, true, false), false);
assertEquals(checkCompact(lgK, 25, HLL_4, true, true), true);
}
//Creates either a direct or heap sketch,
// Serializes to either compact or updatable form.
// Confirms the isMemory() for direct, isOffHeap(), and the
// get compact or updatable serialization bytes.
// Returns true if the compact flag is set.
private static boolean checkCompact(int lgK, int n, TgtHllType type, boolean direct,
boolean compact) {
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = (direct) ? new HllSketch(lgK, type, wmem) : new HllSketch(lgK, type);
assertEquals(sk.isMemory(), direct);
assertFalse(sk.isOffHeap());
for (int i = 0; i < n; i++) { sk.update(i); } //LOAD
byte[] byteArr = (compact) ? sk.toCompactByteArray() : sk.toUpdatableByteArray();
int len = byteArr.length;
if (compact) {
assertEquals(len, sk.getCompactSerializationBytes());
} else {
assertEquals(len, sk.getUpdatableSerializationBytes());
}
HllSketch sk2 = HllSketch.wrap(Memory.wrap(byteArr));
assertEquals(sk2.getEstimate(), n, .01);
boolean resourceCompact = sk2.isCompact();
if (resourceCompact) {
try {
HllSketch.writableWrap(WritableMemory.writableWrap(byteArr));
fail();
} catch (SketchesArgumentException e) {
//OK
}
}
return resourceCompact;
//return (byteArr[5] & COMPACT_FLAG_MASK) > 0;
}
@SuppressWarnings("unused")
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkWritableWrapOfCompact() {
HllSketch sk = new HllSketch();
byte[] byteArr = sk.toCompactByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
HllSketch sk2 = HllSketch.writableWrap(wmem);
}
@SuppressWarnings("unused")
@Test
public void checkJavadocExample() {
Union union; HllSketch sk, sk2;
int lgK = 12;
sk = new HllSketch(lgK, TgtHllType.HLL_4); //can be 4, 6, or 8
for (int i = 0; i < (2 << lgK); i++) { sk.update(i); }
byte[] arr = sk.toCompactByteArray();
// ...
union = Union.heapify(arr); //initializes the union using data from the array.
//OR, if used in an off-heap environment:
union = Union.heapify(Memory.wrap(arr));
//To recover an updatable Heap sketch:
sk2 = HllSketch.heapify(arr);
//OR, if used in an off-heap environment:
sk2 = HllSketch.heapify(Memory.wrap(arr));
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void print(String s) {
//System.out.print(s); //disable here
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,309 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/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.hll;
import static org.apache.datasketches.hll.TgtHllType.HLL_4;
import static org.apache.datasketches.hll.TgtHllType.HLL_6;
import static org.apache.datasketches.hll.TgtHllType.HLL_8;
import static java.lang.Math.min;
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.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
/**
* @author Lee Rhodes
*/
public class DirectUnionTest {
static final String LS = System.getProperty("line.separator");
static final int[] nArr = new int[] {1, 3, 10, 30, 100, 300, 1000, 3000, 10000, 30000};
// n1,... lgK,... tgtHll, Mode Ooo Est
static final String hdrFmt =
"%6s%6s%6s" + "%8s%5s%5s%5s" + "%7s%6s" + "%7s%6s%6s" +"%3s%2s%2s"+ "%13s%12s";
static final String hdr = String.format(hdrFmt,
"n1", "n2", "tot",
"lgMaxK", "lgK1", "lgK2", "lgKR",
"tgt1", "tgt2",
"Mode1", "Mode2", "ModeR",
"1", "2", "R",
"Est", "Err%");
/**
* The task here is to check the transition boundaries as the sketch morphs between LIST to
* SET to HLL modes. The transition points vary as a function of lgConfigK. In addition,
* this checks that the union operation is operating properly based on the order the
* sketches are presented to the union.
*/
@Test
public void checkUnions() {
//HLL_4: t=0, HLL_6: t=1, HLL_8: t=2
int t1 = 2; //type = HLL_8
int t2 = 2;
int rt = 2; //result type
println("TgtR: " + TgtHllType.values()[rt].toString());
int lgK1 = 7;
int lgK2 = 7;
int lgMaxK = 7;
int n1 = 7;
int n2 = 7;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 = 8;
n2 = 7;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 = 7;
n2 = 8;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 = 8;
n2 = 8;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 = 7;
n2 = 14;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
println("++END BASE GROUP++");
int i = 0;
for (i = 7; i <= 13; i++)
{
lgK1 = i;
lgK2 = i;
lgMaxK = i;
{
n1 = ((1 << (i - 3)) * 3)/4; //compute the transition point
n2 = n1;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 -= 2;
n2 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
}
println("--END MINOR GROUP--");
lgK1 = i;
lgK2 = i + 1;
lgMaxK = i;
{
n1 = ((1 << (i - 3)) * 3)/4;
n2 = n1;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 -= 2;
n2 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
}
println("--END MINOR GROUP--");
lgK1 = i + 1;
lgK2 = i;
lgMaxK = i;
{
n1 = ((1 << (i - 3)) * 3)/4;
n2 = n1;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 -= 2;
n2 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
}
println("--END MINOR GROUP--");
lgK1 = i + 1;
lgK2 = i + 1;
lgMaxK = i;
{
n1 = ((1 << (i - 3)) * 3)/4;
n2 = n1;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 -= 2;
n2 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
n1 += 2;
basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt);
}
println("++END MAJOR GROUP++");
} //End for
}
@Test
public void check() { //n1=8, n2=7, lgK1=lgK2=lgMaxK=7, all HLL_8
basicUnion(8, 7, 7, 7, 7, 2, 2, 2);
}
private static void basicUnion(int n1, int n2, int lgK1, int lgK2,
int lgMaxK, int t1, int t2, int rt) {
long v = 0;
int tot = n1 + n2;
TgtHllType type1 = TgtHllType.values()[t1];
String t1str = type1.toString();
TgtHllType type2 = TgtHllType.values()[t2];
String t2str = type2.toString();
TgtHllType resultType = TgtHllType.values()[rt];
//String rtStr = resultType.toString();
HllSketch h1 = new HllSketch(lgK1, type1);
HllSketch h2 = new HllSketch(lgK2, type2);
int lgControlK = min(min(lgK1, lgK2), lgMaxK); //min of all 3
HllSketch control = new HllSketch(lgControlK, resultType);
String dataFmt = "%6d%6d%6d," + "%7d%5d%5d%5d," + "%6s%6s," + "%6s%6s%6s,"
+"%2s%2s%2s," + "%12f%12f%%";
for (long i = 0; i < n1; i++) {
h1.update(v + i);
control.update(v + i);
}
v += n1;
for (long i = 0; i < n2; i++) {
h2.update(v + i);
control.update(v + i);
}
v += n2;
String h1SketchStr = ("H1 SKETCH: \n" + h1.toString());
String h2SketchStr = ("H2 SKETCH: \n" + h2.toString());
Union union = newUnion(lgMaxK);
union.update(h1);
String uH1SketchStr = ("Union after H1: \n" + union.getResult(resultType).toString());
//println(uH1SketchStr);
union.update(h2);
HllSketch result = union.getResult(resultType);
int lgKR = result.getLgConfigK();
String uSketchStr =("Union after H2: \n" + result.toString());
double uEst = result.getEstimate();
double uUb = result.getUpperBound(2);
double uLb = result.getLowerBound(2);
double rerr = ((uEst/tot) - 1.0) * 100;
String mode1 = h1.getCurMode().toString();
String mode2 = h2.getCurMode().toString();
String modeR = result.getCurMode().toString();
//Control
String cSketchStr = ("CONTROL SKETCH: \n" + control.toString());
double controlEst = control.getEstimate();
double controlUb = control.getUpperBound(2);
double controlLb = control.getLowerBound(2);
String h1ooo = h1.isOutOfOrder() ? "T" : "F";
String h2ooo = h2.isOutOfOrder() ? "T" : "F";
String resultooo = result.isOutOfOrder() ? "T" : "F";
String row = String.format(dataFmt,
n1, n2, tot,
lgMaxK, lgK1, lgK2, lgKR,
t1str, t2str,
mode1, mode2, modeR,
h1ooo, h2ooo, resultooo,
uEst, rerr);
println(h1SketchStr);
println(h2SketchStr);
println(uH1SketchStr);
println(uSketchStr);
println(cSketchStr);
println(hdr);
println(row);
assertTrue((controlUb - controlEst) >= 0);
assertTrue((uUb - uEst) >= 0);
assertTrue((controlEst - controlLb) >= 0);
assertTrue((uEst -uLb) >= 0);
}
@Test
public void checkToFromUnion1() {
for (int i = 0; i < 10; i++) {
int n = nArr[i];
for (int lgK = 4; lgK <= 13; lgK++) {
toFrom1(lgK, HLL_4, n);
toFrom1(lgK, HLL_6, n);
toFrom1(lgK, HLL_8, n);
}
println("=======");
}
}
private static void toFrom1(int lgK, TgtHllType tgtHllType, int n) {
Union srcU = newUnion(lgK);
HllSketch srcSk = new HllSketch(lgK, tgtHllType);
for (int i = 0; i < n; i++) {
srcSk.update(i);
}
println("n: " + n + ", lgK: " + lgK + ", type: " + tgtHllType);
//printSketch(src, "SRC");
srcU.update(srcSk);
byte[] byteArr = srcU.toCompactByteArray();
Memory mem = Memory.wrap(byteArr);
Union dstU = Union.heapify(mem);
assertEquals(dstU.getEstimate(), srcU.getEstimate(), 0.0);
}
@Test
public void checkToFromUnion2() {
for (int i = 0; i < 10; i++) {
int n = nArr[i];
for (int lgK = 4; lgK <= 13; lgK++) {
toFrom2(lgK, HLL_4, n);
toFrom2(lgK, HLL_6, n);
toFrom2(lgK, HLL_8, n);
}
println("=======");
}
}
private static void toFrom2(int lgK, TgtHllType tgtHllType, int n) {
Union srcU = newUnion(lgK);
HllSketch srcSk = new HllSketch(lgK, tgtHllType);
for (int i = 0; i < n; i++) {
srcSk.update(i);
}
println("n: " + n + ", lgK: " + lgK + ", type: " + tgtHllType);
//printSketch(src, "SRC");
srcU.update(srcSk);
byte[] byteArr = srcU.toCompactByteArray();
Union dstU = Union.heapify(byteArr);
assertEquals(dstU.getEstimate(), srcU.getEstimate(), 0.0);
}
@Test
public void checkCompositeEst() {
Union u = newUnion(12);
assertEquals(u.getCompositeEstimate(), 0, .03);
for (int i = 1; i <= 15; i++) { u.update(i); }
assertEquals(u.getCompositeEstimate(), 15, 15 *.03);
for (int i = 15; i <= 1000; i++) { u.update(i); }
assertEquals(u.getCompositeEstimate(), 1000, 1000 * .03);
}
@SuppressWarnings("unused")
@Test
public void checkMisc() {
try {
Union u = newUnion(HllUtil.MIN_LOG_K - 1);
fail();
} catch (SketchesArgumentException e) {
//expected
}
try {
Union u = newUnion(HllUtil.MAX_LOG_K + 1);
fail();
} catch (SketchesArgumentException e) {
//expected
}
Union u = newUnion(7);
HllSketch sk = u.getResult();
assertTrue(sk.isEmpty());
}
@Test
public void checkHeapify() {
Union u = newUnion(16);
for (int i = 0; i < (1 << 20); i++) {
u.update(i);
}
double est1 = u.getEstimate();
byte[] byteArray = u.toUpdatableByteArray();
Union u2 = Union.heapify(byteArray);
assertEquals(u2.getEstimate(), est1, 0.0);
}
@Test //for lgK <= 12
public void checkUbLb() {
int lgK = 4;
int n = 1 << 20;
boolean oooFlag = false;
println("LgK="+lgK+", UB3, " + ((getBound(lgK, true, oooFlag, 3, n) / n) - 1));
println("LgK="+lgK+", UB2, " + ((getBound(lgK, true, oooFlag, 2, n) / n) - 1));
println("LgK="+lgK+", UB1, " + ((getBound(lgK, true, oooFlag, 1, n) / n) - 1));
println("LgK="+lgK+", LB1, " + ((getBound(lgK, false, oooFlag, 1, n) / n) - 1));
println("LgK="+lgK+", LB2, " + ((getBound(lgK, false, oooFlag, 2, n) / n) - 1));
println("LgK="+lgK+", LB3, " + ((getBound(lgK, false, oooFlag, 3, n) / n) - 1));
}
@Test
public void checkEmptyCouponMisc() {
int lgK = 8;
Union union = newUnion(lgK);
for (int i = 0; i < 20; i++) { union.update(i); } //SET mode
union.couponUpdate(0);
assertEquals(union.getEstimate(), 20.0, 0.001);
assertEquals(union.getTgtHllType(), TgtHllType.HLL_8);
assertTrue(union.isMemory());
assertFalse(union.isOffHeap());
int bytes = union.getUpdatableSerializationBytes();
assertTrue(bytes <= Union.getMaxSerializationBytes(lgK));
assertFalse(union.isCompact());
}
@Test
public void checkUnionWithWrap() {
int lgConfigK = 4;
TgtHllType type = TgtHllType.HLL_4;
int n = 2;
HllSketch sk = new HllSketch(lgConfigK, type);
for (int i = 0; i < n; i++) { sk.update(i); }
double est = sk.getEstimate();
byte[] skByteArr = sk.toCompactByteArray();
HllSketch sk2 = HllSketch.wrap(Memory.wrap(skByteArr));
assertEquals(sk2.getEstimate(), est, 0.0);
Union union = newUnion(lgConfigK);
union.update(HllSketch.wrap(Memory.wrap(skByteArr)));
assertEquals(union.getEstimate(), est, 0.0);
}
@Test
public void checkUnionWithWrap2() {
int lgConfigK = 10;
int n = 128;
HllSketch sk1 = new HllSketch(lgConfigK);
for (int i = 0; i < n; i++) { sk1.update(i); }
double est1 = sk1.getEstimate();
byte[] byteArr1 = sk1.toCompactByteArray();
Union union = newUnion(lgConfigK);
union.update(HllSketch.wrap(Memory.wrap(byteArr1)));
double est2 = union.getEstimate();
assertEquals(est2, est1);
}
@Test
public void checkWritableWrap() {
int lgConfigK = 10;
int n = 128;
Union union = newUnion(lgConfigK);
for (int i = 0; i < n; i++) { union.update(i); }
double est = union.getEstimate();
Union union2 = Union.writableWrap(WritableMemory.writableWrap(union.toUpdatableByteArray()));
double est2 = union2.getEstimate();
assertEquals(est2, est, 0.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkWritableWrapThrows() {
int lgConfigK = 10;
int n = 128;
HllSketch sk = new HllSketch(lgConfigK, HLL_6);
for (int i = 0; i < n; i++) {sk.update(i); }
Union.writableWrap(WritableMemory.writableWrap(sk.toUpdatableByteArray()));
}
private static Union newUnion(int lgK) {
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, TgtHllType.HLL_8);
WritableMemory wmem = WritableMemory.allocate(bytes);
return new Union(lgK, wmem);
}
private static double getBound(int lgK, boolean ub, boolean oooFlag, int numStdDev, double est) {
double re = RelativeErrorTables.getRelErr(ub, oooFlag, lgK, numStdDev);
return est / (1.0 + re);
}
@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.out.print(s); //disable here
}
}
| 2,310 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/CouponListTest.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.hll;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class CouponListTest {
@Test //visual check
public void checkIterator() {
checkIterator(false, 4, 7);
checkIterator(true, 4, 7);
}
private static void checkIterator(boolean direct, int lgK, int n) {
TgtHllType tgtHllType = TgtHllType.HLL_4;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, tgtHllType);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = (direct) ? new HllSketch(lgK, tgtHllType, wmem) : new HllSketch(lgK);
for (int i = 0; i < n; i++) { sk.update(i); }
String store = direct ? "Memory" : "Heap";
println("CurMode: " + sk.getCurMode().toString() + "; Store: " + store);
PairIterator itr = sk.iterator();
println(itr.getHeader());
while (itr.nextAll()) {
assertTrue(itr.getSlot() < (1 << lgK));
println(itr.getString());
}
}
@Test
public void checkDuplicatesAndMisc() {
checkDuplicatesAndMisc(false);
checkDuplicatesAndMisc(true);
}
private static void checkDuplicatesAndMisc(boolean direct) {
int lgConfigK = 8;
TgtHllType tgtHllType = TgtHllType.HLL_4;
int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType);
WritableMemory wmem = WritableMemory.allocate(bytes);
HllSketch sk = (direct) ? new HllSketch(lgConfigK, tgtHllType, wmem) : new HllSketch(8);
for (int i = 1; i <= 7; i++) {
sk.update(i);
sk.update(i);
}
assertEquals(sk.getCurMode(), CurMode.LIST);
assertEquals(sk.getCompositeEstimate(), 7.0, 7 * .01);
assertEquals(sk.getHipEstimate(), 7.0, 7 * .01);
sk.hllSketchImpl.putEmptyFlag(false); //dummy
sk.hllSketchImpl.putRebuildCurMinNumKxQFlag(false); //dummy
if (direct) {
assertNotNull(sk.getWritableMemory());
assertNotNull(sk.getMemory());
} else {
assertNull(sk.getWritableMemory());
assertNull(sk.getMemory());
}
sk.update(8);
sk.update(8);
assertEquals(sk.getCurMode(), CurMode.SET);
assertEquals(sk.getCompositeEstimate(), 8.0, 8 * .01);
assertEquals(sk.getHipEstimate(), 8.0, 8 * .01);
if (direct) {
assertNotNull(sk.getWritableMemory());
assertNotNull(sk.getMemory());
} else {
assertNull(sk.getWritableMemory());
assertNull(sk.getMemory());
}
for (int i = 9; i <= 25; i++) {
sk.update(i);
sk.update(i);
}
assertEquals(sk.getCurMode(), CurMode.HLL);
assertEquals(sk.getCompositeEstimate(), 25.0, 25 * .1);
if (direct) {
assertNotNull(sk.getWritableMemory());
assertNotNull(sk.getMemory());
} else {
assertNull(sk.getWritableMemory());
assertNull(sk.getMemory());
}
}
@Test
public void toByteArray_Heapify() {
toByteArrayHeapify(7);
toByteArrayHeapify(21);
}
private static void toByteArrayHeapify(int lgK) {
HllSketch sk1 = new HllSketch(lgK);
int u = (lgK < 8) ? 7 : ((1 << (lgK - 3))/4) * 3;
for (int i = 0; i < u; i++) {
sk1.update(i);
}
double est1 = sk1.getEstimate();
assertEquals(est1, u, u * 100.0E-6);
//println("Original\n" + sk1.toString());
byte[] byteArray = sk1.toCompactByteArray();
//println("Preamble: " + PreambleUtil.toString(byteArray));
HllSketch sk2 = HllSketch.heapify(byteArray);
double est2 = sk2.getEstimate();
//println("Heapify Compact\n" + sk2.toString(true, true, true, true));
assertEquals(est2, est1, 0.0);
byteArray = sk1.toUpdatableByteArray();
sk2 = HllSketch.heapify(byteArray);
est2 = sk2.getEstimate();
//println("Heapify Updatable\n" + sk2.toString());
assertEquals(est2, est1, 0.0);
}
@Test
public void checkGetMemory() {
HllSketch sk1 = new HllSketch(4);
AbstractCoupons absCoup = (AbstractCoupons) sk1.hllSketchImpl;
assertNull(absCoup.getMemory());
}
@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,311 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/AuxHashMapTest.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.hll;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesStateException;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class AuxHashMapTest {
static final String LS = System.getProperty("line.separator");
@Test
public void checkMustReplace() {
HeapAuxHashMap map = new HeapAuxHashMap(3, 7);
map.mustAdd(100, 5);
int val = map.mustFindValueFor(100);
assertEquals(val, 5);
map.mustReplace(100, 10);
val = map.mustFindValueFor(100);
assertEquals(val, 10);
try {
map.mustReplace(101, 5);
fail();
} catch (SketchesStateException e) {
//expected
}
}
@Test
public void checkGrowSpace() {
HeapAuxHashMap map = new HeapAuxHashMap(3, 7);
assertFalse(map.isMemory());
assertFalse(map.isOffHeap());
assertEquals(map.getLgAuxArrInts(), 3);
for (int i = 1; i <= 7; i++) {
map.mustAdd(i, i);
}
assertEquals(map.getLgAuxArrInts(), 4);
PairIterator itr = map.getIterator();
int count1 = 0;
int count2 = 0;
while (itr.nextAll()) {
count2++;
int pair = itr.getPair();
if (pair != 0) { count1++; }
}
assertEquals(count1, 7);
assertEquals(count2, 16);
}
@Test(expectedExceptions = SketchesStateException.class)
public void checkExceptions1() {
HeapAuxHashMap map = new HeapAuxHashMap(3, 7);
map.mustAdd(100, 5);
map.mustFindValueFor(101);
}
@Test(expectedExceptions = SketchesStateException.class)
public void checkExceptions2() {
HeapAuxHashMap map = new HeapAuxHashMap(3, 7);
map.mustAdd(100, 5);
map.mustAdd(100, 6);
}
@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,312 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hll/TablesTest.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.hll;
import static org.apache.datasketches.hll.CouponMapping.xArr;
import static org.apache.datasketches.hll.CouponMapping.yArr;
import static org.apache.datasketches.hll.CubicInterpolation.usingXAndYTables;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*
*/
public class TablesTest {
@Test
public void checkInterpolationExceptions() {
try {
usingXAndYTables(xArr, yArr, -1);
fail();
} catch (SketchesArgumentException e) {
//expected
}
try {
usingXAndYTables(xArr, yArr, 11000000.0);
fail();
} catch (SketchesArgumentException e) {
//expected
}
}
@Test
public void checkCornerCases() {
int len = xArr.length;
double x = xArr[len - 1];
double y = usingXAndYTables(xArr, yArr, x);
double yExp = yArr[len - 1];
assertEquals(y, yExp, 0.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,313 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hash/MurmurHash3AdaptorTest.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.hash;
import static org.apache.datasketches.hash.MurmurHash3Adaptor.asDouble;
import static org.apache.datasketches.hash.MurmurHash3Adaptor.asInt;
import static org.apache.datasketches.hash.MurmurHash3Adaptor.hashToBytes;
import static org.apache.datasketches.hash.MurmurHash3Adaptor.hashToLongs;
import static org.apache.datasketches.hash.MurmurHash3Adaptor.modulo;
import org.apache.datasketches.common.SketchesArgumentException;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class MurmurHash3AdaptorTest {
@Test
public void checkToBytesLong() {
byte[] result = hashToBytes(2L, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
}
@Test
public void checkToBytesLongArr() {
long[] arr = { 1L, 2L };
byte[] result = hashToBytes(arr, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
arr = new long[0];
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToBytesIntArr() {
int[] arr = { 1, 2 };
byte[] result = hashToBytes(arr, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
arr = new int[0];
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToBytesCharArr() {
char[] arr = { 1, 2 };
byte[] result = hashToBytes(arr, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
arr = new char[0];
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToBytesByteArr() {
byte[] arr = { 1, 2 };
byte[] result = hashToBytes(arr, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
arr = new byte[0];
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToBytesDouble() {
byte[] result = hashToBytes(1.0, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToBytes(0.0, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToBytes( -0.0, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
}
@Test
public void checkToBytesString() {
byte[] result = hashToBytes("1", 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToBytes("", 0L);
Assert.assertEquals(result, null);
String s = null;
result = hashToBytes(s, 0L);
Assert.assertEquals(result, null);
}
/************/
@Test
public void checkToLongsLong() {
long[] result = hashToLongs(2L, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
}
@Test
public void checkToLongsLongArr() {
long[] arr = { 1L, 2L };
long[] result = hashToLongs(arr, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
arr = new long[0];
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToLongsIntArr() {
int[] arr = { 1, 2 };
long[] result = hashToLongs(arr, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
arr = new int[0];
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToLongsCharArr() {
char[] arr = { 1, 2 };
long[] result = hashToLongs(arr, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
arr = new char[0];
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToLongsByteArr() {
byte[] arr = { 1, 2 };
long[] result = hashToLongs(arr, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
arr = new byte[0];
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToLongsDouble() {
long[] result = hashToLongs(1.0, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToLongs(0.0, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToLongs( -0.0, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
}
@Test
public void checkToLongsString() {
long[] result = hashToLongs("1", 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToLongs("", 0L);
Assert.assertEquals(result, null);
String s = null;
result = hashToLongs(s, 0L);
Assert.assertEquals(result, null);
}
/*************/
@Test
public void checkModulo() {
int div = 7;
for (int i = 20; i-- > 0;) {
long[] out = hashToLongs(i, 9001);
int mod = modulo(out[0], out[1], div);
Assert.assertTrue((mod < div) && (mod >= 0));
mod = modulo(out, div);
Assert.assertTrue((mod < div) && (mod >= 0));
}
}
@Test
public void checkAsDouble() {
for (int i = 0; i < 10000; i++ ) {
double result = asDouble(hashToLongs(i, 0));
Assert.assertTrue((result >= 0) && (result < 1.0));
}
}
//Check asInt() functions
@Test
public void checkAsInt() {
int lo = (3 << 28);
int hi = (1 << 30) + 1;
for (byte i = 0; i < 126; i++ ) {
long[] longArr = {i, i+1}; //long[]
int result = asInt(longArr, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(longArr, hi);
Assert.assertTrue((result >= 0) && (result < hi));
int[] intArr = {i, i+1}; //int[]
result = asInt(intArr, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(intArr, hi);
Assert.assertTrue((result >= 0) && (result < hi));
byte[] byteArr = {i, (byte)(i+1)}; //byte[]
result = asInt(byteArr, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(byteArr, hi);
Assert.assertTrue((result >= 0) && (result < hi));
long longV = i; //long
result = asInt(longV, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(longV, hi);
Assert.assertTrue((result >= 0) && (result < hi));
double v = i; //double
result = asInt(v, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(v, hi);
Assert.assertTrue((result >= 0) && (result < hi));
String s = Integer.toString(i); //String
result = asInt(s, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(s, hi);
Assert.assertTrue((result >= 0) && (result < hi));
}
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseLongNull() {
long[] arr = null;
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseLongEmpty() {
long[] arr = new long[0];
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseIntNull() {
int[] arr = null;
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseIntEmpty() {
int[] arr = new int[0];
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseByteNull() {
byte[] arr = null;
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseByteEmpty() {
byte[] arr = new byte[0];
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseStringNull() {
String s = null;
asInt(s, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseStringEmpty() {
String s = "";
asInt(s, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseNTooSmall() {
String s = "abc";
asInt(s, 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
}
}
| 2,314 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hash/XxHashTest.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.hash;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import org.apache.datasketches.memory.Memory;
/**
* @author Lee Rhodes
*/
public class XxHashTest {
@Test
public void longCheck() {
long seed = 0;
long hash1 = XxHash.hash(123L, seed);
long[] arr = new long[1];
arr[0] = 123L;
Memory mem = Memory.wrap(arr);
long hash2 = XxHash.hash(mem, 0, 8, 0);
assertEquals(hash2, hash1);
}
}
| 2,315 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hash/MurmurHash3v2Test.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.hash;
import java.util.Random;
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.memory.Memory;
import org.apache.datasketches.memory.MurmurHash3v2;
import org.apache.datasketches.memory.WritableMemory;
/**
* @author Lee Rhodes
*/
public class MurmurHash3v2Test {
private Random rand = new Random();
private static final int trials = 1 << 20;
@Test
public void compareLongArrLong() { //long[]
int arrLen = 3;
int iPer = 8 / Long.BYTES;
long[] key = new long[arrLen];
for (int i = 0; i < trials; i++) { //trials
for (int j = 0; j < arrLen / iPer; j++) { //longs
long r = rand.nextLong();
key[j] = r;
}
long[] res1 = hashV1(key, 0);
long[] res2 = hashV2(key, 0);
assertEquals(res2, res1);
}
}
@Test
public void compareIntArr() { //int[]
int bytes = Integer.BYTES;
int arrLen = 6;
int[] key = new int[arrLen];
int iPer = 8 / bytes;
int nLongs = arrLen / iPer;
int shift = 64 / iPer;
for (int i = 0; i < trials; i++) { //trials
for (int j = 0; j < nLongs; j++) { //longs
long r = rand.nextLong();
for (int k = 0; k < iPer; k++) { //ints
int shft = k * shift;
key[k] = (int) (r >>> shft);
}
}
long[] res1 = hashV1(key, 0);
long[] res2 = hashV2(key, 0);
assertEquals(res2, res1);
}
}
@Test
public void compareCharArr() { //char[]
int bytes = Character.BYTES;
int arrLen = 12;
char[] key = new char[arrLen];
int iPer = 8 / bytes;
int nLongs = arrLen / iPer;
int shift = 64 / iPer;
for (int i = 0; i < trials; i++) { //trials
for (int j = 0; j < nLongs; j++) { //longs
long r = rand.nextLong();
for (int k = 0; k < iPer; k++) { //char
int shft = k * shift;
key[k] = (char) (r >>> shft);
}
}
long[] res1 = hashV1(key, 0);
long[] res2 = hashV2(key, 0);
assertEquals(res2, res1);
}
}
@Test
public void compareByteArr() { //byte[]
int bytes = Byte.BYTES;
int arrLen = 12;
byte[] key = new byte[arrLen];
int iPer = 8 / bytes;
int nLongs = arrLen / iPer;
int shift = 64 / iPer;
for (int i = 0; i < trials; i++) { //trials
for (int j = 0; j < nLongs; j++) { //longs
long r = rand.nextLong();
for (int k = 0; k < iPer; k++) { //bytes
int shft = k * shift;
key[k] = (byte) (r >>> shft);
}
}
long[] res1 = hashV1(key, 0);
long[] res2 = hashV2(key, 0);
assertEquals(res2, res1);
}
}
@Test
public void compareLongVsLongArr() {
int arrLen = 1;
long[] key = new long[arrLen];
long[] out = new long[2];
for (int i = 0; i < trials; i++) { //trials
long r = rand.nextLong();
key[0] = r;
long[] res1 = hashV1(key, 0);
long[] res2 = hashV2(r, 0, out);
assertEquals(res2, res1);
}
}
private static final long[] hashV1(long[] key, long seed) {
return MurmurHash3.hash(key, seed);
}
private static final long[] hashV1(int[] key, long seed) {
return MurmurHash3.hash(key, seed);
}
private static final long[] hashV1(char[] key, long seed) {
return MurmurHash3.hash(key, seed);
}
private static final long[] hashV1(byte[] key, long seed) {
return MurmurHash3.hash(key, seed);
}
private static final long[] hashV2(long[] key, long seed) {
return MurmurHash3v2.hash(key, seed);
}
private static final long[] hashV2(int[] key2, long seed) {
return MurmurHash3v2.hash(key2, seed);
}
private static final long[] hashV2(char[] key, long seed) {
return MurmurHash3v2.hash(key, seed);
}
private static final long[] hashV2(byte[] key, long seed) {
return MurmurHash3v2.hash(key, seed);
}
//V2 single primitives
private static final long[] hashV2(long key, long seed, long[] out) {
return MurmurHash3v2.hash(key, seed, out);
}
// private static final long[] hashV2(double key, long seed, long[] out) {
// return MurmurHash3v2.hash(key, seed, out);
// }
// private static final long[] hashV2(String key, long seed, long[] out) {
// return MurmurHash3v2.hash(key, seed, out);
// }
@Test
public void offsetChecks() {
long seed = 12345;
int blocks = 6;
int cap = blocks * 16;
long[] hash1 = new long[2];
long[] hash2;
WritableMemory wmem = WritableMemory.allocate(cap);
for (int i = 0; i < cap; i++) { wmem.putByte(i, (byte)(-128 + i)); }
for (int offset = 0; offset < 16; offset++) {
int arrLen = cap - offset;
hash1 = MurmurHash3v2.hash(wmem, offset, arrLen, seed, hash1);
byte[] byteArr2 = new byte[arrLen];
wmem.getByteArray(offset, byteArr2, 0, arrLen);
hash2 = MurmurHash3.hash(byteArr2, seed);
assertEquals(hash1, hash2);
}
}
@Test
public void byteArrChecks() {
long seed = 0;
int offset = 0;
int bytes = 1024;
long[] hash2 = new long[2];
for (int j = 1; j < bytes; j++) {
byte[] in = new byte[bytes];
WritableMemory wmem = WritableMemory.writableWrap(in);
for (int i = 0; i < j; i++) { wmem.putByte(i, (byte) (-128 + i)); }
long[] hash1 = MurmurHash3.hash(in, 0);
hash2 = MurmurHash3v2.hash(wmem, offset, bytes, seed, hash2);
long[] hash3 = MurmurHash3v2.hash(in, seed);
assertEquals(hash1, hash2);
assertEquals(hash1, hash3);
}
}
@Test
public void charArrChecks() {
long seed = 0;
int offset = 0;
int chars = 16;
int bytes = chars << 1;
long[] hash2 = new long[2];
for (int j = 1; j < chars; j++) {
char[] in = new char[chars];
WritableMemory wmem = WritableMemory.writableWrap(in);
for (int i = 0; i < j; i++) { wmem.putInt(i, i); }
long[] hash1 = MurmurHash3.hash(in, 0);
hash2 = MurmurHash3v2.hash(wmem, offset, bytes, seed, hash2);
long[] hash3 = MurmurHash3v2.hash(in, seed);
assertEquals(hash1, hash2);
assertEquals(hash1, hash3);
}
}
@Test
public void intArrChecks() {
long seed = 0;
int offset = 0;
int ints = 16;
int bytes = ints << 2;
long[] hash2 = new long[2];
for (int j = 1; j < ints; j++) {
int[] in = new int[ints];
WritableMemory wmem = WritableMemory.writableWrap(in);
for (int i = 0; i < j; i++) { wmem.putInt(i, i); }
long[] hash1 = MurmurHash3.hash(in, 0);
hash2 = MurmurHash3v2.hash(wmem, offset, bytes, seed, hash2);
long[] hash3 = MurmurHash3v2.hash(in, seed);
assertEquals(hash1, hash2);
assertEquals(hash1, hash3);
}
}
@Test
public void longArrChecks() {
long seed = 0;
int offset = 0;
int longs = 16;
int bytes = longs << 3;
long[] hash2 = new long[2];
for (int j = 1; j < longs; j++) {
long[] in = new long[longs];
WritableMemory wmem = WritableMemory.writableWrap(in);
for (int i = 0; i < j; i++) { wmem.putLong(i, i); }
long[] hash1 = MurmurHash3.hash(in, 0);
hash2 = MurmurHash3v2.hash(wmem, offset, bytes, seed, hash2);
long[] hash3 = MurmurHash3v2.hash(in, seed);
assertEquals(hash1, hash2);
assertEquals(hash1, hash3);
}
}
@Test
public void longCheck() {
long seed = 0;
int offset = 0;
int bytes = 8;
long[] hash2 = new long[2];
long[] in = { 1 };
WritableMemory wmem = WritableMemory.writableWrap(in);
long[] hash1 = MurmurHash3.hash(in, 0);
hash2 = MurmurHash3v2.hash(wmem, offset, bytes, seed, hash2);
long[] hash3 = MurmurHash3v2.hash(in, seed);
assertEquals(hash1, hash2);
assertEquals(hash1, hash3);
}
@Test
public void checkEmptiesNulls() {
long seed = 123;
long[] hashOut = new long[2];
try {
MurmurHash3v2.hash(Memory.wrap(new long[0]), 0, 0, seed, hashOut); //mem empty
fail();
} catch (final IllegalArgumentException e) { } //OK
try {
Memory mem = null;
MurmurHash3v2.hash(mem, 0, 0, seed, hashOut); //mem null
fail();
} catch (final IllegalArgumentException e) { } //OK
try {
String s = "";
MurmurHash3v2.hash(s, seed, hashOut); //string empty
fail();
} catch (final IllegalArgumentException e) { } //OK
try {
String s = null;
MurmurHash3v2.hash(s, seed, hashOut); //string null
fail();
} catch (final IllegalArgumentException e) { } //OK
try {
byte[] barr = new byte[0];
MurmurHash3v2.hash(barr, seed); //byte[] empty
fail();
} catch (final IllegalArgumentException e) { } //OK
try {
byte[] barr = null;
MurmurHash3v2.hash(barr, seed); //byte[] null
fail();
} catch (final IllegalArgumentException e) { } //OK
try {
char[] carr = new char[0];
MurmurHash3v2.hash(carr, seed); //char[] empty
fail();
} catch (final IllegalArgumentException e) { } //OK
try {
char[] carr = null;
MurmurHash3v2.hash(carr, seed); //char[] null
fail();
} catch (final IllegalArgumentException e) { } //OK
try {
int[] iarr = new int[0];
MurmurHash3v2.hash(iarr, seed); //int[] empty
fail();
} catch (final IllegalArgumentException e) { } //OK
try {
int[] iarr = null;
MurmurHash3v2.hash(iarr, seed); //int[] null
fail();
} catch (final IllegalArgumentException e) { } //OK
try {
long[] larr = new long[0];
MurmurHash3v2.hash(larr, seed); //long[] empty
fail();
} catch (final IllegalArgumentException e) { } //OK
try {
long[] larr = null;
MurmurHash3v2.hash(larr, seed); //long[] null
fail();
} catch (final IllegalArgumentException e) { } //OK
}
@Test
public void checkStringLong() {
long seed = 123;
long[] hashOut = new long[2];
String s = "123";
assertTrue(MurmurHash3v2.hash(s, seed, hashOut)[0] != 0);
long v = 123;
assertTrue(MurmurHash3v2.hash(v, seed, hashOut)[0] != 0);
}
@Test
public void doubleCheck() {
long[] hash1 = checkDouble(-0.0);
long[] hash2 = checkDouble(0.0);
assertEquals(hash1, hash2);
hash1 = checkDouble(Double.NaN);
long nan = (0x7FFL << 52) + 1L;
hash2 = checkDouble(Double.longBitsToDouble(nan));
assertEquals(hash1, hash2);
checkDouble(1.0);
}
private static long[] checkDouble(double dbl) {
long seed = 0;
int offset = 0;
int bytes = 8;
long[] hash2 = new long[2];
final double d = (dbl == 0.0) ? 0.0 : dbl; // canonicalize -0.0, 0.0
final long data = Double.doubleToLongBits(d);// canonicalize all NaN forms
final long[] dataArr = { data };
WritableMemory wmem = WritableMemory.writableWrap(dataArr);
long[] hash1 = MurmurHash3.hash(dataArr, 0);
hash2 = MurmurHash3v2.hash(wmem, offset, bytes, seed, hash2);
long[] hash3 = MurmurHash3v2.hash(dbl, seed, hash2);
assertEquals(hash1, hash2);
assertEquals(hash1, hash3);
return hash1;
}
}
| 2,316 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hash/MurmurHash3Test.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.hash;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.datasketches.hash.MurmurHash3.hash;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Tests the MurmurHash3 against specific, known hash results given known
* inputs obtained from the public domain C++ version 150.
*
* @author Lee Rhodes
*/
public class MurmurHash3Test {
@Test
public void checkByteArrRemainderGT8() { //byte[], remainder > 8
String keyStr = "The quick brown fox jumps over the lazy dog";
byte[] key = keyStr.getBytes(UTF_8);
long[] result = hash(key, 0);
//Should be:
long h1 = 0xe34bbc7bbc071b6cL;
long h2 = 0x7a433ca9c49a9347L;
Assert.assertEquals(result[0], h1);
Assert.assertEquals(result[1], h2);
}
@Test
public void checkByteBufRemainderGT8() { //byte buffer, remainder > 8
String keyStr = "The quick brown fox jumps over the lazy dog";
byte[] key = keyStr.getBytes(UTF_8);
//Should be:
long h1 = 0xe34bbc7bbc071b6cL;
long h2 = 0x7a433ca9c49a9347L;
checkHashByteBuf(key, h1, h2);
}
@Test
public void checkByteArrChange1bit() { //byte[], change one bit
String keyStr = "The quick brown fox jumps over the lazy eog";
byte[] key = keyStr.getBytes(UTF_8);
long[] result = hash(key, 0);
//Should be:
long h1 = 0x362108102c62d1c9L;
long h2 = 0x3285cd100292b305L;
Assert.assertEquals(result[0], h1);
Assert.assertEquals(result[1], h2);
}
@Test
public void checkByteBufChange1bit() { //byte buffer, change one bit
String keyStr = "The quick brown fox jumps over the lazy eog";
byte[] key = keyStr.getBytes(UTF_8);
//Should be:
long h1 = 0x362108102c62d1c9L;
long h2 = 0x3285cd100292b305L;
checkHashByteBuf(key, h1, h2);
}
@Test
public void checkByteArrRemainderLt8() { //byte[], test a remainder < 8
String keyStr = "The quick brown fox jumps over the lazy dogdogdog";
byte[] key = keyStr.getBytes(UTF_8);
long[] result = hash(key, 0);
//Should be;
long h1 = 0x9c8205300e612fc4L;
long h2 = 0xcbc0af6136aa3df9L;
Assert.assertEquals(result[0], h1);
Assert.assertEquals(result[1], h2);
}
@Test
public void checkByteBufRemainderLt8() { //byte buffer, test a remainder < 8
String keyStr = "The quick brown fox jumps over the lazy dogdogdog";
byte[] key = keyStr.getBytes(UTF_8);
//Should be;
long h1 = 0x9c8205300e612fc4L;
long h2 = 0xcbc0af6136aa3df9L;
checkHashByteBuf(key, h1, h2);
}
@Test
public void checkByteArrReaminderEQ8() { //byte[], test a remainder = 8
String keyStr = "The quick brown fox jumps over the lazy1";
byte[] key = keyStr.getBytes(UTF_8);
long[] result = hash(key, 0);
//Should be:
long h1 = 0xe3301a827e5cdfe3L;
long h2 = 0xbdbf05f8da0f0392L;
Assert.assertEquals(result[0], h1);
Assert.assertEquals(result[1], h2);
}
@Test
public void checkByteBufReaminderEQ8() { //byte buffer, test a remainder = 8
String keyStr = "The quick brown fox jumps over the lazy1";
byte[] key = keyStr.getBytes(UTF_8);
//Should be:
long h1 = 0xe3301a827e5cdfe3L;
long h2 = 0xbdbf05f8da0f0392L;
checkHashByteBuf(key, h1, h2);
}
/**
* This test should have the exact same output as Test4
*/
@Test
public void checkLongArrRemainderEQ8() { //long[], test a remainder = 8
String keyStr = "The quick brown fox jumps over the lazy1";
long[] key = stringToLongs(keyStr);
long[] result = hash(key, 0);
//Should be:
long h1 = 0xe3301a827e5cdfe3L;
long h2 = 0xbdbf05f8da0f0392L;
Assert.assertEquals(result[0], h1);
Assert.assertEquals(result[1], h2);
}
/**
* This test should have the exact same output as Test4
*/
@Test
public void checkIntArrRemainderEQ8() { //int[], test a remainder = 8
String keyStr = "The quick brown fox jumps over the lazy1"; //40B
int[] key = stringToInts(keyStr);
long[] result = hash(key, 0);
//Should be:
long h1 = 0xe3301a827e5cdfe3L;
long h2 = 0xbdbf05f8da0f0392L;
Assert.assertEquals(result[0], h1);
Assert.assertEquals(result[1], h2);
}
@Test
public void checkIntArrRemainderEQ0() { //int[], test a remainder = 0
String keyStr = "The quick brown fox jumps over t"; //32B
int[] key = stringToInts(keyStr);
long[] result = hash(key, 0);
//Should be:
long h1 = 0xdf6af91bb29bdacfL;
long h2 = 0x91a341c58df1f3a6L;
Assert.assertEquals(result[0], h1);
Assert.assertEquals(result[1], h2);
}
/**
* Tests an odd remainder of int[].
*/
@Test
public void checkIntArrOddRemainder() { //int[], odd remainder
String keyStr = "The quick brown fox jumps over the lazy dog"; //43B
int[] key = stringToInts(keyStr);
long[] result = hash(key, 0);
//Should be:
long h1 = 0x1eb232b0087543f5L;
long h2 = 0xfc4c1383c3ace40fL;
Assert.assertEquals(result[0], h1);
Assert.assertEquals(result[1], h2);
}
/**
* Tests an odd remainder of int[].
*/
@Test
public void checkCharArrOddRemainder() { //char[], odd remainder
String keyStr = "The quick brown fox jumps over the lazy dog.."; //45B
char[] key = keyStr.toCharArray();
long[] result = hash(key, 0);
//Should be:
long h1 = 0xca77b498ea9ed953L;
long h2 = 0x8b8f8ec3a8f4657eL;
Assert.assertEquals(result[0], h1);
Assert.assertEquals(result[1], h2);
}
/**
* Tests an odd remainder of int[].
*/
@Test
public void checkCharArrRemainderEQ0() { //char[], remainder of 0
String keyStr = "The quick brown fox jumps over the lazy "; //40B
char[] key = keyStr.toCharArray();
long[] result = hash(key, 0);
//Should be:
long h1 = 0x51b15e9d0887f9f1L;
long h2 = 0x8106d226786511ebL;
Assert.assertEquals(result[0], h1);
Assert.assertEquals(result[1], h2);
}
@Test
public void checkByteArrAllOnesZeros() { //byte[], test a ones byte and a zeros byte
byte[] key = {
0x54, 0x68, 0x65, 0x20, 0x71, 0x75, 0x69, 0x63, 0x6b, 0x20, 0x62, 0x72, 0x6f, 0x77, 0x6e,
0x20, 0x66, 0x6f, 0x78, 0x20, 0x6a, 0x75, 0x6d, 0x70, 0x73, 0x20, 0x6f, 0x76, 0x65,
0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x61, 0x7a, 0x79, 0x20, 0x64, 0x6f, 0x67,
(byte) 0xff, 0x64, 0x6f, 0x67, 0x00
};
long[] result = MurmurHash3.hash(key, 0);
//Should be:
long h1 = 0xe88abda785929c9eL;
long h2 = 0x96b98587cacc83d6L;
Assert.assertEquals(result[0], h1);
Assert.assertEquals(result[1], h2);
}
@Test
public void checkByteBufAllOnesZeros() { //byte[], test a ones byte and a zeros byte
byte[] key = {
0x54, 0x68, 0x65, 0x20, 0x71, 0x75, 0x69, 0x63, 0x6b, 0x20, 0x62, 0x72, 0x6f, 0x77, 0x6e,
0x20, 0x66, 0x6f, 0x78, 0x20, 0x6a, 0x75, 0x6d, 0x70, 0x73, 0x20, 0x6f, 0x76, 0x65,
0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x61, 0x7a, 0x79, 0x20, 0x64, 0x6f, 0x67,
(byte) 0xff, 0x64, 0x6f, 0x67, 0x00
};
long h1 = 0xe88abda785929c9eL;
long h2 = 0x96b98587cacc83d6L;
checkHashByteBuf(key, h1, h2);
}
/**
* This test demonstrates that the hash of byte[], char[], int[], or long[] will produce the
* same hash result if, and only if, all the arrays have the same exact length in bytes, and if
* the contents of the values in the arrays have the same byte endianness and overall order.
*/
@Test
public void checkCrossTypeHashConsistency() {
long[] out;
println("Bytes");
byte[] bArr = {1,2,3,4,5,6,7,8, 9,10,11,12,13,14,15,16, 17,18,19,20,21,22,23,24};
long[] out1 = hash(bArr, 0L);
println(org.apache.datasketches.common.Util.longToHexBytes(out1[0]));
println(org.apache.datasketches.common.Util.longToHexBytes(out1[1]));
println("ByteBuffer");
ByteBuffer bBuf = ByteBuffer.wrap(bArr);
out = hash(bBuf, 0L);
Assert.assertEquals(out, out1);
println(org.apache.datasketches.common.Util.longToHexBytes(out1[0]));
println(org.apache.datasketches.common.Util.longToHexBytes(out1[1]));
println("Chars");
char[] cArr = {0X0201, 0X0403, 0X0605, 0X0807, 0X0a09, 0X0c0b, 0X0e0d, 0X100f,
0X1211, 0X1413, 0X1615, 0X1817};
out = hash(cArr, 0L);
Assert.assertEquals(out, out1);
println(org.apache.datasketches.common.Util.longToHexBytes(out[0]));
println(org.apache.datasketches.common.Util.longToHexBytes(out[1]));
println("Ints");
int[] iArr = {0X04030201, 0X08070605, 0X0c0b0a09, 0X100f0e0d, 0X14131211, 0X18171615};
out = hash(iArr, 0L);
Assert.assertEquals(out, out1);
println(org.apache.datasketches.common.Util.longToHexBytes(out[0]));
println(org.apache.datasketches.common.Util.longToHexBytes(out[1]));
println("Longs");
long[] lArr = {0X0807060504030201L, 0X100f0e0d0c0b0a09L, 0X1817161514131211L};
out = hash(lArr, 0L);
Assert.assertEquals(out, out1);
println(org.apache.datasketches.common.Util.longToHexBytes(out[0]));
println(org.apache.datasketches.common.Util.longToHexBytes(out[1]));
}
//Helper methods
private static long[] stringToLongs(String in) {
byte[] bArr = in.getBytes(UTF_8);
int inLen = bArr.length;
int outLen = inLen / 8 + (inLen % 8 != 0 ? 1 : 0);
long[] out = new long[outLen];
for (int i = 0; i < outLen - 1; i++ ) {
for (int j = 0; j < 8; j++ ) {
out[i] |= (bArr[i * 8 + j] & 0xFFL) << j * 8;
}
}
int inTail = 8 * (outLen - 1);
int rem = inLen - inTail;
for (int j = 0; j < rem; j++ ) {
out[outLen - 1] |= (bArr[inTail + j] & 0xFFL) << j * 8;
}
return out;
}
private static int[] stringToInts(String in) {
byte[] bArr = in.getBytes(UTF_8);
int inLen = bArr.length;
int outLen = inLen / 4 + (inLen % 4 != 0 ? 1 : 0);
int[] out = new int[outLen];
for (int i = 0; i < outLen - 1; i++ ) {
for (int j = 0; j < 4; j++ ) {
out[i] |= (bArr[i * 4 + j] & 0xFFL) << j * 8;
}
}
int inTail = 4 * (outLen - 1);
int rem = inLen - inTail;
for (int j = 0; j < rem; j++ ) {
out[outLen - 1] |= (bArr[inTail + j] & 0xFFL) << j * 8;
}
return out;
}
/**
* Tests {@link MurmurHash3#hash(ByteBuffer, long)} on the provided key.
*
* @param key byte array to hash
* @param h1 first half of expected hash
* @param h2 second half of expected hash
*/
private static void checkHashByteBuf(byte[] key, long h1, long h2) {
// Include dummy byte at start, end to make sure position, limit are respected.
ByteBuffer buf = ByteBuffer.allocate(key.length + 2).order(ByteOrder.LITTLE_ENDIAN);
buf.position(1);
buf.put(key);
buf.limit(1 + key.length);
buf.position(1);
long[] result1 = MurmurHash3.hash(buf, 0);
// Position, limit, order should not be changed.
Assert.assertEquals(1, buf.position());
Assert.assertEquals(1 + key.length, buf.limit());
Assert.assertEquals(ByteOrder.LITTLE_ENDIAN, buf.order());
// Check the actual hashes.
Assert.assertEquals(result1[0], h1);
Assert.assertEquals(result1[1], h2);
}
@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,317 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/IntegerSummaryDeserializer.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.tuple;
import org.apache.datasketches.memory.Memory;
public class IntegerSummaryDeserializer implements SummaryDeserializer<IntegerSummary> {
@Override
public DeserializeResult<IntegerSummary> heapifySummary(final Memory mem) {
return IntegerSummary.fromMemory(mem);
}
}
| 2,318 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/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.tuple;
import org.apache.datasketches.common.SketchesReadOnlyException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder;
import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch;
import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketches;
import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion;
import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch;
import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ReadOnlyMemoryTest {
@Test
public void wrapAndTryUpdatingSketch() {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch1.update(1, new double[] {1});
final ArrayOfDoublesUpdatableSketch sketch2 = (ArrayOfDoublesUpdatableSketch)
ArrayOfDoublesSketches.wrapSketch(Memory.wrap(sketch1.toByteArray()));
Assert.assertEquals(sketch2.getEstimate(), 1.0);
sketch2.toByteArray();
boolean thrown = false;
try {
sketch2.update(2, new double[] {1});
} catch (final SketchesReadOnlyException e) {
thrown = true;
}
try {
sketch2.trim();
} catch (final SketchesReadOnlyException e) {
thrown = true;
}
Assert.assertTrue(thrown);
}
@Test
public void heapifyAndUpdateSketch() {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch1.update(1, new double[] {1});
// downcasting is not recommended, for testing only
final ArrayOfDoublesUpdatableSketch sketch2 = (ArrayOfDoublesUpdatableSketch)
ArrayOfDoublesSketches.heapifySketch(Memory.wrap(sketch1.toByteArray()));
sketch2.update(2, new double[] {1});
Assert.assertEquals(sketch2.getEstimate(), 2.0);
}
@Test
public void wrapAndTryUpdatingUnionEstimationMode() {
final int numUniques = 10000;
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < numUniques; i++) {
sketch1.update(key++, new double[] {1});
}
final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().buildUnion();
union1.union(sketch1);
final ArrayOfDoublesUnion union2 = ArrayOfDoublesSketches.wrapUnion(Memory.wrap(union1.toByteArray()));
final ArrayOfDoublesSketch resultSketch = union2.getResult();
Assert.assertTrue(resultSketch.isEstimationMode());
Assert.assertEquals(resultSketch.getEstimate(), numUniques, numUniques * 0.04);
// make sure union update actually needs to modify the union
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < numUniques; i++) {
sketch2.update(key++, new double[] {1});
}
boolean thrown = false;
try {
union2.union(sketch2);
} catch (final SketchesReadOnlyException e) {
thrown = true;
}
Assert.assertTrue(thrown);
}
@Test
public void heapifyAndUpdateUnion() {
final int numUniques = 10000;
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < numUniques; i++) {
sketch1.update(key++, new double[] {1});
}
final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().buildUnion();
union1.union(sketch1);
final ArrayOfDoublesUnion union2 = ArrayOfDoublesSketches.heapifyUnion(Memory.wrap(union1.toByteArray()));
final ArrayOfDoublesSketch resultSketch = union2.getResult();
Assert.assertTrue(resultSketch.isEstimationMode());
Assert.assertEquals(resultSketch.getEstimate(), numUniques, numUniques * 0.04);
// make sure union update actually needs to modify the union
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < numUniques; i++) {
sketch2.update(key++, new double[] {1});
}
union2.union(sketch2);
}
}
| 2,319 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/TupleCrossLanguageTest.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.tuple;
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.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.TestUtil;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.tuple.adouble.DoubleSummary;
import org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer;
import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TupleCrossLanguageTest {
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
public void serialVersion1Compatibility() {
final byte[] byteArr = TestUtil.getResourceBytes("CompactSketchWithDoubleSummary4K_serialVersion1.sk");
Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(byteArr), new DoubleSummaryDeserializer());
Assert.assertTrue(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 8192, 8192 * 0.99);
Assert.assertEquals(sketch.getRetainedEntries(), 4096);
int count = 0;
TupleSketchIterator<DoubleSummary> it = sketch.iterator();
while (it.next()) {
Assert.assertEquals(it.getSummary().getValue(), 1.0);
count++;
}
Assert.assertEquals(count, 4096);
}
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
public void version2Compatibility() {
final byte[] byteArr = TestUtil.getResourceBytes("TupleWithTestIntegerSummary4kTrimmedSerVer2.sk");
Sketch<IntegerSummary> sketch1 = Sketches.heapifySketch(Memory.wrap(byteArr), new IntegerSummaryDeserializer());
// construct the same way
final int lgK = 12;
final int K = 1 << lgK;
final UpdatableSketchBuilder<Integer, IntegerSummary> builder =
new UpdatableSketchBuilder<>(new IntegerSummaryFactory());
final UpdatableSketch<Integer, IntegerSummary> updatableSketch = builder.build();
for (int i = 0; i < 2 * K; i++) {
updatableSketch.update(i, 1);
}
updatableSketch.trim();
Sketch<IntegerSummary> sketch2 = updatableSketch.compact();
Assert.assertEquals(sketch1.getRetainedEntries(), sketch2.getRetainedEntries());
Assert.assertEquals(sketch1.getThetaLong(), sketch2.getThetaLong());
Assert.assertEquals(sketch1.isEmpty(), sketch2.isEmpty());
Assert.assertEquals(sketch1.isEstimationMode(), sketch2.isEstimationMode());
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCppIntegerSummary() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("tuple_int_n" + n + "_cpp.sk"));
final Sketch<IntegerSummary> sketch =
Sketches.heapifySketch(Memory.wrap(bytes), new IntegerSummaryDeserializer());
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
assertTrue(n > 1000 ? sketch.isEstimationMode() : !sketch.isEstimationMode());
assertEquals(sketch.getEstimate(), n, n * 0.03);
final TupleSketchIterator<IntegerSummary> it = sketch.iterator();
while (it.next()) {
assertTrue(it.getHash() < sketch.getThetaLong());
assertTrue(it.getSummary().getValue() < n);
}
}
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateForCppIntegerSummary() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000};
for (int n: nArr) {
final UpdatableSketch<Integer, IntegerSummary> sk =
new UpdatableSketchBuilder<>(new IntegerSummaryFactory()).build();
for (int i = 0; i < n; i++) sk.update(i, i);
Files.newOutputStream(javaPath.resolve("tuple_int_n" + n + "_java.sk")).write(sk.compact().toByteArray());
}
}
@Test(expectedExceptions = SketchesArgumentException.class, groups = {CHECK_CPP_HISTORICAL_FILES})
public void noSupportHeapifyV0_9_1() throws Exception {
final byte[] byteArr = TestUtil.getResourceBytes("ArrayOfDoublesUnion_v0.9.1.sk");
ArrayOfDoublesUnion.heapify(Memory.wrap(byteArr));
}
@Test(expectedExceptions = SketchesArgumentException.class, groups = {CHECK_CPP_HISTORICAL_FILES})
public void noSupportWrapV0_9_1() throws Exception {
final byte[] byteArr = TestUtil.getResourceBytes("ArrayOfDoublesUnion_v0.9.1.sk");
ArrayOfDoublesUnion.wrap(WritableMemory.writableWrap(byteArr));
}
}
| 2,320 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/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.tuple;
import org.apache.datasketches.tuple.adouble.DoubleSummary;
import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory;
import org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations;
import org.testng.annotations.Test;
import org.apache.datasketches.theta.UpdateSketch;
import org.apache.datasketches.theta.UpdateSketchBuilder;
import static org.apache.datasketches.tuple.JaccardSimilarity.dissimilarityTest;
import static org.apache.datasketches.tuple.JaccardSimilarity.exactlyEqual;
import static org.apache.datasketches.tuple.JaccardSimilarity.jaccard;
import static org.apache.datasketches.tuple.JaccardSimilarity.similarityTest;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
/**
* @author Lee Rhodes
* @author David Cromberge
*/
public class JaccardSimilarityTest {
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 checkNullsEmpties1() { // tuple, tuple
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, dsso);
boolean state = jResults[1] > threshold;
println("null \t null:\t" + state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(null, null, dsso);
assertFalse(state);
final UpdatableSketch<Double, DoubleSummary> measured = tupleBldr.setNominalEntries(minK).build();
final UpdatableSketch<Double, DoubleSummary> expected = tupleBldr.setNominalEntries(minK).build();
//check both empty
jResults = jaccard(measured, expected, dsso);
state = jResults[1] > threshold;
println("empty\tempty:\t" + state + "\t" + jaccardString(jResults));
assertTrue(state);
state = exactlyEqual(measured, expected, dsso);
assertTrue(state);
state = exactlyEqual(measured, measured, dsso);
assertTrue(state);
//adjust one
expected.update(1, constSummary);
jResults = jaccard(measured, expected, dsso);
state = jResults[1] > threshold;
println("empty\t 1:\t" + state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(measured, expected, dsso);
assertFalse(state);
println("");
}
@Test
public void checkNullsEmpties2() { // tuple, theta
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, factory.newSummary(), dsso);
boolean state = jResults[1] > threshold;
println("null \t null:\t" + state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(null, null, factory.newSummary(), dsso);
assertFalse(state);
final UpdatableSketch<Double, DoubleSummary> measured = tupleBldr.setNominalEntries(minK).build();
final UpdateSketch expected = thetaBldr.setNominalEntries(minK).build();
//check both empty
jResults = jaccard(measured, expected, factory.newSummary(), dsso);
state = jResults[1] > threshold;
println("empty\tempty:\t" + state + "\t" + jaccardString(jResults));
assertTrue(state);
state = exactlyEqual(measured, expected, factory.newSummary(), dsso);
assertTrue(state);
state = exactlyEqual(measured, measured, dsso);
assertTrue(state);
//adjust one
expected.update(1);
jResults = jaccard(measured, expected, factory.newSummary(), dsso);
state = jResults[1] > threshold;
println("empty\t 1:\t" + state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(measured, expected, factory.newSummary(), dsso);
assertFalse(state);
println("");
}
@Test
public void checkExactMode1() { // tuple, tuple
int k = 1 << 12;
int u = k;
double threshold = 0.9999;
println("Exact Mode, minK: " + k + "\t Th: " + threshold);
final UpdatableSketch<Double, DoubleSummary> measured = tupleBldr.setNominalEntries(k).build();
final UpdatableSketch<Double, DoubleSummary> expected = tupleBldr.setNominalEntries(k).build();
for (int i = 0; i < (u-1); i++) { //one short
measured.update(i, constSummary);
expected.update(i, constSummary);
}
double[] jResults = jaccard(measured, expected, dsso);
boolean state = jResults[1] > threshold;
println(state + "\t" + jaccardString(jResults));
assertTrue(state);
state = exactlyEqual(measured, expected, dsso);
assertTrue(state);
measured.update(u-1, constSummary); //now exactly k entries
expected.update(u, constSummary); //now exactly k entries but differs by one
jResults = jaccard(measured, expected, dsso);
state = jResults[1] > threshold;
println(state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(measured, expected, dsso);
assertFalse(state);
println("");
}
@Test
public void checkExactMode2() { // tuple, theta
int k = 1 << 12;
int u = k;
double threshold = 0.9999;
println("Exact Mode, minK: " + k + "\t Th: " + threshold);
final UpdatableSketch<Double, DoubleSummary> measured = tupleBldr.setNominalEntries(k).build();
final UpdateSketch expected = thetaBldr.setNominalEntries(k).build();
for (int i = 0; i < (u-1); i++) { //one short
measured.update(i, constSummary);
expected.update(i);
}
double[] jResults = jaccard(measured, expected, factory.newSummary(), dsso);
boolean state = jResults[1] > threshold;
println(state + "\t" + jaccardString(jResults));
assertTrue(state);
state = exactlyEqual(measured, expected, factory.newSummary(), dsso);
assertTrue(state);
measured.update(u-1, constSummary); //now exactly k entries
expected.update(u); //now exactly k entries but differs by one
jResults = jaccard(measured, expected, factory.newSummary(), dsso);
state = jResults[1] > threshold;
println(state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(measured, expected, factory.newSummary(), dsso);
assertFalse(state);
println("");
}
@Test
public void checkEstMode1() { // tuple, tuple
int k = 1 << 12;
int u = 1 << 20;
double threshold = 0.9999;
println("Estimation Mode, minK: " + k + "\t Th: " + threshold);
final UpdatableSketch<Double, DoubleSummary> measured = tupleBldr.setNominalEntries(k).build();
final UpdatableSketch<Double, DoubleSummary> expected = tupleBldr.setNominalEntries(k).build();
for (int i = 0; i < u; i++) {
measured.update(i, constSummary);
expected.update(i, constSummary);
}
double[] jResults = jaccard(measured, expected, dsso);
boolean state = jResults[1] > threshold;
println(state + "\t" + jaccardString(jResults));
assertTrue(state);
state = exactlyEqual(measured, expected, dsso);
assertTrue(state);
for (int i = u; i < (u + 50); i++) { //empirically determined
measured.update(i, constSummary);
}
jResults = jaccard(measured, expected, dsso);
state = jResults[1] >= threshold;
println(state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(measured, expected, dsso);
assertFalse(state);
println("");
}
@Test
public void checkEstMode2() { // tuple, theta
int k = 1 << 12;
int u = 1 << 20;
double threshold = 0.9999;
println("Estimation Mode, minK: " + k + "\t Th: " + threshold);
final UpdatableSketch<Double, DoubleSummary> measured = tupleBldr.setNominalEntries(k).build();
final UpdateSketch expected = thetaBldr.setNominalEntries(k).build();
for (int i = 0; i < u; i++) {
measured.update(i, constSummary);
expected.update(i);
}
double[] jResults = jaccard(measured, expected, factory.newSummary(), dsso);
boolean state = jResults[1] > threshold;
println(state + "\t" + jaccardString(jResults));
assertTrue(state);
state = exactlyEqual(measured, expected, factory.newSummary(), dsso);
assertTrue(state);
for (int i = u; i < (u + 50); i++) { //empirically determined
measured.update(i, constSummary);
}
jResults = jaccard(measured, expected, factory.newSummary(), dsso);
state = jResults[1] >= threshold;
println(state + "\t" + jaccardString(jResults));
assertFalse(state);
state = exactlyEqual(measured, expected, factory.newSummary(), dsso);
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 checkSimilarity1() { // tuple, tuple
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);
final UpdatableSketch<Double, DoubleSummary> measured = tupleBldr.setNominalEntries(minK).build();
final UpdatableSketch<Double, DoubleSummary> expected = tupleBldr.setNominalEntries(minK).build();
for (int i = 0; i < u1; i++) {
expected.update(i, constSummary);
}
for (int i = 0; i < u2; i++) {
measured.update(i, constSummary);
}
double[] jResults = jaccard(measured, expected, dsso);
boolean state = similarityTest(measured, expected, dsso, threshold);
println(state + "\t" + jaccardString(jResults));
assertTrue(state);
//check identity case
state = similarityTest(measured, measured, dsso, threshold);
assertTrue(state);
}
/**
* 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 checkSimilarity2() { // tuple, theta
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);
final UpdatableSketch<Double, DoubleSummary> measured = tupleBldr.setNominalEntries(minK).build();
final UpdateSketch expected = thetaBldr.setNominalEntries(minK).build();
for (int i = 0; i < u1; i++) {
expected.update(i);
}
for (int i = 0; i < u2; i++) {
measured.update(i, constSummary);
}
double[] jResults = jaccard(measured, expected, factory.newSummary(), dsso);
boolean state = similarityTest(measured, expected, factory.newSummary(), dsso, threshold);
println(state + "\t" + jaccardString(jResults));
assertTrue(state);
//check identity case
state = similarityTest(measured, measured, dsso, 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 checkDissimilarity1() { // tuple, tuple
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);
final UpdatableSketch<Double, DoubleSummary> measured = tupleBldr.setNominalEntries(minK).setNominalEntries(minK).build();
final UpdatableSketch<Double, DoubleSummary> expected = tupleBldr.setNominalEntries(minK).setNominalEntries(minK).build();
for (int i = 0; i < u1; i++) {
expected.update(i, constSummary);
}
for (int i = 0; i < u2; i++) {
measured.update(i, constSummary);
}
double[] jResults = jaccard(measured, expected, dsso);
boolean state = dissimilarityTest(measured, expected, dsso, threshold);
println(state + "\t" + jaccardString(jResults));
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 checkDissimilarity2() { // tuple, theta
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);
final UpdatableSketch<Double, DoubleSummary> measured = tupleBldr.setNominalEntries(minK).setNominalEntries(minK).build();
final UpdateSketch expected = thetaBldr.setNominalEntries(minK).build();
for (int i = 0; i < u1; i++) {
expected.update(i);
}
for (int i = 0; i < u2; i++) {
measured.update(i, constSummary);
}
double[] jResults = jaccard(measured, expected, factory.newSummary(), dsso);
boolean state = dissimilarityTest(measured, expected, factory.newSummary(), dsso, 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 checkMinK1() { // tuple, tuple
final UpdatableSketch<Double, DoubleSummary> skA = tupleBldr.build(); //4096
final UpdatableSketch<Double, DoubleSummary> skB = tupleBldr.build(); //4096
skA.update(1, constSummary);
skB.update(1, constSummary);
double[] result = jaccard(skA, skB, dsso);
println(result[0] + ", " + result[1] + ", " + result[2]);
for (int i = 1; i < 4096; i++) {
skA.update(i, constSummary);
skB.update(i, constSummary);
}
result = jaccard(skA, skB, dsso);
println(result[0] + ", " + result[1] + ", " + result[2]);
}
@Test
public void checkMinK2() { // tuple, theta
final UpdatableSketch<Double, DoubleSummary> skA = tupleBldr.build(); //4096
final UpdateSketch skB = UpdateSketch.builder().build(); //4096
skA.update(1, constSummary);
skB.update(1);
double[] result = jaccard(skA, skB, factory.newSummary(), dsso);
println(result[0] + ", " + result[1] + ", " + result[2]);
for (int i = 1; i < 4096; i++) {
skA.update(i, constSummary);
skB.update(i);
}
result = jaccard(skA, skB, factory.newSummary(), dsso);
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,321 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/MiscTest.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.tuple;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase;
import org.apache.datasketches.tuple.adouble.DoubleSummary;
import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode;
import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class MiscTest {
@Test
public void checkUpdatableSketchBuilderReset() {
final DoubleSummary.Mode mode = Mode.Sum;
final UpdatableSketchBuilder<Double, DoubleSummary> bldr =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode));
bldr.reset();
final UpdatableSketch<Double,DoubleSummary> sk = bldr.build();
assertTrue(sk.isEmpty());
}
@Test
public void checkStringToByteArray() {
Util.stringToByteArray("");
}
@Test
public void checkDoubleToLongArray() {
final long[] v = Util.doubleToLongArray(-0.0);
assertEquals(v[0], 0);
}
//@Test
public void checkById() {
final int[] ids = {0,1,2, 5, 6 };
final int len = ids.length;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
final int id = ids[i] << 3 | ids[j];
final CornerCase cCase = CornerCase.caseIdToCornerCase(id);
final String interResStr = cCase.getIntersectAction().getActionDescription();
final String anotbResStr = cCase.getAnotbAction().getActionDescription();
println(Integer.toOctalString(id) + "\t" + cCase + "\t" + cCase.getCaseDescription()
+ "\t" + interResStr + "\t" + anotbResStr);
}
}
}
@Test
public void checkCopyCtor() {
final DoubleSummary.Mode mode = Mode.Sum;
final UpdatableSketchBuilder<Double, DoubleSummary> bldr =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode));
bldr.reset();
final UpdatableSketch<Double,DoubleSummary> sk = bldr.build();
sk.update(1.0, 1.0);
assertEquals(sk.getRetainedEntries(), 1);
final UpdatableSketch<Double,DoubleSummary> sk2 = sk.copy();
assertEquals(sk2.getRetainedEntries(), 1);
}
/**
*
* @param o object to print
*/
private static void println(final Object o) {
//System.out.println(o.toString()); //disable here
}
}
| 2,322 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/CompactSketchWithDoubleSummaryTest.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.tuple;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.tuple.adouble.DoubleSummary;
import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode;
import org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer;
import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class CompactSketchWithDoubleSummaryTest {
private final DoubleSummary.Mode mode = Mode.Sum;
@Test
public void emptyFromNonPublicConstructorNullArray() {
CompactSketch<DoubleSummary> sketch =
new CompactSketch<>(null, null, Long.MAX_VALUE, true);
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getRetainedEntries(), 0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertNotNull(it);
Assert.assertFalse(it.next());
sketch.toString();
}
@Test
public void emptyFromNonPublicConstructor() {
long[] keys = new long[0];
DoubleSummary[] summaries =
(DoubleSummary[]) java.lang.reflect.Array.newInstance(DoubleSummary.class, 0);
CompactSketch<DoubleSummary> sketch =
new CompactSketch<>(keys, summaries, Long.MAX_VALUE, true);
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getRetainedEntries(), 0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertNotNull(it);
Assert.assertFalse(it.next());
}
@Test
public void emptyFromQuickSelectSketch() {
UpdatableSketch<Double, DoubleSummary> us =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
CompactSketch<DoubleSummary> sketch = us.compact();
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getRetainedEntries(), 0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertNotNull(it);
Assert.assertFalse(it.next());
}
@Test
public void exactModeFromQuickSelectSketch() {
UpdatableSketch<Double, DoubleSummary> us =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
us.update(1, 1.0);
us.update(2, 1.0);
us.update(3, 1.0);
us.update(1, 1.0);
us.update(2, 1.0);
us.update(3, 1.0);
CompactSketch<DoubleSummary> sketch = us.compact();
Assert.assertFalse(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 3.0);
Assert.assertEquals(sketch.getLowerBound(1), 3.0);
Assert.assertEquals(sketch.getUpperBound(1), 3.0);
Assert.assertEquals(sketch.getRetainedEntries(), 3);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
TupleSketchIterator<DoubleSummary> it = sketch.iterator();
int count = 0;
while (it.next()) {
Assert.assertEquals(it.getSummary().getValue(), 2.0);
count++;
}
Assert.assertEquals(count, 3);
}
@Test
public void serializeDeserializeSmallExact() {
UpdatableSketch<Double, DoubleSummary> us =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
us.update("a", 1.0);
us.update("b", 1.0);
us.update("c", 1.0);
CompactSketch<DoubleSummary> sketch1 = us.compact();
Sketch<DoubleSummary> sketch2 =
Sketches.heapifySketch(Memory.wrap(sketch1.toByteArray()),
new DoubleSummaryDeserializer());
Assert.assertFalse(sketch2.isEmpty());
Assert.assertFalse(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 3.0);
Assert.assertEquals(sketch2.getLowerBound(1), 3.0);
Assert.assertEquals(sketch2.getUpperBound(1), 3.0);
Assert.assertEquals(sketch2.getRetainedEntries(), 3);
Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch2.getTheta(), 1.0);
TupleSketchIterator<DoubleSummary> it = sketch2.iterator();
int count = 0;
while (it.next()) {
Assert.assertEquals(it.getSummary().getValue(), 1.0);
count++;
}
Assert.assertEquals(count, 3);
}
@Test
public void serializeDeserializeEstimation() throws Exception {
UpdatableSketch<Double, DoubleSummary> us =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
for (int i = 0; i < 8192; i++) {
us.update(i, 1.0);
}
us.trim();
CompactSketch<DoubleSummary> sketch1 = us.compact();
byte[] bytes = sketch1.toByteArray();
// for binary testing
//TestUtil.writeBytesToFile(bytes, "CompactSketchWithDoubleSummary4K.sk");
Sketch<DoubleSummary> sketch2 =
Sketches.heapifySketch(Memory.wrap(bytes), new DoubleSummaryDeserializer());
Assert.assertFalse(sketch2.isEmpty());
Assert.assertTrue(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), sketch1.getEstimate());
Assert.assertEquals(sketch2.getThetaLong(), sketch1.getThetaLong());
TupleSketchIterator<DoubleSummary> it = sketch2.iterator();
int count = 0;
while (it.next()) {
Assert.assertEquals(it.getSummary().getValue(), 1.0);
count++;
}
Assert.assertEquals(count, 4096);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void deserializeWrongType() {
UpdatableSketch<Double, DoubleSummary> us =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
for (int i = 0; i < 8192; i++) {
us.update(i, 1.0);
}
CompactSketch<DoubleSummary> sketch1 = us.compact();
Sketches.heapifyUpdatableSketch(Memory.wrap(sketch1.toByteArray()),
new DoubleSummaryDeserializer(),
new DoubleSummaryFactory(mode));
}
}
| 2,323 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/TupleExamplesTest.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.tuple;
import static org.testng.Assert.assertEquals;
import org.apache.datasketches.theta.UpdateSketch;
import org.apache.datasketches.theta.UpdateSketchBuilder;
import org.apache.datasketches.tuple.aninteger.IntegerSummary;
import org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode;
import org.apache.datasketches.tuple.aninteger.IntegerSummaryFactory;
import org.apache.datasketches.tuple.aninteger.IntegerSummarySetOperations;
import org.testng.annotations.Test;
/**
* Tests for Version 2.0.0
* @author Lee Rhodes
*/
public class TupleExamplesTest {
private final IntegerSummary.Mode umode = Mode.Sum;
private final IntegerSummary.Mode imode = Mode.AlwaysOne;
private final IntegerSummarySetOperations isso = new IntegerSummarySetOperations(umode, imode);
private final IntegerSummaryFactory ufactory = new IntegerSummaryFactory(umode);
private final IntegerSummaryFactory ifactory = new IntegerSummaryFactory(imode);
private final UpdateSketchBuilder thetaBldr = UpdateSketch.builder();
private final UpdatableSketchBuilder<Integer, IntegerSummary> tupleBldr =
new UpdatableSketchBuilder<>(ufactory);
@Test
public void example1() {
//Load source sketches
final UpdatableSketch<Integer, IntegerSummary> tupleSk = tupleBldr.build();
final UpdateSketch thetaSk = thetaBldr.build();
for (int i = 1; i <= 12; i++) {
tupleSk.update(i, 1);
thetaSk.update(i + 3);
}
//Union stateful: tuple, theta
final Union<IntegerSummary> union = new Union<>(isso);
union.union(tupleSk);
union.union(thetaSk, ufactory.newSummary().update(1));
final CompactSketch<IntegerSummary> ucsk = union.getResult();
int entries = ucsk.getRetainedEntries();
println("Union Stateful: tuple, theta: " + entries);
final TupleSketchIterator<IntegerSummary> uiter = ucsk.iterator();
int counter = 1;
int twos = 0;
int ones = 0;
while (uiter.next()) {
final int i = uiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1
if (i == 1) { ones++; }
if (i == 2) { twos++; }
}
assertEquals(ones, 6);
assertEquals(twos, 9);
//Intersection stateful: tuple, theta
final Intersection<IntegerSummary> inter = new Intersection<>(isso);
inter.intersect(tupleSk);
inter.intersect(thetaSk, ifactory.newSummary().update(1));
final CompactSketch<IntegerSummary> icsk = inter.getResult();
entries = icsk.getRetainedEntries();
println("Intersection Stateful: tuple, theta: " + entries);
final TupleSketchIterator<IntegerSummary> iiter = icsk.iterator();
counter = 1;
while (iiter.next()) {
final int i = iiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 1
assertEquals(i, 1);
}
}
@Test
public void example2() {
//Load source sketches
final UpdatableSketch<Integer, IntegerSummary> tupleSk1 = tupleBldr.build();
final UpdatableSketch<Integer, IntegerSummary> tupleSk2 = tupleBldr.build();
for (int i = 1; i <= 12; i++) {
tupleSk1.update(i, 1);
tupleSk2.update(i + 3, 1);
}
//Union, stateless: tuple1, tuple2
final Union<IntegerSummary> union = new Union<>(isso);
final CompactSketch<IntegerSummary> ucsk = union.union(tupleSk1, tupleSk2);
int entries = ucsk.getRetainedEntries();
println("Union: " + entries);
final TupleSketchIterator<IntegerSummary> uiter = ucsk.iterator();
int counter = 1;
int twos = 0;
int ones = 0;
while (uiter.next()) {
final int i = uiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1
if (i == 1) { ones++; }
if (i == 2) { twos++; }
}
assertEquals(ones, 6);
assertEquals(twos, 9);
//Intersection stateless: tuple1, tuple2
final Intersection<IntegerSummary> inter = new Intersection<>(isso);
final CompactSketch<IntegerSummary> icsk = inter.intersect(tupleSk1, tupleSk2);
entries = icsk.getRetainedEntries();
println("Intersection: " + entries);
final TupleSketchIterator<IntegerSummary> iiter = icsk.iterator();
counter = 1;
while (iiter.next()) {
final int i = iiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2
assertEquals(i, 1);
}
}
@Test
public void example3() {
//Load source sketches
final UpdatableSketch<Integer, IntegerSummary> tupleSk = tupleBldr.build();
final UpdateSketch thetaSk = thetaBldr.build();
for (int i = 1; i <= 12; i++) {
tupleSk.update(i, 1);
thetaSk.update(i + 3);
}
//Union, stateless: tuple1, tuple2
final Union<IntegerSummary> union = new Union<>(isso);
final CompactSketch<IntegerSummary> ucsk =
union.union(tupleSk, thetaSk, ufactory.newSummary().update(1));
int entries = ucsk.getRetainedEntries();
println("Union: " + entries);
final TupleSketchIterator<IntegerSummary> uiter = ucsk.iterator();
int counter = 1;
int twos = 0;
int ones = 0;
while (uiter.next()) {
final int i = uiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1
if (i == 1) { ones++; }
if (i == 2) { twos++; }
}
assertEquals(ones, 6);
assertEquals(twos, 9);
//Intersection stateless: tuple1, tuple2
final Intersection<IntegerSummary> inter = new Intersection<>(isso);
final CompactSketch<IntegerSummary> icsk =
inter.intersect(tupleSk, thetaSk, ufactory.newSummary().update(1));
entries = icsk.getRetainedEntries();
println("Intersection: " + entries);
final TupleSketchIterator<IntegerSummary> iiter = icsk.iterator();
counter = 1;
while (iiter.next()) {
final int i = iiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2
assertEquals(i, 1);
}
}
@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,324 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/SerializerDeserializerTest.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.tuple;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SerializerDeserializerTest {
@Test
public void validSketchType() {
byte[] bytes = new byte[4];
bytes[SerializerDeserializer.TYPE_BYTE_OFFSET] = (byte) SerializerDeserializer.SketchType.CompactSketch.ordinal();
Assert.assertEquals(SerializerDeserializer.getSketchType(Memory.wrap(bytes)), SerializerDeserializer.SketchType.CompactSketch);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void invalidSketchType() {
byte[] bytes = new byte[4];
bytes[SerializerDeserializer.TYPE_BYTE_OFFSET] = 33;
SerializerDeserializer.getSketchType(Memory.wrap(bytes));
}
// @Test(expectedExceptions = SketchesArgumentException.class)
// public void deserializeFromMemoryUsupportedClass() {
// Memory mem = null;
// SerializerDeserializer.deserializeFromMemory(mem, 0, "bogus");
// }
@Test(expectedExceptions = SketchesArgumentException.class)
public void validateFamilyNotTuple() {
SerializerDeserializer.validateFamily((byte) 1, (byte) 0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void validateFamilyWrongPreambleLength() {
SerializerDeserializer.validateFamily((byte) Family.TUPLE.getID(), (byte) 0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSeedHash() {
org.apache.datasketches.tuple.Util.computeSeedHash(50541);
}
}
| 2,325 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/IntegerSummary.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.tuple;
import org.apache.datasketches.common.ByteArrayUtil;
import org.apache.datasketches.memory.Memory;
/**
* Summary for generic tuple sketches of type Integer.
* This summary keeps an Integer value.
*/
public class IntegerSummary implements UpdatableSummary<Integer> {
private int value_;
/**
* Creates an instance of IntegerSummary with a given starting value.
* @param value starting value
*/
public IntegerSummary(final int value) {
value_ = value;
}
@Override
public IntegerSummary update(final Integer value) {
value_ += value;
return this;
}
@Override
public IntegerSummary copy() {
return new IntegerSummary(value_);
}
/**
* @return current value of the IntegerSummary
*/
public int getValue() {
return value_;
}
private static final int SERIALIZED_SIZE_BYTES = 4;
private static final int VALUE_INDEX = 0;
@Override
public byte[] toByteArray() {
final byte[] bytes = new byte[SERIALIZED_SIZE_BYTES];
ByteArrayUtil.putIntLE(bytes, VALUE_INDEX, value_);
return bytes;
}
/**
* Creates an instance of the IntegerSummary given a serialized representation
* @param mem Memory object with serialized IntegerSummary
* @return DeserializedResult object, which contains a IntegerSummary object and number of bytes
* read from the Memory
*/
public static DeserializeResult<IntegerSummary> fromMemory(final Memory mem) {
return new DeserializeResult<>(new IntegerSummary(mem.getInt(VALUE_INDEX)), SERIALIZED_SIZE_BYTES);
}
}
| 2,326 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/IntegerSummaryFactory.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.tuple;
/**
* Factory for IntegerSummary.
*/
public class IntegerSummaryFactory implements SummaryFactory<IntegerSummary> {
@Override
public IntegerSummary newSummary() {
return new IntegerSummary(0);
}
}
| 2,327 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/TupleExamples2Test.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.tuple;
import static org.testng.Assert.assertEquals;
import org.apache.datasketches.theta.UpdateSketch;
import org.apache.datasketches.theta.UpdateSketchBuilder;
import org.apache.datasketches.tuple.adouble.DoubleSummary;
import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode;
import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory;
import org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations;
import org.testng.annotations.Test;
/**
* Tests for Version 2.0.0
* @author Lee Rhodes
*/
public class TupleExamples2Test {
private final DoubleSummary.Mode umode = Mode.Sum;
private final DoubleSummary.Mode imode = Mode.AlwaysOne;
private final DoubleSummarySetOperations dsso0 = new DoubleSummarySetOperations();
private final DoubleSummarySetOperations dsso1 = new DoubleSummarySetOperations(umode);
private final DoubleSummarySetOperations dsso2 = new DoubleSummarySetOperations(umode, imode);
private final DoubleSummaryFactory ufactory = new DoubleSummaryFactory(umode);
private final DoubleSummaryFactory ifactory = new DoubleSummaryFactory(imode);
private final UpdateSketchBuilder thetaBldr = UpdateSketch.builder();
private final UpdatableSketchBuilder<Double, DoubleSummary> tupleBldr =
new UpdatableSketchBuilder<>(ufactory);
@Test
public void example1() { // stateful: tuple, theta, use dsso2
//Load source sketches
final UpdatableSketch<Double, DoubleSummary> tupleSk = tupleBldr.build();
final UpdateSketch thetaSk = thetaBldr.build();
for (int i = 1; i <= 12; i++) {
tupleSk.update(i, 1.0);
thetaSk.update(i + 3);
}
//Union
final Union<DoubleSummary> union = new Union<>(dsso2);
union.union(tupleSk);
union.union(thetaSk, ufactory.newSummary().update(1.0));
final CompactSketch<DoubleSummary> ucsk = union.getResult();
int entries = ucsk.getRetainedEntries();
println("Union Stateful: tuple, theta: " + entries);
final TupleSketchIterator<DoubleSummary> uiter = ucsk.iterator();
int counter = 1;
int twos = 0;
int ones = 0;
while (uiter.next()) {
final int i = (int)uiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1
if (i == 1) { ones++; }
if (i == 2) { twos++; }
}
assertEquals(ones, 6);
assertEquals(twos, 9);
//Intersection
final Intersection<DoubleSummary> inter = new Intersection<>(dsso2);
inter.intersect(tupleSk);
inter.intersect(thetaSk, ifactory.newSummary().update(1.0));
final CompactSketch<DoubleSummary> icsk = inter.getResult();
entries = icsk.getRetainedEntries();
println("Intersection Stateful: tuple, theta: " + entries);
final TupleSketchIterator<DoubleSummary> iiter = icsk.iterator();
counter = 1;
while (iiter.next()) {
final int i = (int)iiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 1
assertEquals(i, 1);
}
}
@Test
public void example2() { //stateless: tuple1, tuple2, use dsso2
//Load source sketches
final UpdatableSketch<Double, DoubleSummary> tupleSk1 = tupleBldr.build();
final UpdatableSketch<Double, DoubleSummary> tupleSk2 = tupleBldr.build();
for (int i = 1; i <= 12; i++) {
tupleSk1.update(i, 1.0);
tupleSk2.update(i + 3, 1.0);
}
//Union
final Union<DoubleSummary> union = new Union<>(dsso2);
final CompactSketch<DoubleSummary> ucsk = union.union(tupleSk1, tupleSk2);
int entries = ucsk.getRetainedEntries();
println("Union: " + entries);
final TupleSketchIterator<DoubleSummary> uiter = ucsk.iterator();
int counter = 1;
int twos = 0;
int ones = 0;
while (uiter.next()) {
final int i = (int)uiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1
if (i == 1) { ones++; }
if (i == 2) { twos++; }
}
assertEquals(ones, 6);
assertEquals(twos, 9);
//Intersection
final Intersection<DoubleSummary> inter = new Intersection<>(dsso2);
final CompactSketch<DoubleSummary> icsk = inter.intersect(tupleSk1, tupleSk2);
entries = icsk.getRetainedEntries();
println("Intersection: " + entries);
final TupleSketchIterator<DoubleSummary> iiter = icsk.iterator();
counter = 1;
while (iiter.next()) {
final int i = (int)iiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2
assertEquals(i, 1);
}
}
@Test
public void example3() { //stateless: tuple1, tuple2, use dsso2
//Load source sketches
final UpdatableSketch<Double, DoubleSummary> tupleSk = tupleBldr.build();
final UpdateSketch thetaSk = thetaBldr.build();
for (int i = 1; i <= 12; i++) {
tupleSk.update(i, 1.0);
thetaSk.update(i + 3);
}
//Union
final Union<DoubleSummary> union = new Union<>(dsso2);
final CompactSketch<DoubleSummary> ucsk =
union.union(tupleSk, thetaSk, ufactory.newSummary().update(1.0));
int entries = ucsk.getRetainedEntries();
println("Union: " + entries);
final TupleSketchIterator<DoubleSummary> uiter = ucsk.iterator();
int counter = 1;
int twos = 0;
int ones = 0;
while (uiter.next()) {
final int i = (int)uiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1
if (i == 1) { ones++; }
if (i == 2) { twos++; }
}
assertEquals(ones, 6);
assertEquals(twos, 9);
//Intersection
final Intersection<DoubleSummary> inter = new Intersection<>(dsso2);
final CompactSketch<DoubleSummary> icsk =
inter.intersect(tupleSk, thetaSk, ufactory.newSummary().update(1.0));
entries = icsk.getRetainedEntries();
println("Intersection: " + entries);
final TupleSketchIterator<DoubleSummary> iiter = icsk.iterator();
counter = 1;
while (iiter.next()) {
final int i = (int)iiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2
assertEquals(i, 1);
}
}
@Test
public void example4() { //stateful: tuple, theta, Mode=sum for both, use dsso0
//Load source sketches
final UpdatableSketch<Double, DoubleSummary> tupleSk = tupleBldr.build();
final UpdateSketch thetaSk = thetaBldr.build();
for (int i = 1; i <= 12; i++) {
tupleSk.update(i, 1.0);
thetaSk.update(i + 3);
}
//Union
final Union<DoubleSummary> union = new Union<>(dsso0);
union.union(tupleSk);
union.union(thetaSk, ufactory.newSummary().update(1.0));
final CompactSketch<DoubleSummary> ucsk = union.getResult();
int entries = ucsk.getRetainedEntries();
println("Union Stateful: tuple, theta: " + entries);
final TupleSketchIterator<DoubleSummary> uiter = ucsk.iterator();
int counter = 1;
int twos = 0;
int ones = 0;
while (uiter.next()) {
final int i = (int)uiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1
if (i == 1) { ones++; }
if (i == 2) { twos++; }
}
assertEquals(ones, 6);
assertEquals(twos, 9);
//Intersection
final Intersection<DoubleSummary> inter = new Intersection<>(dsso0);
inter.intersect(tupleSk);
inter.intersect(thetaSk, ifactory.newSummary().update(1.0));
final CompactSketch<DoubleSummary> icsk = inter.getResult();
entries = icsk.getRetainedEntries();
println("Intersection Stateful: tuple, theta: " + entries);
final TupleSketchIterator<DoubleSummary> iiter = icsk.iterator();
counter = 1;
while (iiter.next()) {
final int i = (int)iiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 1
assertEquals(i, 2);
}
}
@Test
public void example5() { //stateful, tuple, theta, Mode=sum for both, use dsso1
//Load source sketches
final UpdatableSketch<Double, DoubleSummary> tupleSk = tupleBldr.build();
final UpdateSketch thetaSk = thetaBldr.build();
for (int i = 1; i <= 12; i++) {
tupleSk.update(i, 1.0);
thetaSk.update(i + 3);
}
//Union
final Union<DoubleSummary> union = new Union<>(dsso1);
union.union(tupleSk);
union.union(thetaSk, ufactory.newSummary().update(1.0));
final CompactSketch<DoubleSummary> ucsk = union.getResult();
int entries = ucsk.getRetainedEntries();
println("Union Stateful: tuple, theta: " + entries);
final TupleSketchIterator<DoubleSummary> uiter = ucsk.iterator();
int counter = 1;
int twos = 0;
int ones = 0;
while (uiter.next()) {
final int i = (int)uiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1
if (i == 1) { ones++; }
if (i == 2) { twos++; }
}
assertEquals(ones, 6);
assertEquals(twos, 9);
//Intersection
final Intersection<DoubleSummary> inter = new Intersection<>(dsso1);
inter.intersect(tupleSk);
inter.intersect(thetaSk, ifactory.newSummary().update(1.0));
final CompactSketch<DoubleSummary> icsk = inter.getResult();
entries = icsk.getRetainedEntries();
println("Intersection Stateful: tuple, theta: " + entries);
final TupleSketchIterator<DoubleSummary> iiter = icsk.iterator();
counter = 1;
while (iiter.next()) {
final int i = (int)iiter.getSummary().getValue();
println(counter++ + ", " + i); //9 entries = 1
assertEquals(i, 2);
}
}
@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,328 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleIntersectionTest.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.tuple.adouble;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesStateException;
import org.apache.datasketches.theta.UpdateSketch;
import org.apache.datasketches.theta.UpdateSketchBuilder;
import org.apache.datasketches.tuple.CompactSketch;
import org.apache.datasketches.tuple.Intersection;
import org.apache.datasketches.tuple.Sketch;
import org.apache.datasketches.tuple.TupleSketchIterator;
import org.apache.datasketches.tuple.Sketches;
import org.apache.datasketches.tuple.UpdatableSketch;
import org.apache.datasketches.tuple.UpdatableSketchBuilder;
import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class AdoubleIntersectionTest {
private final DoubleSummary.Mode mode = Mode.Sum;
@Test
public void intersectionNotEmptyNoEntries() {
final UpdatableSketch<Double, DoubleSummary> sketch1 =
new UpdatableSketchBuilder<>
(new DoubleSummaryFactory(mode)).setSamplingProbability(0.01f).build();
sketch1.update("a", 1.0); // this happens to get rejected because of sampling with low probability
final Intersection<DoubleSummary> intersection =
new Intersection<>(new DoubleSummarySetOperations(mode, mode));
intersection.intersect(sketch1);
final CompactSketch<DoubleSummary> result = intersection.getResult();
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0, 0.0001);
Assert.assertTrue(result.getUpperBound(1) > 0);
}
@Test
public void intersectionExactWithEmpty() {
final UpdatableSketch<Double, DoubleSummary> sketch1 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
sketch1.update(1, 1.0);
sketch1.update(2, 1.0);
sketch1.update(3, 1.0);
final Sketch<DoubleSummary> sketch2 = Sketches.createEmptySketch();
final Intersection<DoubleSummary> intersection =
new Intersection<>(new DoubleSummarySetOperations(mode, mode));
intersection.intersect(sketch1);
intersection.intersect(sketch2);
final CompactSketch<DoubleSummary> result = intersection.getResult();
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
}
@Test
public void intersectionExactMode() {
UpdatableSketch<Double, DoubleSummary> sketch1 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
sketch1.update(1, 1.0);
sketch1.update(1, 1.0);
sketch1.update(2, 1.0);
sketch1.update(2, 1.0);
final UpdatableSketch<Double, DoubleSummary> sketch2 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
sketch2.update(2, 1.0);
sketch2.update(2, 1.0);
sketch2.update(3, 1.0);
sketch2.update(3, 1.0);
final Intersection<DoubleSummary> intersection =
new Intersection<>(new DoubleSummarySetOperations(mode, mode));
intersection.intersect(sketch1);
intersection.intersect(sketch2);
final CompactSketch<DoubleSummary> result = intersection.getResult();
Assert.assertEquals(result.getRetainedEntries(), 1);
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 1.0);
Assert.assertEquals(result.getLowerBound(1), 1.0);
Assert.assertEquals(result.getUpperBound(1), 1.0);
final TupleSketchIterator<DoubleSummary> it = result.iterator();
Assert.assertTrue(it.next());
Assert.assertTrue(it.getHash() > 0);
Assert.assertEquals(it.getSummary().getValue(), 4.0);
Assert.assertFalse(it.next());
intersection.reset();
sketch1 = null;
try { intersection.intersect(sketch1); fail();}
catch (final SketchesArgumentException e) { }
}
@Test
public void intersectionDisjointEstimationMode() {
int key = 0;
final UpdatableSketch<Double, DoubleSummary> sketch1 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, 1.0);
}
final UpdatableSketch<Double, DoubleSummary> sketch2 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, 1.0);
}
final Intersection<DoubleSummary> intersection =
new Intersection<>(new DoubleSummarySetOperations(mode, mode));
intersection.intersect(sketch1);
intersection.intersect(sketch2);
CompactSketch<DoubleSummary> result = intersection.getResult();
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertTrue(result.getUpperBound(1) > 0);
// an intersection with no entries must survive more updates
intersection.intersect(sketch1);
result = intersection.getResult();
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertTrue(result.getUpperBound(1) > 0);
}
@Test
public void intersectionEstimationMode() {
int key = 0;
final UpdatableSketch<Double, DoubleSummary> sketch1 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, 1.0);
}
key -= 4096; // overlap half of the entries
final UpdatableSketch<Double, DoubleSummary> sketch2 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, 1.0);
}
final Intersection<DoubleSummary> intersection =
new Intersection<>(new DoubleSummarySetOperations(mode, mode));
intersection.intersect(sketch1);
intersection.intersect(sketch2);
final CompactSketch<DoubleSummary> result = intersection.getResult();
Assert.assertFalse(result.isEmpty());
// crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries())
Assert.assertEquals(result.getEstimate(), 4096.0, 4096 * 0.03);
Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate());
Assert.assertTrue(result.getUpperBound(1) > result.getEstimate());
final TupleSketchIterator<DoubleSummary> it = result.iterator();
while (it.next()) {
Assert.assertEquals(it.getSummary().getValue(), 2.0);
}
}
@Test
public void checkExactIntersectionWithTheta() {
final UpdateSketch thSkNull = null;
final UpdateSketch thSkEmpty = new UpdateSketchBuilder().build();
final UpdateSketch thSk10 = new UpdateSketchBuilder().build();
final UpdateSketch thSk15 = new UpdateSketchBuilder().build();
for (int i = 0; i < 10; i++) { thSk10.update(i); }
for (int i = 0; i < 10; i++) { thSk15.update(i + 5); } //overlap = 5
DoubleSummary dsum = new DoubleSummaryFactory(mode).newSummary();
final Intersection<DoubleSummary> intersection =
new Intersection<>(new DoubleSummarySetOperations(mode, mode));
CompactSketch<DoubleSummary> result;
try { intersection.getResult(); fail(); }
catch (final SketchesStateException e ) { } //OK.
try { intersection.intersect(thSkNull, dsum); fail(); }
catch (final SketchesArgumentException e) { } //OK
intersection.intersect(thSkEmpty, dsum);
result = intersection.getResult();
Assert.assertTrue(result.isEmpty()); //Empty after empty first call
intersection.reset();
intersection.intersect(thSk10, dsum);
result = intersection.getResult();
Assert.assertEquals(result.getEstimate(), 10.0); //Returns valid first call
intersection.reset();
intersection.intersect(thSk10, dsum); // Valid first call
intersection.intersect(thSkEmpty, dsum);
result = intersection.getResult();
Assert.assertTrue(result.isEmpty()); //Returns Empty after empty second call
intersection.reset();
intersection.intersect(thSk10, dsum);
intersection.intersect(thSk15, dsum);
result = intersection.getResult();
Assert.assertEquals(result.getEstimate(), 5.0); //Returns intersection
intersection.reset();
dsum = null;
try { intersection.intersect(thSk10, dsum); fail(); }
catch (final SketchesArgumentException e) { }
}
@Test
public void checkExactIntersectionWithThetaDisjoint() {
final UpdateSketch thSkA = new UpdateSketchBuilder().setLogNominalEntries(10).build();
final UpdateSketch thSkB = new UpdateSketchBuilder().setLogNominalEntries(10).build();
int key = 0;
for (int i = 0; i < 32; i++) { thSkA.update(key++); }
for (int i = 0; i < 32; i++) { thSkB.update(key++); }
final DoubleSummary dsum = new DoubleSummaryFactory(mode).newSummary();
final Intersection<DoubleSummary> intersection =
new Intersection<>(new DoubleSummarySetOperations(mode, mode));
CompactSketch<DoubleSummary> result;
intersection.intersect(thSkA, dsum);
intersection.intersect(thSkB, dsum);
result = intersection.getResult();
Assert.assertEquals(result.getRetainedEntries(), 0);
// an intersection with no entries must survive more updates
intersection.intersect(thSkA, dsum);
result = intersection.getResult();
Assert.assertEquals(result.getRetainedEntries(), 0);
intersection.reset();
}
@Test
public void checkEstimatingIntersectionWithThetaOverlapping() {
final UpdateSketch thSkA = new UpdateSketchBuilder().setLogNominalEntries(4).build();
final UpdateSketch thSkB = new UpdateSketchBuilder().setLogNominalEntries(10).build();
for (int i = 0; i < 64; i++) { thSkA.update(i); } //dense mode, low theta
for (int i = 32; i < 96; i++) { thSkB.update(i); } //exact overlapping
final DoubleSummary dsum = new DoubleSummaryFactory(mode).newSummary();
final Intersection<DoubleSummary> intersection =
new Intersection<>(new DoubleSummarySetOperations(mode, mode));
CompactSketch<DoubleSummary> result;
intersection.intersect(thSkA, dsum);
intersection.intersect(thSkB, dsum);
result = intersection.getResult();
Assert.assertEquals(result.getRetainedEntries(), 14);
thSkB.reset();
for (int i = 100; i < 164; i++) { thSkB.update(i); } //exact, disjoint
intersection.intersect(thSkB, dsum); //remove existing entries
result = intersection.getResult();
Assert.assertEquals(result.getRetainedEntries(), 0);
intersection.intersect(thSkB, dsum);
result = intersection.getResult();
Assert.assertEquals(result.getRetainedEntries(), 0);
}
@Test
public void intersectionEmpty() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
final Intersection<DoubleSummary> intersection =
new Intersection<>(new DoubleSummarySetOperations(mode, mode));
intersection.intersect(sketch);
final CompactSketch<DoubleSummary> result = intersection.getResult();
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
}
}
| 2,329 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/adouble/FilterTest.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.tuple.adouble;
import java.util.Random;
import org.apache.datasketches.tuple.Filter;
import org.apache.datasketches.tuple.Sketch;
import org.apache.datasketches.tuple.Sketches;
import org.apache.datasketches.tuple.UpdatableSketch;
import org.apache.datasketches.tuple.UpdatableSketchBuilder;
import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode;
import org.testng.Assert;
import org.testng.annotations.Test;
public class FilterTest {
private static final int numberOfElements = 100;
private static final Random random = new Random(1);//deterministic for this class
private final DoubleSummary.Mode mode = Mode.Sum;
@Test
public void emptySketch() {
final Sketch<DoubleSummary> sketch = Sketches.createEmptySketch();
final Filter<DoubleSummary> filter = new Filter<>(o -> true);
final Sketch<DoubleSummary> filteredSketch = filter.filter(sketch);
Assert.assertEquals(filteredSketch.getEstimate(), 0.0);
Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong());
Assert.assertTrue(filteredSketch.isEmpty());
Assert.assertEquals(filteredSketch.getLowerBound(1), 0.0);
Assert.assertEquals(filteredSketch.getUpperBound(1), 0.0);
}
@Test
public void nullSketch() {
final Filter<DoubleSummary> filter = new Filter<>(o -> true);
final Sketch<DoubleSummary> filteredSketch = filter.filter(null);
Assert.assertEquals(filteredSketch.getEstimate(), 0.0);
Assert.assertEquals(filteredSketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertTrue(filteredSketch.isEmpty());
Assert.assertEquals(filteredSketch.getLowerBound(1), 0.0);
Assert.assertEquals(filteredSketch.getUpperBound(1), 0.0);
}
@Test
public void filledSketchShouldBehaveTheSame() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
fillSketch(sketch, numberOfElements, 0.0);
final Filter<DoubleSummary> filter = new Filter<>(o -> true);
final Sketch<DoubleSummary> filteredSketch = filter.filter(sketch);
Assert.assertEquals(filteredSketch.getEstimate(), sketch.getEstimate());
Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong());
Assert.assertFalse(filteredSketch.isEmpty());
Assert.assertEquals(filteredSketch.getLowerBound(1), sketch.getLowerBound(1));
Assert.assertEquals(filteredSketch.getUpperBound(1), sketch.getUpperBound(1));
}
@Test
public void filledSketchShouldFilterOutElements() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
fillSketch(sketch, numberOfElements, 0.0);
fillSketch(sketch, 2 * numberOfElements, 1.0);
final Filter<DoubleSummary> filter = new Filter<>(o -> o.getValue() < 0.5);
final Sketch<DoubleSummary> filteredSketch = filter.filter(sketch);
Assert.assertEquals(filteredSketch.getEstimate(), numberOfElements);
Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong());
Assert.assertFalse(filteredSketch.isEmpty());
Assert.assertTrue(filteredSketch.getLowerBound(1) <= filteredSketch.getEstimate());
Assert.assertTrue(filteredSketch.getUpperBound(1) >= filteredSketch.getEstimate());
}
@Test
public void filteringInEstimationMode() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
final int n = 10000;
fillSketch(sketch, n, 0.0);
fillSketch(sketch, 2 * n, 1.0);
final Filter<DoubleSummary> filter = new Filter<>(o -> o.getValue() < 0.5);
final Sketch<DoubleSummary> filteredSketch = filter.filter(sketch);
Assert.assertEquals(filteredSketch.getEstimate(), n, n * 0.05);
Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong());
Assert.assertFalse(filteredSketch.isEmpty());
Assert.assertTrue(filteredSketch.getLowerBound(1) <= filteredSketch.getEstimate());
Assert.assertTrue(filteredSketch.getUpperBound(1) >= filteredSketch.getEstimate());
}
@Test
public void nonEmptySketchWithNoEntries() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(
new DoubleSummaryFactory(mode)).setSamplingProbability(0.0001f).build();
sketch.update(0, 0.0);
Assert.assertFalse(sketch.isEmpty());
Assert.assertEquals(sketch.getRetainedEntries(), 0);
final Filter<DoubleSummary> filter = new Filter<>(o -> true);
final Sketch<DoubleSummary> filteredSketch = filter.filter(sketch);
Assert.assertFalse(filteredSketch.isEmpty());
Assert.assertEquals(filteredSketch.getEstimate(), sketch.getEstimate());
Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong());
Assert.assertEquals(filteredSketch.getLowerBound(1), sketch.getLowerBound(1));
Assert.assertEquals(filteredSketch.getUpperBound(1), sketch.getUpperBound(1));
}
private static void fillSketch(final UpdatableSketch<Double, DoubleSummary> sketch,
final int numberOfElements, final Double sketchValue) {
for (int cont = 0; cont < numberOfElements; cont++) {
sketch.update(random.nextLong(), sketchValue);
}
}
}
| 2,330 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleTest.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.tuple.adouble;
import static org.testng.Assert.assertEquals;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.tuple.Sketch;
import org.apache.datasketches.tuple.TupleSketchIterator;
import org.apache.datasketches.tuple.Sketches;
import org.apache.datasketches.tuple.UpdatableSketch;
import org.apache.datasketches.tuple.UpdatableSketchBuilder;
import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode;
import org.testng.Assert;
import org.testng.annotations.Test;
public class AdoubleTest {
private final DoubleSummary.Mode mode = Mode.Sum;
@Test
public void isEmpty() {
final int lgK = 12;
final DoubleSketch sketch = new DoubleSketch(lgK, mode);
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getTheta(), 1.0);
Assert.assertEquals(sketch.getTheta(), 1.0);
Assert.assertNotNull(sketch.toString());
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertNotNull(it);
Assert.assertFalse(it.next());
}
@Test
public void checkLowK() {
final UpdatableSketchBuilder<Double, DoubleSummary> bldr = new UpdatableSketchBuilder<>(
new DoubleSummaryFactory(Mode.Sum));
bldr.setNominalEntries(16);
final UpdatableSketch<Double,DoubleSummary> sk = bldr.build();
assertEquals(sk.getLgK(), 4);
}
@SuppressWarnings("deprecation")
@Test
public void serDeTest() {
final int lgK = 12;
final int K = 1 << lgK;
final DoubleSketch a1Sk = new DoubleSketch(lgK, Mode.AlwaysOne);
final int m = 2 * K;
for (int key = 0; key < m; key++) {
a1Sk.update(key, 1.0);
}
final double est1 = a1Sk.getEstimate();
final Memory mem = Memory.wrap(a1Sk.toByteArray());
final DoubleSketch a1Sk2 = new DoubleSketch(mem, Mode.AlwaysOne);
final double est2 = a1Sk2.getEstimate();
assertEquals(est1, est2);
}
@Test
public void checkStringKey() {
final int lgK = 12;
final int K = 1 << lgK;
final DoubleSketch a1Sk1 = new DoubleSketch(lgK, Mode.AlwaysOne);
final int m = K / 2;
for (int key = 0; key < m; key++) {
a1Sk1.update(Integer.toHexString(key), 1.0);
}
assertEquals(a1Sk1.getEstimate(), K / 2.0);
}
@Test
public void isEmptyWithSampling() {
final float samplingProbability = 0.1f;
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode))
.setSamplingProbability(samplingProbability).build();
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
}
@Test
public void sampling() {
final float samplingProbability = 0.001f;
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(
new DoubleSummaryFactory(mode)).setSamplingProbability(samplingProbability).build();
sketch.update("a", 1.0);
Assert.assertFalse(sketch.isEmpty());
Assert.assertTrue(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertTrue(sketch.getUpperBound(1) > 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0, 0.0000001);
Assert.assertEquals((float)sketch.getTheta(), samplingProbability);
Assert.assertEquals((float)sketch.getTheta(), samplingProbability);
}
@Test
public void exactMode() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(
new DoubleSummaryFactory(mode)).build();
Assert.assertTrue(sketch.isEmpty());
Assert.assertEquals(sketch.getEstimate(), 0.0);
for (int i = 1; i <= 4096; i++) {
sketch.update(i, 1.0);
}
Assert.assertFalse(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 4096.0);
Assert.assertEquals(sketch.getUpperBound(1), 4096.0);
Assert.assertEquals(sketch.getLowerBound(1), 4096.0);
Assert.assertEquals(sketch.getTheta(), 1.0);
Assert.assertEquals(sketch.getTheta(), 1.0);
int count = 0;
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
while (it.next()) {
Assert.assertEquals(it.getSummary().getValue(), 1.0);
count++;
}
Assert.assertEquals(count, 4096);
sketch.reset();
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getTheta(), 1.0);
Assert.assertEquals(sketch.getTheta(), 1.0);
}
@Test
// The moment of going into the estimation mode is, to some extent, an implementation detail
// Here we assume that presenting as many unique values as twice the nominal
// size of the sketch will result in estimation mode
public void estimationMode() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(
new DoubleSummaryFactory(mode)).build();
Assert.assertEquals(sketch.getEstimate(), 0.0);
for (int i = 1; i <= 8192; i++) {
sketch.update(i, 1.0);
}
Assert.assertTrue(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 8192, 8192 * 0.01);
Assert.assertTrue(sketch.getEstimate() >= sketch.getLowerBound(1));
Assert.assertTrue(sketch.getEstimate() < sketch.getUpperBound(1));
int count = 0;
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
while (it.next()) {
Assert.assertEquals(it.getSummary().getValue(), 1.0);
count++;
}
Assert.assertTrue(count >= 4096);
sketch.reset();
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getTheta(), 1.0);
Assert.assertEquals(sketch.getTheta(), 1.0);
}
@Test
public void estimationModeWithSamplingNoResizing() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(
new DoubleSummaryFactory(mode))
.setSamplingProbability(0.5f)
.setResizeFactor(ResizeFactor.X1).build();
for (int i = 0; i < 16384; i++) {
sketch.update(i, 1.0);
}
Assert.assertTrue(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 16384, 16384 * 0.01);
Assert.assertTrue(sketch.getEstimate() >= sketch.getLowerBound(1));
Assert.assertTrue(sketch.getEstimate() < sketch.getUpperBound(1));
}
@Test
public void updatesOfAllKeyTypes() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
sketch.update(1L, 1.0);
sketch.update(2.0, 1.0);
final byte[] bytes = { 3 };
sketch.update(bytes, 1.0);
final int[] ints = { 4 };
sketch.update(ints, 1.0);
final long[] longs = { 5L };
sketch.update(longs, 1.0);
sketch.update("a", 1.0);
Assert.assertEquals(sketch.getEstimate(), 6.0);
}
@Test
public void doubleSummaryDefaultSumMode() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(
new DoubleSummaryFactory(mode)).build();
{
sketch.update(1, 1.0);
Assert.assertEquals(sketch.getRetainedEntries(), 1);
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 1.0);
Assert.assertFalse(it.next());
}
{
sketch.update(1, 0.7);
Assert.assertEquals(sketch.getRetainedEntries(), 1);
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 1.7);
Assert.assertFalse(it.next());
}
{
sketch.update(1, 0.8);
Assert.assertEquals(sketch.getRetainedEntries(), 1);
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 2.5);
Assert.assertFalse(it.next());
}
}
@Test
public void doubleSummaryMinMode() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(
new DoubleSummaryFactory(DoubleSummary.Mode.Min)).build();
{
sketch.update(1, 1.0);
Assert.assertEquals(sketch.getRetainedEntries(), 1);
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 1.0);
Assert.assertFalse(it.next());
}
{
sketch.update(1, 0.7);
Assert.assertEquals(sketch.getRetainedEntries(), 1);
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 0.7);
Assert.assertFalse(it.next());
}
{
sketch.update(1, 0.8);
Assert.assertEquals(sketch.getRetainedEntries(), 1);
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 0.7);
Assert.assertFalse(it.next());
}
}
@Test
public void doubleSummaryMaxMode() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(
new DoubleSummaryFactory(DoubleSummary.Mode.Max)).build();
{
sketch.update(1, 1.0);
Assert.assertEquals(sketch.getRetainedEntries(), 1);
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 1.0);
Assert.assertFalse(it.next());
}
{
sketch.update(1, 0.7);
Assert.assertEquals(sketch.getRetainedEntries(), 1);
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 1.0);
Assert.assertFalse(it.next());
}
{
sketch.update(1, 2.0);
Assert.assertEquals(sketch.getRetainedEntries(), 1);
final TupleSketchIterator<DoubleSummary> it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 2.0);
Assert.assertFalse(it.next());
}
}
@SuppressWarnings("deprecation")
@Test
public void serializeDeserializeExact() throws Exception {
final UpdatableSketch<Double, DoubleSummary> sketch1 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
sketch1.update(1, 1.0);
final UpdatableSketch<Double, DoubleSummary> sketch2 = Sketches.heapifyUpdatableSketch(
Memory.wrap(sketch1.toByteArray()),
new DoubleSummaryDeserializer(), new DoubleSummaryFactory(mode));
Assert.assertEquals(sketch2.getEstimate(), 1.0);
final TupleSketchIterator<DoubleSummary> it = sketch2.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 1.0);
Assert.assertFalse(it.next());
// the same key, so still one unique
sketch2.update(1, 1.0);
Assert.assertEquals(sketch2.getEstimate(), 1.0);
sketch2.update(2, 1.0);
Assert.assertEquals(sketch2.getEstimate(), 2.0);
}
@SuppressWarnings("deprecation")
@Test
public void serializeDeserializeEstimationNoResizing() throws Exception {
final UpdatableSketch<Double, DoubleSummary> sketch1 =
new UpdatableSketchBuilder<>(
new DoubleSummaryFactory(mode)).setResizeFactor(ResizeFactor.X1).build();
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 8192; i++) {
sketch1.update(i, 1.0);
}
}
sketch1.trim();
final byte[] bytes = sketch1.toByteArray();
//for binary testing
//TestUtil.writeBytesToFile(bytes, "UpdatableSketchWithDoubleSummary4K.sk");
final Sketch<DoubleSummary> sketch2 =
Sketches.heapifySketch(Memory.wrap(bytes), new DoubleSummaryDeserializer());
Assert.assertTrue(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 8192, 8192 * 0.99);
Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta());
final TupleSketchIterator<DoubleSummary> it = sketch2.iterator();
int count = 0;
while (it.next()) {
Assert.assertEquals(it.getSummary().getValue(), 10.0);
count++;
}
Assert.assertEquals(count, 4096);
}
@SuppressWarnings("deprecation")
@Test
public void serializeDeserializeSampling() throws Exception {
final int sketchSize = 16384;
final int numberOfUniques = sketchSize;
final UpdatableSketch<Double, DoubleSummary> sketch1 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode))
.setNominalEntries(sketchSize).setSamplingProbability(0.5f).build();
for (int i = 0; i < numberOfUniques; i++) {
sketch1.update(i, 1.0);
}
final Sketch<DoubleSummary> sketch2 = Sketches.heapifySketch(
Memory.wrap(sketch1.toByteArray()), new DoubleSummaryDeserializer());
Assert.assertTrue(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate() / numberOfUniques, 1.0, 0.01);
Assert.assertEquals(sketch2.getRetainedEntries() / (double) numberOfUniques, 0.5, 0.01);
Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta());
}
@Test
public void checkUpdatableSketch() {
final DoubleSummaryFactory dsumFact = new DoubleSummaryFactory(mode);
//DoubleSummary dsum = dsumFact.newSummary();
final UpdatableSketchBuilder<Double, DoubleSummary> bldr = new UpdatableSketchBuilder<>(dsumFact);
final UpdatableSketch<Double, DoubleSummary> usk = bldr.build();
final byte[] byteArr = new byte[0];
usk.update(byteArr, 0.0);
final int[] intArr = new int[0];
usk.update(intArr, 1.0);
final long[] longArr = new long[0];
usk.update(longArr, 2.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void invalidSamplingProbability() {
new UpdatableSketchBuilder<>
(new DoubleSummaryFactory(mode)).setSamplingProbability(2f).build();
}
}
| 2,331 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleAnotBTest.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.tuple.adouble;
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.theta.UpdateSketch;
import org.apache.datasketches.theta.UpdateSketchBuilder;
import org.apache.datasketches.tuple.AnotB;
import org.apache.datasketches.tuple.CompactSketch;
import org.apache.datasketches.tuple.Sketch;
import org.apache.datasketches.tuple.TupleSketchIterator;
import org.apache.datasketches.tuple.UpdatableSketch;
import org.apache.datasketches.tuple.UpdatableSketchBuilder;
import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class AdoubleAnotBTest {
private static final DoubleSummary.Mode mode = Mode.Sum;
private final Results results = new Results();
private static void threeMethodsWithTheta(
final AnotB<DoubleSummary> aNotB,
final Sketch<DoubleSummary> skA,
final Sketch<DoubleSummary> skB,
final org.apache.datasketches.theta.Sketch skThetaB,
final Results results)
{
CompactSketch<DoubleSummary> result;
//Stateful, A = Tuple, B = Tuple
if (skA != null) {
try {
aNotB.setA(skA);
aNotB.notB(skB);
result = aNotB.getResult(true);
results.check(result);
}
catch (final SketchesArgumentException e) { }
}
//Stateless A = Tuple, B = Tuple
if (skA == null || skB == null) {
try {
result = AnotB.aNotB(skA, skB);
fail();
}
catch (final SketchesArgumentException e) { }
} else {
result = AnotB.aNotB(skA, skB);
results.check(result);
}
//Stateless A = Tuple, B = Theta
if (skA == null || skThetaB == null) {
try { result = AnotB.aNotB(skA, skThetaB); fail(); }
catch (final SketchesArgumentException e) { }
} else {
result = AnotB.aNotB(skA, skThetaB);
results.check(result);
}
//Stateful A = Tuple, B = Tuple
if (skA == null) {
try { aNotB.setA(skA); fail(); }
catch (final SketchesArgumentException e) { }
} else {
aNotB.setA(skA);
aNotB.notB(skB);
result = aNotB.getResult(true);
results.check(result);
}
//Stateful A = Tuple, B = Theta
if (skA == null) {
try { aNotB.setA(skA); fail(); }
catch (final SketchesArgumentException e) { }
} else {
aNotB.setA(skA);
aNotB.notB(skThetaB);
result = aNotB.getResult(false);
results.check(result);
result = aNotB.getResult(true);
results.check(result);
}
}
private static class Results {
private int retEnt = 0;
private boolean empty = true;
private double expect = 0.0;
private double tol = 0.0;
private double sum = 0.0;
Results() {}
Results set(final int retEnt, final boolean empty,
final double expect, final double tol, final double sum) {
this.retEnt = retEnt; //retained Entries
this.empty = empty;
this.expect = expect; //expected estimate
this.tol = tol; //tolerance
this.sum = sum;
return this;
}
void check(final CompactSketch<DoubleSummary> result) {
assertEquals(result.getRetainedEntries(), retEnt);
assertEquals(result.isEmpty(), empty);
if (result.getTheta() < 1.0) {
final double est = result.getEstimate();
assertEquals(est, expect, expect * tol);
assertTrue(result.getUpperBound(1) > est);
assertTrue(result.getLowerBound(1) <= est);
} else {
assertEquals(result.getEstimate(), expect, 0.0);
assertEquals(result.getUpperBound(1), expect, 0.0);
assertEquals(result.getLowerBound(1), expect, 0.0);
}
final TupleSketchIterator<DoubleSummary> it = result.iterator();
while (it.next()) {
Assert.assertEquals(it.getSummary().getValue(), sum);
}
}
} //End class Results
private static UpdatableSketch<Double, DoubleSummary> buildUpdatableTuple() {
return new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
}
private static UpdateSketch buildUpdateTheta() {
return new UpdateSketchBuilder().build();
}
/*****************************************/
@Test
public void aNotBNullEmptyCombinations() {
final AnotB<DoubleSummary> aNotB = new AnotB<>();
// calling getResult() before calling update() should yield an empty set
final CompactSketch<DoubleSummary> result = aNotB.getResult(true);
results.set(0, true, 0.0, 0.0, 0.0).check(result);
final UpdatableSketch<Double, DoubleSummary> sketch = buildUpdatableTuple();
final UpdateSketch skTheta = buildUpdateTheta();
threeMethodsWithTheta(aNotB, null, null, null, results);
threeMethodsWithTheta(aNotB, sketch, null, null, results);
threeMethodsWithTheta(aNotB, null, sketch, null, results);
threeMethodsWithTheta(aNotB, sketch, sketch, null, results);
threeMethodsWithTheta(aNotB, null, null, skTheta, results);
threeMethodsWithTheta(aNotB, sketch, null, skTheta, results);
threeMethodsWithTheta(aNotB, null, sketch, skTheta, results);
threeMethodsWithTheta(aNotB, sketch, sketch, skTheta, results);
}
@Test
public void aNotBCheckDoubleSetAs() {
final UpdatableSketch<Double, DoubleSummary> skA = buildUpdatableTuple();
skA.update(1, 1.0);
skA.update(2, 1.0);
final UpdatableSketch<Double, DoubleSummary> skA2 = buildUpdatableTuple();
final AnotB<DoubleSummary> aNotB = new AnotB<>();
aNotB.setA(skA);
assertEquals(aNotB.getResult(false).isEmpty(), false);
aNotB.setA(skA2);
assertEquals(aNotB.getResult(false).isEmpty(), true);
}
@Test
public void aNotBEmptyExact() {
final UpdatableSketch<Double, DoubleSummary> sketchA = buildUpdatableTuple();
final UpdatableSketch<Double, DoubleSummary> sketchB = buildUpdatableTuple();
sketchB.update(1, 1.0);
sketchB.update(2, 1.0);
final UpdateSketch skThetaB = buildUpdateTheta();
skThetaB.update(1);
skThetaB.update(2);
final AnotB<DoubleSummary> aNotB = new AnotB<>();
results.set(0, true, 0.0, 0.0, 0.0);
threeMethodsWithTheta(aNotB, sketchA, sketchB, skThetaB, results);
}
@Test
public void aNotBExactEmpty() {
final UpdatableSketch<Double, DoubleSummary> sketchA = buildUpdatableTuple();
sketchA.update(1, 1.0);
sketchA.update(2, 1.0);
final UpdatableSketch<Double, DoubleSummary> sketchB = buildUpdatableTuple();
final UpdateSketch skThetaB = buildUpdateTheta();
final AnotB<DoubleSummary> aNotB = new AnotB<>();
results.set(2, false, 2.0, 0.0, 1.0);
threeMethodsWithTheta(aNotB, sketchA, sketchB, skThetaB, results);
// same thing, but compact sketches
threeMethodsWithTheta(aNotB, sketchA.compact(), sketchB.compact(), skThetaB.compact(), results);
}
@Test
public void aNotBExactOverlap() {
final UpdatableSketch<Double, DoubleSummary> sketchA = buildUpdatableTuple();
sketchA.update(1, 1.0);
sketchA.update(1, 1.0);
sketchA.update(2, 1.0);
sketchA.update(2, 1.0);
final UpdatableSketch<Double, DoubleSummary> sketchB = buildUpdatableTuple();
sketchB.update(2, 1.0);
sketchB.update(2, 1.0);
sketchB.update(3, 1.0);
sketchB.update(3, 1.0);
final UpdateSketch skThetaB = buildUpdateTheta();
skThetaB.update(2);
skThetaB.update(3);
final AnotB<DoubleSummary> aNotB = new AnotB<>();
results.set(1, false, 1.0, 0.0, 2.0);
threeMethodsWithTheta(aNotB, sketchA, sketchB, skThetaB, results);
}
@Test
public void aNotBEstimationOverlap() {
final UpdatableSketch<Double, DoubleSummary> sketchA = buildUpdatableTuple();
for (int i = 0; i < 8192; i++) {
sketchA.update(i, 1.0);
}
final UpdatableSketch<Double, DoubleSummary> sketchB = buildUpdatableTuple();
for (int i = 0; i < 4096; i++) {
sketchB.update(i, 1.0);
}
final UpdateSketch skThetaB = buildUpdateTheta();
for (int i = 0; i < 4096; i++) {
skThetaB.update(i);
}
final AnotB<DoubleSummary> aNotB = new AnotB<>();
results.set(2123, false, 4096.0, 0.03, 1.0);
threeMethodsWithTheta(aNotB, sketchA, sketchB, skThetaB, results);
// same thing, but compact sketches
threeMethodsWithTheta(aNotB, sketchA.compact(), sketchB.compact(), skThetaB.compact(), results);
}
@Test
public void aNotBEstimationOverlapLargeB() {
final UpdatableSketch<Double, DoubleSummary> sketchA = buildUpdatableTuple();
for (int i = 0; i < 10_000; i++) {
sketchA.update(i, 1.0);
}
final UpdatableSketch<Double, DoubleSummary> sketchB = buildUpdatableTuple();
for (int i = 0; i < 100_000; i++) {
sketchB.update(i + 8000, 1.0);
}
final UpdateSketch skThetaB = buildUpdateTheta();
for (int i = 0; i < 100_000; i++) {
skThetaB.update(i + 8000);
}
final int expected = 8_000;
final AnotB<DoubleSummary> aNotB = new AnotB<>();
results.set(376, false, expected, 0.1, 1.0);
threeMethodsWithTheta(aNotB, sketchA, sketchB, skThetaB, results);
// same thing, but compact sketches
threeMethodsWithTheta(aNotB, sketchA.compact(), sketchB.compact(), skThetaB.compact(), results);
}
}
| 2,332 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleUnionTest.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.tuple.adouble;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.theta.UpdateSketch;
import org.apache.datasketches.theta.UpdateSketchBuilder;
import org.apache.datasketches.tuple.CompactSketch;
import org.apache.datasketches.tuple.TupleSketchIterator;
import org.apache.datasketches.tuple.Union;
import org.apache.datasketches.tuple.UpdatableSketch;
import org.apache.datasketches.tuple.UpdatableSketchBuilder;
import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class AdoubleUnionTest {
private final DoubleSummary.Mode mode = Mode.Sum;
@Test
public void unionEmptySampling() {
final UpdatableSketch<Double, DoubleSummary> sketch =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).setSamplingProbability(0.01f).build();
sketch.update(1, 1.0);
Assert.assertEquals(sketch.getRetainedEntries(), 0); // not retained due to low sampling probability
final Union<DoubleSummary> union = new Union<>(new DoubleSummarySetOperations(mode, mode));
union.union(sketch);
final CompactSketch<DoubleSummary> result = union.getResult();
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertFalse(result.isEmpty());
Assert.assertTrue(result.isEstimationMode());
Assert.assertEquals(result.getEstimate(), 0.0);
}
@Test
public void unionExactMode() {
final UpdatableSketch<Double, DoubleSummary> sketch1 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
sketch1.update(1, 1.0);
sketch1.update(1, 1.0);
sketch1.update(1, 1.0);
sketch1.update(2, 1.0);
final UpdatableSketch<Double, DoubleSummary> sketch2 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
sketch2.update(2, 1.0);
sketch2.update(2, 1.0);
sketch2.update(3, 1.0);
sketch2.update(3, 1.0);
sketch2.update(3, 1.0);
final Union<DoubleSummary> union = new Union<>(new DoubleSummarySetOperations(mode, mode));
union.union(sketch1);
union.union(sketch2);
CompactSketch<DoubleSummary> result = union.getResult();
Assert.assertEquals(result.getEstimate(), 3.0);
final TupleSketchIterator<DoubleSummary> it = result.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 3.0);
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 3.0);
Assert.assertTrue(it.next());
Assert.assertEquals(it.getSummary().getValue(), 3.0);
Assert.assertFalse(it.next());
union.reset();
result = union.getResult();
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertTrue(result.isEmpty());
Assert.assertFalse(result.isEstimationMode());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
Assert.assertEquals(result.getTheta(), 1.0);
}
@Test
public void unionEstimationMode() {
int key = 0;
final UpdatableSketch<Double, DoubleSummary> sketch1 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, 1.0);
}
key -= 4096; // overlap half of the entries
final UpdatableSketch<Double, DoubleSummary> sketch2 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, 1.0);
}
final Union<DoubleSummary> union = new Union<>(4096, new DoubleSummarySetOperations(mode, mode));
union.union(sketch1);
union.union(sketch2);
final CompactSketch<DoubleSummary> result = union.getResult();
Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01);
Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate());
Assert.assertTrue(result.getUpperBound(1) > result.getEstimate());
}
@Test
public void unionMixedMode() {
int key = 0;
final UpdatableSketch<Double, DoubleSummary> sketch1 =
new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
for (int i = 0; i < 1000; i++) {
sketch1.update(key++, 1.0);
//System.out.println("theta1=" + sketch1.getTheta() + " " + sketch1.getThetaLong());
}
key -= 500; // overlap half of the entries
final UpdatableSketch<Double, DoubleSummary> sketch2 =
new UpdatableSketchBuilder<>
(new DoubleSummaryFactory(mode)).setSamplingProbability(0.2f).build();
for (int i = 0; i < 20000; i++) {
sketch2.update(key++, 1.0);
//System.out.println("theta2=" + sketch2.getTheta() + " " + sketch2.getThetaLong());
}
final Union<DoubleSummary> union = new Union<>(4096, new DoubleSummarySetOperations(mode, mode));
union.union(sketch1);
union.union(sketch2);
final CompactSketch<DoubleSummary> result = union.getResult();
Assert.assertEquals(result.getEstimate(), 20500.0, 20500 * 0.01);
Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate());
Assert.assertTrue(result.getUpperBound(1) > result.getEstimate());
}
@Test
public void checkUnionUpdateWithTheta() {
final Union<DoubleSummary> union = new Union<>(new DoubleSummarySetOperations(mode, mode));
UpdateSketch usk = null;
DoubleSummary dsum = null;
try { union.union(usk, dsum); fail(); }
catch (final SketchesArgumentException e) { }
usk = new UpdateSketchBuilder().build();
try { union.union(usk, dsum); fail(); }
catch (final SketchesArgumentException e) { }
dsum = new DoubleSummaryFactory(mode).newSummary();
for (int i = 0; i < 10; i++) { usk.update(i); }
union.union(usk, dsum);
Assert.assertEquals(union.getResult().getEstimate(), 10.0);
}
}
| 2,333 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryTest.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.tuple.strings;
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.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.tuple.DeserializeResult;
/**
* @author Lee Rhodes
*/
public class ArrayOfStringsSummaryTest {
@Test
public void checkToByteArray() {
String[] strArr = new String[] {"abcd", "abcd", "abcd"};
ArrayOfStringsSummary nsum = new ArrayOfStringsSummary(strArr);
ArrayOfStringsSummary copy = nsum.copy();
assertTrue(copy.equals(nsum));
byte[] out = nsum.toByteArray();
Memory mem = Memory.wrap(out);
ArrayOfStringsSummary nsum2 = new ArrayOfStringsSummary(mem);
String[] nodesArr = nsum2.getValue();
for (String s : nodesArr) {
println(s);
}
println("\nfromMemory(mem)");
DeserializeResult<ArrayOfStringsSummary> dres = ArrayOfStringsSummaryDeserializer.fromMemory(mem);
ArrayOfStringsSummary nsum3 = dres.getObject();
nodesArr = nsum3.getValue();
for (String s : nodesArr) {
println(s);
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkNumNodes() {
ArrayOfStringsSummary.checkNumNodes(200);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInBytes() {
Memory mem = Memory.wrap(new byte[100]);
ArrayOfStringsSummary.checkInBytes(mem, 200);
}
@SuppressWarnings("unlikely-arg-type")
@Test
public void checkHashCode() {
String[] strArr = new String[] {"abcd", "abcd", "abcd"};
ArrayOfStringsSummary sum1 = new ArrayOfStringsSummary(strArr);
ArrayOfStringsSummary sum2 = new ArrayOfStringsSummary(strArr);
int hc1 = sum1.hashCode();
int hc2 = sum2.hashCode();
assertEquals(hc1, hc2);
assertTrue(sum1.equals(sum2));
assertFalse(sum1.equals(hc2));
assertFalse(sum1.equals(null));
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s);
}
}
| 2,334 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSketchTest.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.tuple.strings;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.tuple.AnotB;
import org.apache.datasketches.tuple.CompactSketch;
import org.apache.datasketches.tuple.Intersection;
import org.apache.datasketches.tuple.TupleSketchIterator;
import org.apache.datasketches.tuple.Union;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class ArrayOfStringsSketchTest {
private static final String LS = System.getProperty("line.separator");
@SuppressWarnings("deprecation")
@Test
public void checkSketch() {
ArrayOfStringsSketch sketch1 = new ArrayOfStringsSketch();
String[][] strArrArr = {{"a","b"},{"c","d"},{"e","f"}};
int len = strArrArr.length;
for (int i = 0; i < len; i++) {
sketch1.update(strArrArr[i], strArrArr[i]);
}
sketch1.update(strArrArr[0], strArrArr[0]); //insert duplicate
//printSummaries(sketch1.iterator());
byte[] array = sketch1.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(array);
ArrayOfStringsSketch sketch2 = new ArrayOfStringsSketch(wmem);
//printSummaries(sketch2.iterator());
checkSummaries(sketch2, sketch2);
String[] strArr3 = {"g", "h" };
sketch2.update(strArr3, strArr3);
Union<ArrayOfStringsSummary> union = new Union<>(new ArrayOfStringsSummarySetOperations());
union.union(sketch1);
union.union(sketch2);
CompactSketch<ArrayOfStringsSummary> csk = union.getResult();
//printSummaries(csk.iterator());
assertEquals(csk.getRetainedEntries(), 4);
Intersection<ArrayOfStringsSummary> inter =
new Intersection<>(new ArrayOfStringsSummarySetOperations());
inter.intersect(sketch1);
inter.intersect(sketch2);
csk = inter.getResult();
assertEquals(csk.getRetainedEntries(), 3);
AnotB<ArrayOfStringsSummary> aNotB = new AnotB<>();
aNotB.setA(sketch2);
aNotB.notB(sketch1);
csk = aNotB.getResult(true);
assertEquals(csk.getRetainedEntries(), 1);
}
private static void checkSummaries(ArrayOfStringsSketch sk1, ArrayOfStringsSketch sk2) {
TupleSketchIterator<ArrayOfStringsSummary> it1 = sk1.iterator();
TupleSketchIterator<ArrayOfStringsSummary> it2 = sk2.iterator();
while(it1.next() && it2.next()) {
ArrayOfStringsSummary sum1 = it1.getSummary();
ArrayOfStringsSummary sum2 = it2.getSummary();
assertTrue(sum1.equals(sum2));
}
}
static void printSummaries(TupleSketchIterator<ArrayOfStringsSummary> it) {
while (it.next()) {
String[] strArr = it.getSummary().getValue();
for (String s : strArr) {
print(s + ", ");
}
println("");
}
}
@Test
public void checkCopyCtor() {
ArrayOfStringsSketch sk1 = new ArrayOfStringsSketch();
String[][] strArrArr = {{"a","b"},{"c","d"},{"e","f"}};
int len = strArrArr.length;
for (int i = 0; i < len; i++) {
sk1.update(strArrArr[i], strArrArr[i]);
}
assertEquals(sk1.getRetainedEntries(), 3);
final ArrayOfStringsSketch sk2 = sk1.copy();
assertEquals(sk2.getRetainedEntries(), 3);
}
@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.out.print(s); //disable here
}
}
| 2,335 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/aninteger/IntegerSketchTest.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.tuple.aninteger;
import static org.testng.Assert.assertEquals;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.tuple.AnotB;
import org.apache.datasketches.tuple.CompactSketch;
import org.apache.datasketches.tuple.Intersection;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class IntegerSketchTest {
@SuppressWarnings("deprecation")
@Test
public void serDeTest() {
final int lgK = 12;
final int K = 1 << lgK;
final IntegerSummary.Mode a1Mode = IntegerSummary.Mode.AlwaysOne;
final IntegerSketch a1Sk = new IntegerSketch(lgK, a1Mode);
final int m = 2 * K;
for (int i = 0; i < m; i++) {
a1Sk.update(i, 1);
}
final double est1 = a1Sk.getEstimate();
final Memory mem = Memory.wrap(a1Sk.toByteArray());
final IntegerSketch a1Sk2 = new IntegerSketch(mem, a1Mode);
final double est2 = a1Sk2.getEstimate();
assertEquals(est1, est2);
}
@Test
public void intersectTest() {
final int lgK = 12;
final int K = 1 << lgK;
final IntegerSummary.Mode a1Mode = IntegerSummary.Mode.AlwaysOne;
final IntegerSketch a1Sk1 = new IntegerSketch(lgK, a1Mode);
final IntegerSketch a1Sk2 = new IntegerSketch(lgK, a1Mode);
final int m = 2 * K;
for (int i = 0; i < m; i++) {
a1Sk1.update(i, 1);
a1Sk2.update(i + m/2, 1);
}
final Intersection<IntegerSummary> inter =
new Intersection<>(new IntegerSummarySetOperations(a1Mode, a1Mode));
inter.intersect(a1Sk1);
inter.intersect(a1Sk2);
final CompactSketch<IntegerSummary> csk = inter.getResult();
assertEquals(csk.getEstimate(), K * 1.0, K * .03);
}
@Test
public void aNotBTest() {
final int lgK = 4;
final int u = 5;
final IntegerSummary.Mode a1Mode = IntegerSummary.Mode.AlwaysOne;
final IntegerSketch a1Sk1 = new IntegerSketch(lgK, a1Mode);
final IntegerSketch a1Sk2 = null;//new IntegerSketch(lgK, a1Mode);
final AnotB<IntegerSummary> anotb = new AnotB<>();
for (int i = 0; i < u; i++) {
a1Sk1.update(i, 1);
}
anotb.setA(a1Sk1);
anotb.notB(a1Sk2);
final CompactSketch<IntegerSummary> cSk = anotb.getResult(true);
assertEquals((int)cSk.getEstimate(), u);
}
@Test
public void checkMinMaxMode() {
final int lgK = 12;
final int K = 1 << lgK;
final IntegerSummary.Mode minMode = IntegerSummary.Mode.Min;
final IntegerSummary.Mode maxMode = IntegerSummary.Mode.Max;
final IntegerSketch a1Sk1 = new IntegerSketch(lgK, minMode);
final IntegerSketch a1Sk2 = new IntegerSketch(lgK, maxMode);
final int m = K / 2;
for (int key = 0; key < m; key++) {
a1Sk1.update(key, 1);
a1Sk1.update(key, 0);
a1Sk1.update(key, 2);
a1Sk2.update(key + m/2, 1);
a1Sk2.update(key + m/2, 0);
a1Sk2.update(key + m/2, 2);
}
final double est1 = a1Sk1.getEstimate();
final double est2 = a1Sk2.getEstimate();
assertEquals(est1, est2);
}
@Test
public void checkStringKey() {
final int lgK = 12;
final int K = 1 << lgK;
final IntegerSummary.Mode a1Mode = IntegerSummary.Mode.AlwaysOne;
final IntegerSketch a1Sk1 = new IntegerSketch(lgK, a1Mode);
final int m = K / 2;
for (int key = 0; key < m; key++) {
a1Sk1.update(Integer.toHexString(key), 1);
}
assertEquals(a1Sk1.getEstimate(), K / 2.0);
}
/**
* @param o object to print
*/
static void println(final Object o) {
//System.out.println(o.toString()); //Disable
}
/**
* @param fmt format
* @param args arguments
*/
static void printf(final String fmt, final Object ... args) {
//System.out.printf(fmt, args); //Disable
}
}
| 2,336 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/aninteger/EngagementTest.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.tuple.aninteger;
import static java.lang.Math.exp;
import static java.lang.Math.log;
import static java.lang.Math.round;
import static org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode.AlwaysOne;
import static org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode.Sum;
import org.apache.datasketches.tuple.CompactSketch;
import org.apache.datasketches.tuple.TupleSketchIterator;
import org.apache.datasketches.tuple.Union;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class EngagementTest {
public static final int numStdDev = 2;
@Test
public void computeEngagementHistogram() {
final int lgK = 8; //Using a larger sketch >= 9 will produce exact results for this little example
final int K = 1 << lgK;
final int days = 30;
int v = 0;
final IntegerSketch[] skArr = new IntegerSketch[days];
for (int i = 0; i < days; i++) {
skArr[i] = new IntegerSketch(lgK, AlwaysOne);
}
for (int i = 0; i <= days; i++) { //31 generating indices for symmetry
final int numIds = numIDs(days, i);
final int numDays = numDays(days, i);
final int myV = v++;
for (int d = 0; d < numDays; d++) {
for (int id = 0; id < numIds; id++) {
skArr[d].update(myV + id, 1);
}
}
v += numIds;
}
unionOps(K, Sum, skArr);
}
private static int numIDs(final int totalDays, final int index) {
final double d = totalDays;
final double i = index;
return (int)round(exp(i * log(d) / d));
}
private static int numDays(final int totalDays, final int index) {
final double d = totalDays;
final double i = index;
return (int)round(exp((d - i) * log(d) / d));
}
private static void unionOps(final int K, final IntegerSummary.Mode mode, final IntegerSketch ... sketches) {
final IntegerSummarySetOperations setOps = new IntegerSummarySetOperations(mode, mode);
final Union<IntegerSummary> union = new Union<>(K, setOps);
final int len = sketches.length;
for (final IntegerSketch isk : sketches) {
union.union(isk);
}
final CompactSketch<IntegerSummary> result = union.getResult();
final TupleSketchIterator<IntegerSummary> itr = result.iterator();
final int[] numDaysArr = new int[len + 1]; //zero index is ignored
while (itr.next()) {
//For each unique visitor from the result sketch, get the # days visited
final int numDaysVisited = itr.getSummary().getValue();
//increment the number of visitors that visited numDays
numDaysArr[numDaysVisited]++; //values range from 1 to 30
}
println("\nEngagement Histogram:");
println("Number of Unique Visitors by Number of Days Visited");
printf("%12s%12s%12s%12s\n","Days Visited", "Estimate", "LB", "UB");
int sumVisits = 0;
final double theta = result.getTheta();
for (int i = 0; i < numDaysArr.length; i++) {
final int visitorsAtDaysVisited = numDaysArr[i];
if (visitorsAtDaysVisited == 0) { continue; }
sumVisits += visitorsAtDaysVisited * i;
final double estVisitorsAtDaysVisited = visitorsAtDaysVisited / theta;
final double lbVisitorsAtDaysVisited = result.getLowerBound(numStdDev, visitorsAtDaysVisited);
final double ubVisitorsAtDaysVisited = result.getUpperBound(numStdDev, visitorsAtDaysVisited);
printf("%12d%12.0f%12.0f%12.0f\n",
i, estVisitorsAtDaysVisited, lbVisitorsAtDaysVisited, ubVisitorsAtDaysVisited);
}
//The estimate and bounds of the total number of visitors comes directly from the sketch.
final double visitors = result.getEstimate();
final double lbVisitors = result.getLowerBound(numStdDev);
final double ubVisitors = result.getUpperBound(numStdDev);
printf("\n%12s%12s%12s%12s\n","Totals", "Estimate", "LB", "UB");
printf("%12s%12.0f%12.0f%12.0f\n", "Visitors", visitors, lbVisitors, ubVisitors);
//The total number of visits, however, is a scaled metric and takes advantage of the fact that
//the retained entries in the sketch is a uniform random sample of all unique visitors, and
//the the rest of the unique users will likely behave in the same way.
final double estVisits = sumVisits / theta;
final double lbVisits = estVisits * lbVisitors / visitors;
final double ubVisits = estVisits * ubVisitors / visitors;
printf("%12s%12.0f%12.0f%12.0f\n\n", "Visits", estVisits, lbVisits, ubVisits);
}
/**
* @param o object to print
*/
private static void println(final Object o) {
printf("%s\n", o.toString());
}
/**
* @param fmt format
* @param args arguments
*/
private static void printf(final String fmt, final Object ... args) {
//System.out.printf(fmt, args); //Enable/Disable printing here
}
}
| 2,337 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/aninteger/ParameterLeakageTest.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.tuple.aninteger;
import static org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode.Min;
import static org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode.Sum;
import org.apache.datasketches.tuple.AnotB;
import org.apache.datasketches.tuple.CompactSketch;
import org.apache.datasketches.tuple.Intersection;
//import org.apache.datasketches.tuple.UpdatableSketch;
import org.apache.datasketches.tuple.Sketch;
import org.apache.datasketches.tuple.TupleSketchIterator;
import org.apache.datasketches.tuple.Union;
import org.testng.annotations.Test;
/**
* These tests check to make sure that no summary objects, which are mutable, and created
* as needed internally within a tuple sketch never leak into the result sketch.
*
* @author Lee Rhodes
*
*/
public class ParameterLeakageTest {
IntegerSummarySetOperations setOps = new IntegerSummarySetOperations(Sum, Min);
@Test
public void checkUnion() {
IntegerSketch sk1 = new IntegerSketch(4, Sum);
sk1.update(1, 1);
IntegerSummary sk1sum = captureSummaries(sk1)[0];
IntegerSketch sk2 = new IntegerSketch(4, Sum);
sk2.update(2, 1);
IntegerSummary sk2sum = captureSummaries(sk2)[0];
Union<IntegerSummary> union = new Union<>(setOps);
CompactSketch<IntegerSummary> csk = union.union(sk1, sk2);
IntegerSummary[] summaries = captureSummaries(csk);
println("Union Count: " + summaries.length);
for (IntegerSummary isum : summaries) {
if ((isum == sk1sum) || (isum == sk2sum)) {
throw new IllegalArgumentException("Parameter Leakage");
}
}
}
@Test
public void checkIntersectStateless() {
IntegerSketch sk1 = new IntegerSketch(4, Sum);
sk1.update(1, 1);
IntegerSummary sk1sum = captureSummaries(sk1)[0];
IntegerSketch sk2 = new IntegerSketch(4, Sum);
sk2.update(1, 1);
IntegerSummary sk2sum = captureSummaries(sk2)[0];
Intersection<IntegerSummary> intersect = new Intersection<>(setOps);
CompactSketch<IntegerSummary> csk = intersect.intersect(sk1, sk2);
IntegerSummary[] summaries = captureSummaries(csk);
println("Intersect Stateless Count: " + summaries.length);
for (IntegerSummary isum : summaries) {
if ((isum == sk1sum) || (isum == sk2sum)) {
throw new IllegalArgumentException("Parameter Leakage");
}
}
}
@Test
public void checkIntersectStateful() {
IntegerSketch sk1 = new IntegerSketch(4, Sum);
sk1.update(1, 1);
IntegerSummary sk1sum = captureSummaries(sk1)[0];
IntegerSketch sk2 = new IntegerSketch(4, Sum);
sk2.update(1, 1);
IntegerSummary sk2sum = captureSummaries(sk2)[0];
Intersection<IntegerSummary> intersect = new Intersection<>(setOps);
intersect.intersect(sk1);
intersect.intersect(sk2);
CompactSketch<IntegerSummary> csk = intersect.getResult();
IntegerSummary[] summaries = captureSummaries(csk);
println("Intersect Stateful Count: " + summaries.length);
for (IntegerSummary isum : summaries) {
if ((isum == sk1sum) || (isum == sk2sum)) {
throw new IllegalArgumentException("Parameter Leakage");
}
}
}
@Test
public void checkAnotbStateless() {
IntegerSketch sk1 = new IntegerSketch(4, Sum);
sk1.update(1, 1);
CompactSketch<IntegerSummary> csk1 = sk1.compact();
IntegerSummary sk1sum = captureSummaries(csk1)[0];
IntegerSketch sk2 = new IntegerSketch(4, Sum); //EMPTY
CompactSketch<IntegerSummary> csk = AnotB.aNotB(csk1, sk2);
IntegerSummary[] summaries = captureSummaries(csk);
println("AnotB Stateless Count: " + summaries.length);
for (IntegerSummary isum : summaries) {
if (isum == sk1sum) {
throw new IllegalArgumentException("Parameter Leakage");
}
}
}
@Test
public void checkAnotbStateful() {
IntegerSketch sk1 = new IntegerSketch(4, Sum);
sk1.update(1, 1);
CompactSketch<IntegerSummary> csk1 = sk1.compact();
IntegerSummary sk1sum = captureSummaries(csk1)[0];
IntegerSketch sk2 = new IntegerSketch(4, Sum); //EMPTY
AnotB<IntegerSummary> anotb = new AnotB<>();
anotb.setA(csk1);
anotb.notB(sk2);
CompactSketch<IntegerSummary> csk = anotb.getResult(true);
IntegerSummary[] summaries = captureSummaries(csk);
println("AnotB Stateful Count: " + summaries.length);
for (IntegerSummary isum : summaries) {
if (isum == sk1sum) {
throw new IllegalArgumentException("Parameter Leakage");
}
}
}
private static IntegerSummary[] captureSummaries(Sketch<IntegerSummary> sk) {
int entries = sk.getRetainedEntries();
IntegerSummary[] intSumArr = new IntegerSummary[entries];
int cnt = 0;
TupleSketchIterator<IntegerSummary> it = sk.iterator();
while (it.next()) {
intSumArr[cnt] = it.getSummary();
cnt++;
}
return intSumArr;
}
/**
* @param o Object to print
*/
static void println(Object o) {
//System.out.println(o.toString()); //disable
}
}
| 2,338 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/aninteger/CornerCaseTupleSetOperationsTest.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.tuple.aninteger;
import static org.apache.datasketches.hash.MurmurHash3.hash;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.theta.UpdateSketch;
import org.apache.datasketches.theta.UpdateSketchBuilder;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.apache.datasketches.tuple.AnotB;
import org.apache.datasketches.tuple.CompactSketch;
import org.apache.datasketches.tuple.Intersection;
import org.apache.datasketches.tuple.Union;
import org.testng.annotations.Test;
public class CornerCaseTupleSetOperationsTest {
/* Hash Values
* 9223372036854775807 Theta = 1.0
*
* 6730918654704304314 hash(3L)[0] >>> 1 GT_MIDP
* 4611686018427387904 Theta for p = 0.5f = MIDP
* 2206043092153046979 hash(2L)[0] >>> 1 LT_MIDP_V
* 1498732507761423037 hash(5L)[0] >>> 1 LTLT_MIDP_V
*
* 1206007004353599230 hash(6L)[0] >>> 1 GT_LOWP_V
* 922337217429372928 Theta for p = 0.1f = LOWP
* 593872385995628096 hash(4L)[0] >>> 1 LT_LOWP_V
* 405753591161026837 hash(1L)[0] >>> 1 LTLT_LOWP_V
*/
private static final long GT_MIDP_V = 3L;
private static final float MIDP_FLT = 0.5f;
private static final long GT_LOWP_V = 6L;
private static final float LOWP_FLT = 0.1f;
private static final long LT_LOWP_V = 4L;
private IntegerSummary.Mode mode = IntegerSummary.Mode.Min;
private IntegerSummary integerSummary = new IntegerSummary(mode);
private IntegerSummarySetOperations setOperations = new IntegerSummarySetOperations(mode, mode);
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() {
IntegerSketch tupleA = getTupleSketch(SkType.EMPTY, 0, 0);
IntegerSketch tupleB = getTupleSketch(SkType.EMPTY, 0, 0);
UpdateSketch thetaB = getThetaSketch(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(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void emptyExact() {
IntegerSketch tupleA = getTupleSketch(SkType.EMPTY, 0, 0);
IntegerSketch tupleB = getTupleSketch(SkType.EXACT, 0, GT_MIDP_V);
UpdateSketch thetaB = getThetaSketch(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(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void EmptyDegenerate() {
IntegerSketch tupleA = getTupleSketch(SkType.EMPTY, 0, 0);
IntegerSketch tupleB = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V);
UpdateSketch thetaB = getThetaSketch(SkType.DEGENERATE, LOWP_FLT, 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_FLT;
final int expectedUnionCount = 0;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void emptyEstimation() {
IntegerSketch tupleA = getTupleSketch(SkType.EMPTY, 0, 0);
IntegerSketch tupleB = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V);
UpdateSketch thetaB = getThetaSketch(SkType.ESTIMATION, LOWP_FLT, 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_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
@Test
public void exactEmpty() {
IntegerSketch tupleA = getTupleSketch(SkType.EXACT, 0, GT_MIDP_V);
IntegerSketch tupleB = getTupleSketch(SkType.EMPTY, 0, 0);
UpdateSketch thetaB = getThetaSketch(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(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void exactExact() {
IntegerSketch tupleA = getTupleSketch(SkType.EXACT, 0, GT_MIDP_V);
IntegerSketch tupleB = getTupleSketch(SkType.EXACT, 0, GT_MIDP_V);
UpdateSketch thetaB = getThetaSketch(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(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void exactDegenerate() {
IntegerSketch tupleA = getTupleSketch(SkType.EXACT, 0, LT_LOWP_V);
IntegerSketch tupleB = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); //entries = 0
UpdateSketch thetaB = getThetaSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 1;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void exactEstimation() {
IntegerSketch tupleA = getTupleSketch(SkType.EXACT, 0, LT_LOWP_V);
IntegerSketch tupleB = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V);
UpdateSketch thetaB = getThetaSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 1;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
@Test
public void estimationEmpty() {
IntegerSketch tupleA = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V);
IntegerSketch tupleB = getTupleSketch(SkType.EMPTY, 0, 0);
UpdateSketch thetaB = getThetaSketch(SkType.EMPTY, 0, 0);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = true;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 1;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void estimationExact() {
IntegerSketch tupleA = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V);
IntegerSketch tupleB = getTupleSketch(SkType.EXACT, 0, LT_LOWP_V);
UpdateSketch thetaB = getThetaSketch(SkType.EXACT, 0, LT_LOWP_V);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 1;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void estimationDegenerate() {
IntegerSketch tupleA = getTupleSketch(SkType.ESTIMATION, MIDP_FLT, LT_LOWP_V);
IntegerSketch tupleB = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V);
UpdateSketch thetaB = getThetaSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 1;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void estimationEstimation() {
IntegerSketch tupleA = getTupleSketch(SkType.ESTIMATION, MIDP_FLT, LT_LOWP_V);
IntegerSketch tupleB = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V);
UpdateSketch thetaB = getThetaSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 1;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
@Test
public void degenerateEmpty() {
IntegerSketch tupleA = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); //entries = 0
IntegerSketch tupleB = getTupleSketch(SkType.EMPTY, 0, 0);
UpdateSketch thetaB = getThetaSketch(SkType.EMPTY, 0, 0);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = true;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 0;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void degenerateExact() {
IntegerSketch tupleA = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); //entries = 0
IntegerSketch tupleB = getTupleSketch(SkType.EXACT, 0, LT_LOWP_V);
UpdateSketch thetaB = getThetaSketch(SkType.EXACT, 0, LT_LOWP_V);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void degenerateDegenerate() {
IntegerSketch tupleA = getTupleSketch(SkType.DEGENERATE, MIDP_FLT, GT_MIDP_V); //entries = 0
IntegerSketch tupleB = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V);
UpdateSketch thetaB = getThetaSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 0;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void degenerateEstimation() {
IntegerSketch tupleA = getTupleSketch(SkType.DEGENERATE, MIDP_FLT, GT_MIDP_V); //entries = 0
IntegerSketch tupleB = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V);
UpdateSketch thetaB = getThetaSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(tupleA, tupleB, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
//=================================
private void checks(
IntegerSketch tupleA,
IntegerSketch tupleB,
UpdateSketch thetaB,
double expectedIntersectTheta,
int expectedIntersectCount,
boolean expectedIntersectEmpty,
double expectedAnotbTheta,
int expectedAnotbCount,
boolean expectedAnotbEmpty,
double expectedUnionTheta,
int expectedUnionCount,
boolean expectedUnionEmpty) {
CompactSketch<IntegerSummary> csk;
Intersection<IntegerSummary> inter = new Intersection<>(setOperations);
AnotB<IntegerSummary> anotb = new AnotB<>();
Union<IntegerSummary> union = new Union<>(16, setOperations);
//Intersection Stateless Tuple, Tuple Updatable
csk = inter.intersect(tupleA, tupleB);
checkResult("Intersect Stateless Tuple, Tuple", csk, expectedIntersectTheta, expectedIntersectCount,
expectedIntersectEmpty);
//Intersection Stateless Tuple, Tuple Compact
csk = inter.intersect(tupleA.compact(), tupleB.compact());
checkResult("Intersect Stateless Tuple, Tuple", csk, expectedIntersectTheta, expectedIntersectCount,
expectedIntersectEmpty);
//Intersection Stateless Tuple, Theta Updatable
csk = inter.intersect(tupleA, thetaB, integerSummary); //Tuple, Theta
checkResult("Intersect Stateless Tuple, Theta", csk, expectedIntersectTheta, expectedIntersectCount,
expectedIntersectEmpty);
//Intersection Stateless Tuple, Theta Compact
csk = inter.intersect(tupleA.compact(), thetaB.compact(), integerSummary);
checkResult("Intersect Stateless Tuple, Theta", csk, expectedIntersectTheta, expectedIntersectCount,
expectedIntersectEmpty);
//AnotB Stateless Tuple, Tuple Updatable
csk = AnotB.aNotB(tupleA, tupleB);
checkResult("AnotB Stateless Tuple, Tuple", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//AnotB Stateless Tuple, Tuple Compact
csk = AnotB.aNotB(tupleA.compact(), tupleB.compact());
checkResult("AnotB Stateless Tuple, Tuple", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//AnotB Stateless Tuple, Theta Updatable
csk = AnotB.aNotB(tupleA, thetaB);
checkResult("AnotB Stateless Tuple, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//AnotB Stateless Tuple, Theta Compact
csk = AnotB.aNotB(tupleA.compact(), thetaB.compact());
checkResult("AnotB Stateless Tuple, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//AnotB Stateful Tuple, Tuple Updatable
anotb.setA(tupleA);
anotb.notB(tupleB);
csk = anotb.getResult(true);
checkResult("AnotB Stateful Tuple, Tuple", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//AnotB Stateful Tuple, Tuple Compact
anotb.setA(tupleA.compact());
anotb.notB(tupleB.compact());
csk = anotb.getResult(true);
checkResult("AnotB Stateful Tuple, Tuple", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//AnotB Stateful Tuple, Theta Updatable
anotb.setA(tupleA);
anotb.notB(thetaB);
csk = anotb.getResult(true);
checkResult("AnotB Stateful Tuple, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//AnotB Stateful Tuple, Theta Compact
anotb.setA(tupleA.compact());
anotb.notB(thetaB.compact());
csk = anotb.getResult(true);
checkResult("AnotB Stateful Tuple, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//Union Stateless Tuple, Tuple Updatable
csk = union.union(tupleA, tupleB);
checkResult("Union Stateless Tuple, Tuple", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
//Union Stateless Tuple, Tuple Compact
csk = union.union(tupleA.compact(), tupleB.compact());
checkResult("Union Stateless Tuple, Tuple", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
//Union Stateless Tuple, Theta Updatable
csk = union.union(tupleA, thetaB, integerSummary);
checkResult("Union Stateless Tuple, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
//Union Stateless Tuple, Theta Compact
csk = union.union(tupleA.compact(), thetaB.compact(), integerSummary);
checkResult("Union Stateless Tuple, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
//Union Stateful Tuple, Tuple Updatable
union.union(tupleA);
union.union(tupleB);
csk = union.getResult(true);
checkResult("Union Stateful Tuple, Tuple", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
//AnotB Stateful Tuple, Tuple Compact
union.union(tupleA.compact());
union.union(tupleB.compact());
csk = union.getResult(true);
checkResult("Union Stateful Tuple, Tuple", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
//AnotB Stateful Tuple, Theta Updatable
union.union(tupleA);
union.union(thetaB, integerSummary);
csk = union.getResult(true);
checkResult("Union Stateful Tuple, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
//AnotB Stateful Tuple, Theta Compact
union.union(tupleA.compact());
union.union(thetaB.compact(), integerSummary);
csk = union.getResult(true);
checkResult("Union Stateful Tuple, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
private static void checkResult(
String comment,
CompactSketch<IntegerSummary> 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 IntegerSketch getTupleSketch(
SkType skType,
float p,
long updateKey) {
IntegerSketch sk;
switch(skType) {
case EMPTY: { // { 1.0, 0, T} p and value are not used
sk = new IntegerSketch(4, 2, 1.0f, IntegerSummary.Mode.Min);
break;
}
case EXACT: { // { 1.0, >0, F} p is not used
sk = new IntegerSketch(4, 2, 1.0f, IntegerSummary.Mode.Min);
sk.update(updateKey, 1);
break;
}
case ESTIMATION: { // {<1.0, >0, F}
checkValidUpdate(p, updateKey);
sk = new IntegerSketch(4, 2, p, IntegerSummary.Mode.Min);
sk.update(updateKey, 1);
break;
}
case DEGENERATE: { // {<1.0, 0, F}
checkInvalidUpdate(p, updateKey);
sk = new IntegerSketch(4, 2, p, IntegerSummary.Mode.Min);
sk.update(updateKey, 1); // > theta
break;
}
default: { return null; } // should not happen
}
return sk;
}
//NOTE: p and value arguments are used for every case
private static UpdateSketch getThetaSketch(
SkType skType,
float p,
long updateKey) {
UpdateSketchBuilder bldr = new UpdateSketchBuilder();
bldr.setLogNominalEntries(4);
bldr.setResizeFactor(ResizeFactor.X4);
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(updateKey);
break;
}
case ESTIMATION: { // {<1.0, >0, F}
checkValidUpdate(p, updateKey);
bldr.setP(p);
sk = bldr.build();
sk.update(updateKey);
break;
}
case DEGENERATE: { // {<1.0, 0, F}
checkInvalidUpdate(p, updateKey);
bldr.setP(p);
sk = bldr.build();
sk.update(updateKey);
break;
}
default: { return null; } // should not happen
}
return sk;
}
private static void checkValidUpdate(float p, long updateKey) {
assertTrue( getLongHash(updateKey) < (long) (p * Long.MAX_VALUE));
}
private static void checkInvalidUpdate(float p, long updateKey) {
assertTrue( getLongHash(updateKey) > (long) (p * Long.MAX_VALUE));
}
static long getLongHash(long v) {
return (hash(v, ThetaUtil.DEFAULT_UPDATE_SEED)[0]) >>> 1;
}
}
| 2,339 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/aninteger/MikhailsBugTupleTest.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.tuple.aninteger;
import org.apache.datasketches.tuple.AnotB;
import org.apache.datasketches.tuple.CompactSketch;
import org.apache.datasketches.tuple.Intersection;
import org.testng.annotations.Test;
/**
* Issue #368, from Mikhail Lavrinovich 12 OCT 2021
* The failure was AnotB(estimating {<1.0,1,F}, Intersect(estimating{<1.0,1,F}, newDegenerative{<1.0,0,T},
* Which should be equal to AnotB(estimating{<1.0,1,F}, new{1.0,0,T} = estimating{<1.0, 1, F}. The AnotB
* threw a null pointer exception because it was not properly handling sketches with zero entries.
*/
public class MikhailsBugTupleTest {
@Test
public void mikhailsBug() {
IntegerSketch x = new IntegerSketch(12, 2, 0.1f, IntegerSummary.Mode.Min);
IntegerSketch y = new IntegerSketch(12, 2, 0.1f, IntegerSummary.Mode.Min);
x.update(1L, 1);
IntegerSummarySetOperations setOperations =
new IntegerSummarySetOperations(IntegerSummary.Mode.Min, IntegerSummary.Mode.Min);
Intersection<IntegerSummary> intersection = new Intersection<>(setOperations);
CompactSketch<IntegerSummary> intersect = intersection.intersect(x, y);
AnotB.aNotB(x, intersect); // NPE was here
}
//@Test
public void withTuple() {
IntegerSketch x = new IntegerSketch(12, 2, 0.1f, IntegerSummary.Mode.Min);
IntegerSketch y = new IntegerSketch(12, 2, 0.1f, IntegerSummary.Mode.Min);
x.update(1L, 1);
println("Tuple x: Estimating {<1.0,1,F}");
println(x.toString());
println("Tuple y: NewDegenerative {<1.0,0,T}");
println(y.toString());
IntegerSummarySetOperations setOperations =
new IntegerSummarySetOperations(IntegerSummary.Mode.Min, IntegerSummary.Mode.Min);
Intersection<IntegerSummary> intersection = new Intersection<>(setOperations);
CompactSketch<IntegerSummary> intersect = intersection.intersect(x, y);
println("Tuple Intersect(Estimating, NewDegen) = new {1.0, 0, T}");
println(intersect.toString());
CompactSketch<IntegerSummary> csk = AnotB.aNotB(x, intersect);
println("Tuple AnotB(Estimating, New) = estimating {<1.0, 1, F}");
println(csk.toString());
}
/**
* Println an object
* @param o object to print
*/
private static void println(Object o) {
//System.out.println(o.toString()); //disable here
}
} | 2,340 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesCompactSketchTest.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.tuple.arrayofdoubles;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.apache.datasketches.tuple.Util;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DirectArrayOfDoublesCompactSketchTest {
@Test
public void emptyFromQuickSelectSketch() {
ArrayOfDoublesUpdatableSketch us =
new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
ArrayOfDoublesCompactSketch sketch = us.compact(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getRetainedEntries(), 0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
Assert.assertNotNull(sketch.getValues());
Assert.assertEquals(sketch.getValues().length, 0);
ArrayOfDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
Assert.fail("empty sketch expected");
}
}
@Test
public void exactModeFromQuickSelectSketch() {
ArrayOfDoublesUpdatableSketch us =
new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
us.update(1, new double[] {1.0});
us.update(2, new double[] {1.0});
us.update(3, new double[] {1.0});
us.update(1, new double[] {1.0});
us.update(2, new double[] {1.0});
us.update(3, new double[] {1.0});
ArrayOfDoublesCompactSketch sketch = us.compact(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertFalse(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 3.0);
Assert.assertEquals(sketch.getLowerBound(1), 3.0);
Assert.assertEquals(sketch.getUpperBound(1), 3.0);
Assert.assertEquals(sketch.getRetainedEntries(), 3);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
Assert.assertEquals(sketch.getSeedHash(), Util.computeSeedHash(ThetaUtil.DEFAULT_UPDATE_SEED));
double[][] values = sketch.getValues();
Assert.assertEquals(values.length, 3);
for (double[] array: values) {
Assert.assertEquals(array[0], 2.0);
}
}
@Test
public void serializeDeserializeSmallExact() {
ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
us.update("a", new double[] {1.0});
us.update("b", new double[] {1.0});
us.update("c", new double[] {1.0});
ArrayOfDoublesCompactSketch sketch1 = us.compact(WritableMemory.writableWrap(new byte[1000000]));
ArrayOfDoublesSketch sketch2 = ArrayOfDoublesSketches.wrapSketch(WritableMemory.writableWrap(sketch1.toByteArray()));
Assert.assertFalse(sketch2.isEmpty());
Assert.assertFalse(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 3.0);
Assert.assertEquals(sketch2.getLowerBound(1), 3.0);
Assert.assertEquals(sketch2.getUpperBound(1), 3.0);
Assert.assertEquals(sketch2.getRetainedEntries(), 3);
Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch2.getTheta(), 1.0);
double[][] values = sketch2.getValues();
Assert.assertEquals(values.length, 3);
for (double[] array: values) {
Assert.assertEquals(array[0], 1.0);
}
}
@Test
public void serializeDeserializeEstimation() {
ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
us.update(i, new double[] {1.0});
}
ArrayOfDoublesCompactSketch sketch1 = us.compact(WritableMemory.writableWrap(new byte[1000000]));
ArrayOfDoublesSketch sketch2 = ArrayOfDoublesSketches.wrapSketch(WritableMemory.writableWrap(sketch1.toByteArray()));
Assert.assertFalse(sketch2.isEmpty());
Assert.assertTrue(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), sketch1.getEstimate());
Assert.assertEquals(sketch2.getThetaLong(), sketch1.getThetaLong());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void deserializeWithWrongSeed() {
ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
us.update(i, new double[] {1.0});
}
ArrayOfDoublesCompactSketch sketch1 = us.compact(WritableMemory.writableWrap(new byte[1000000]));
ArrayOfDoublesSketches.wrapSketch(WritableMemory.writableWrap(sketch1.toByteArray()), 123);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void fromQuickSelectSketchNotEnoughMemory() {
ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
us.update(1, new double[] {1.0});
us.compact(WritableMemory.writableWrap(new byte[39]));
}
}
| 2,341 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesQuickSelectSketchTest.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.tuple.arrayofdoubles;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ArrayOfDoublesQuickSelectSketchTest {
@Test(expectedExceptions = SketchesArgumentException.class)
public void invalidSamplingProbability() {
new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(2f);
}
@Test
public void heapToDirectExactTwoDoubles() {
double[] valuesArr = {1.0, 2.0};
ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build();
sketch1.update("a", valuesArr);
sketch1.update("b", valuesArr);
sketch1.update("c", valuesArr);
sketch1.update("d", valuesArr);
sketch1.update("a", valuesArr);
noopUpdates(sketch1, valuesArr);
ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.wrap(WritableMemory.writableWrap(sketch1.toByteArray()));
sketch2.update("b", valuesArr);
sketch2.update("c", valuesArr);
sketch2.update("d", valuesArr);
Assert.assertFalse(sketch2.isEmpty());
Assert.assertFalse(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 4.0);
Assert.assertEquals(sketch2.getUpperBound(1), 4.0);
Assert.assertEquals(sketch2.getLowerBound(1), 4.0);
Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch2.getTheta(), 1.0);
double[][] values = sketch2.getValues();
Assert.assertEquals(values.length, 4);
for (double[] array: values) {
Assert.assertEquals(array.length, 2);
Assert.assertEquals(array[0], 2.0);
Assert.assertEquals(array[1], 4.0);
}
}
@Test
public void heapToDirectWithSeed() {
long seed = 1;
double[] values = {1.0};
ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build();
sketch1.update("a", values);
sketch1.update("b", values);
sketch1.update("c", values);
ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.wrap(WritableMemory.writableWrap(sketch1.toByteArray()), seed);
sketch2.update("b", values);
sketch2.update("c", values);
sketch2.update("d", values);
Assert.assertEquals(sketch2.getEstimate(), 4.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInsertExceptions() {
ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build();
sketch1.update("a", new double[] {1.0});
}
@Test
public void directToHeapExactTwoDoubles() {
double[] valuesArr = {1.0, 2.0};
ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().
setNumberOfValues(2).build(WritableMemory.writableWrap(new byte[1000000]));
sketch1.update("a", valuesArr);
sketch1.update("b", valuesArr);
sketch1.update("c", valuesArr);
sketch1.update("d", valuesArr);
sketch1.update("a", valuesArr);
noopUpdates(sketch1, valuesArr);
ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.heapify(Memory.wrap(sketch1.toByteArray()));
sketch2.update("b", valuesArr);
sketch2.update("c", valuesArr);
sketch2.update("d", valuesArr);
Assert.assertFalse(sketch2.isEmpty());
Assert.assertFalse(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 4.0);
Assert.assertEquals(sketch2.getUpperBound(1), 4.0);
Assert.assertEquals(sketch2.getLowerBound(1), 4.0);
Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch2.getTheta(), 1.0);
double[][] values = sketch2.getValues();
Assert.assertEquals(values.length, 4);
for (double[] array: values) {
Assert.assertEquals(array.length, 2);
Assert.assertEquals(array[0], 2.0);
Assert.assertEquals(array[1], 4.0);
}
}
@Test
public void directToHeapWithSeed() {
long seed = 1;
double[] values = {1.0};
ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build(
WritableMemory.writableWrap(new byte[1000000]));
sketch1.update("a", values);
sketch1.update("b", values);
sketch1.update("c", values);
ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.heapify(Memory.wrap(sketch1.toByteArray()), seed);
sketch2.update("b", values);
sketch2.update("c", values);
sketch2.update("d", values);
Assert.assertEquals(sketch2.getEstimate(), 4.0);
}
@Test
public void maxBytes() {
Assert.assertEquals(ArrayOfDoublesQuickSelectSketch.getMaxBytes(1024, 2), 49184);
}
private static void noopUpdates(ArrayOfDoublesUpdatableSketch sketch, double[] valuesArr) {
byte[] byteArr = null;
sketch.update(byteArr, valuesArr);
byteArr = new byte[0];
sketch.update(byteArr, valuesArr);
int[] intArr = null;
sketch.update(intArr, valuesArr);
intArr = new int[0];
sketch.update(intArr, valuesArr);
long[] longArr = null;
sketch.update(longArr, valuesArr);
longArr = new long[0];
sketch.update(longArr, valuesArr);
}
}
| 2,342 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersectionTest.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.tuple.arrayofdoubles;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ArrayOfDoublesIntersectionTest {
private static ArrayOfDoublesCombiner combiner = new ArrayOfDoublesCombiner() {
@Override
public double[] combine(final double[] a, final double[] b) {
for (int i = 0; i < a.length; i++) {
a[i] += b[i];
}
return a;
}
};
@Test
public void nullInput() {
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection();
try {
intersection.intersect(null, null);
fail();
} catch (SketchesArgumentException e) {}
}
@Test
public void empty() {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection();
intersection.intersect(sketch1, null);
final ArrayOfDoublesCompactSketch result = intersection.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
Assert.assertEquals(result.getValues().length, 0);
}
@Test
public void degenerateWithExact() {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(0.01f).build();
sketch1.update("a", new double[] {1}); // this happens to get rejected because of sampling with low probability
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch2.update(1, new double[] {1});
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection();
intersection.intersect(sketch1, null);
intersection.intersect(sketch2, null);
final ArrayOfDoublesCompactSketch result = intersection.getResult();
Assert.assertFalse(result.isEmpty()); //Degenerate
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 184.0);
Assert.assertEquals(result.getValues().length, 0);
}
@Test
public void heapExactWithEmpty() {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch1.update(1, new double[] {1});
sketch1.update(2, new double[] {1});
sketch1.update(3, new double[] {1});
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection();
intersection.intersect(sketch1, null);
intersection.intersect(sketch2, null);
final ArrayOfDoublesCompactSketch result = intersection.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
}
@Test
public void directExactWithEmpty() {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder()
.build(WritableMemory.writableWrap(new byte[1000000]));
sketch1.update(1, new double[] {1});
sketch1.update(2, new double[] {1});
sketch1.update(3, new double[] {1});
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder()
.build(WritableMemory.writableWrap(new byte[1000000]));
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().
buildIntersection(WritableMemory.writableWrap(new byte[1000000]));
intersection.intersect(sketch1, null);
intersection.intersect(sketch2, null);
final ArrayOfDoublesCompactSketch result = intersection.getResult(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
}
@Test
public void heapExactMode() {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch1.update(1, new double[] {1});
sketch1.update(1, new double[] {1});
sketch1.update(2, new double[] {1});
sketch1.update(2, new double[] {1});
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch2.update(2, new double[] {1});
sketch2.update(2, new double[] {1});
sketch2.update(3, new double[] {1});
sketch2.update(3, new double[] {1});
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection();
intersection.intersect(sketch1, combiner);
intersection.intersect(sketch2, combiner);
ArrayOfDoublesCompactSketch result = intersection.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 1);
Assert.assertEquals(result.getEstimate(), 1.0);
Assert.assertEquals(result.getLowerBound(1), 1.0);
Assert.assertEquals(result.getUpperBound(1), 1.0);
final double[][] values = result.getValues();
for (int i = 0; i < values.length; i++) {
Assert.assertEquals(values[i][0], 4.0);
}
intersection.reset();
try {
intersection.intersect(null, null);
fail();
} catch (SketchesArgumentException e) { }
}
@Test
public void heapDisjointEstimationMode() {
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, new double[] {1.0});
}
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, new double[] {1.0});
}
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection();
intersection.intersect(sketch1, combiner);
intersection.intersect(sketch2, combiner);
final ArrayOfDoublesCompactSketch result = intersection.getResult();
Assert.assertFalse(result.isEmpty()); //Degenerate case
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 3.0);
Assert.assertEquals(result.getValues().length, 0);
Assert.assertTrue(result.thetaLong_ < Long.MAX_VALUE);
}
@Test
public void directDisjointEstimationMode() {
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().
build(WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, new double[] {1.0});
}
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().
build(WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, new double[] {1.0});
}
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().
buildIntersection(WritableMemory.writableWrap(new byte[1000000]));
intersection.intersect(sketch1, combiner);
intersection.intersect(sketch2, combiner);
final ArrayOfDoublesCompactSketch result = intersection.getResult(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 3.0);
Assert.assertEquals(result.getValues().length, 0);
}
@Test
public void heapEstimationMode() {
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, new double[] {1.0});
}
key -= 4096; // overlap half of the entries
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, new double[] {1.0});
}
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection();
intersection.intersect(sketch1, combiner);
intersection.intersect(sketch2, combiner);
final ArrayOfDoublesCompactSketch result = intersection.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 4096.0, 4096 * 0.03); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries())
Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate());
Assert.assertTrue(result.getUpperBound(1) > result.getEstimate());
final double[][] values = result.getValues();
for (int i = 0; i < values.length; i++) {
Assert.assertEquals(values[i][0], 2.0);
}
}
@Test
public void directEstimationMode() {
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, new double[] {1.0});
}
key -= 4096; // overlap half of the entries
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, new double[] {1.0});
}
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection(WritableMemory.writableWrap(new byte[1000000]));
intersection.intersect(sketch1, combiner);
intersection.intersect(sketch2, combiner);
final ArrayOfDoublesCompactSketch result = intersection.getResult(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 4096.0, 4096 * 0.03); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries())
Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate());
Assert.assertTrue(result.getUpperBound(1) > result.getEstimate());
final double[][] values = result.getValues();
for (int i = 0; i < values.length; i++) {
Assert.assertEquals(values[i][0], 2.0);
}
}
@Test
public void heapExactModeCustomSeed() {
final long seed = 1234567890;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build();
sketch1.update(1, new double[] {1});
sketch1.update(1, new double[] {1});
sketch1.update(2, new double[] {1});
sketch1.update(2, new double[] {1});
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build();
sketch2.update(2, new double[] {1});
sketch2.update(2, new double[] {1});
sketch2.update(3, new double[] {1});
sketch2.update(3, new double[] {1});
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().setSeed(seed).buildIntersection();
intersection.intersect(sketch1, combiner);
intersection.intersect(sketch2, combiner);
final ArrayOfDoublesCompactSketch result = intersection.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 1);
Assert.assertEquals(result.getEstimate(), 1.0);
Assert.assertEquals(result.getLowerBound(1), 1.0);
Assert.assertEquals(result.getUpperBound(1), 1.0);
final double[][] values = result.getValues();
for (int i = 0; i < values.length; i++) {
Assert.assertEquals(values[i][0], 4.0);
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void incompatibleSeeds() {
final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(1).build();
final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().setSeed(2).buildIntersection();
intersection.intersect(sketch, combiner);
}
}
| 2,343 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesQuickSelectSketchTest.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.tuple.arrayofdoubles;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class HeapArrayOfDoublesQuickSelectSketchTest {
@Test
public void isEmpty() {
final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build();
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
final ArrayOfDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
Assert.fail("empty sketch expected");
}
Assert.assertNotNull(sketch.toString());
}
@Test
public void isEmptyWithSampling() {
final float samplingProbability = 0.1f;
final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(samplingProbability).build();
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
}
@Test
public void sampling() {
final float samplingProbability = 0.001f;
final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(samplingProbability).build();
sketch.update("a", new double[] {1.0});
Assert.assertFalse(sketch.isEmpty());
Assert.assertTrue(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertTrue(sketch.getUpperBound(1) > 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0, 0.0000001);
Assert.assertEquals((float)(sketch.getThetaLong() / (double) Long.MAX_VALUE), samplingProbability);
Assert.assertEquals((float)sketch.getTheta(), samplingProbability);
}
@Test
public void exactMode() {
final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build();
Assert.assertTrue(sketch.isEmpty());
Assert.assertEquals(sketch.getEstimate(), 0.0);
for (int i = 1; i <= 4096; i++) {
sketch.update(i, new double[] {1.0});
}
Assert.assertFalse(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 4096.0);
Assert.assertEquals(sketch.getUpperBound(1), 4096.0);
Assert.assertEquals(sketch.getLowerBound(1), 4096.0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
final double[][] values = sketch.getValues();
Assert.assertEquals(values.length, 4096);
int count = 0;
for (int i = 0; i < values.length; i++) {
if (values[i] != null) {
count++;
}
}
Assert.assertEquals(count, 4096);
for (int i = 0; i < 4096; i++) {
Assert.assertEquals(values[i][0], 1.0);
}
sketch.reset();
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
final ArrayOfDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
Assert.fail("empty sketch expected");
}
}
@Test
// The moment of going into the estimation mode is, to some extent, an implementation detail
// Here we assume that presenting as many unique values as twice the nominal size of the sketch will result in estimation mode
public void estimationMode() {
final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build();
Assert.assertEquals(sketch.getEstimate(), 0.0);
for (int i = 1; i <= 8192; i++) {
sketch.update(i, new double[] {1.0});
}
Assert.assertTrue(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 8192, 8192 * 0.01);
Assert.assertTrue(sketch.getEstimate() >= sketch.getLowerBound(1));
Assert.assertTrue(sketch.getEstimate() < sketch.getUpperBound(1));
Assert.assertTrue(sketch.getRetainedEntries() > 4096);
sketch.trim();
Assert.assertEquals(sketch.getRetainedEntries(), 4096);
final double[][] values = sketch.getValues();
int count = 0;
for (final double[] array: values) {
if (array != null) {
count++;
Assert.assertEquals(array.length, 1);
Assert.assertEquals(array[0], 1.0);
}
}
Assert.assertEquals(count, values.length);
sketch.reset();
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
final ArrayOfDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
Assert.fail("empty sketch expected");
}
}
@Test
public void updatesOfAllKeyTypes() {
final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch.update(1L, new double[] {1.0});
sketch.update(2.0, new double[] {1.0});
sketch.update(new byte[] {3}, new double[] {1.0});
sketch.update(new int[] {4}, new double[] {1.0});
sketch.update(new long[] {5L}, new double[] {1.0});
sketch.update("a", new double[] {1.0});
Assert.assertEquals(sketch.getEstimate(), 6.0);
}
@Test
public void doubleSum() {
final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch.update(1, new double[] {1.0});
Assert.assertEquals(sketch.getRetainedEntries(), 1);
Assert.assertEquals(sketch.getValues()[0][0], 1.0);
sketch.update(1, new double[] {0.7});
Assert.assertEquals(sketch.getRetainedEntries(), 1);
Assert.assertEquals(sketch.getValues()[0][0], 1.7);
sketch.update(1, new double[] {0.8});
Assert.assertEquals(sketch.getRetainedEntries(), 1);
Assert.assertEquals(sketch.getValues()[0][0], 2.5);
}
@Test
public void serializeDeserializeExact() {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch1.update(1, new double[] {1.0});
final ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.heapify(WritableMemory.writableWrap(sketch1.toByteArray()));
Assert.assertEquals(sketch2.getEstimate(), 1.0);
final double[][] values = sketch2.getValues();
Assert.assertEquals(values.length, 1);
Assert.assertEquals(values[0][0], 1.0);
// the same key, so still one unique
sketch2.update(1, new double[] {1.0});
Assert.assertEquals(sketch2.getEstimate(), 1.0);
sketch2.update(2, new double[] {1.0});
Assert.assertEquals(sketch2.getEstimate(), 2.0);
}
@Test
public void serializeDeserializeEstimationNoResize() throws Exception {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().
setResizeFactor(ResizeFactor.X1).build();
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 8192; i++) {
sketch1.update(i, new double[] {1.0});
}
}
final byte[] byteArray = sketch1.toByteArray();
//for visual testing
//TestUtil.writeBytesToFile(byteArray, "ArrayOfDoublesQuickSelectSketch4K.data");
final ArrayOfDoublesSketch sketch2 = ArrayOfDoublesSketch.heapify(Memory.wrap(byteArray));
Assert.assertTrue(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 8192, 8192 * 0.99);
Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta());
final double[][] values = sketch2.getValues();
Assert.assertTrue(values.length >= 4096);
for (final double[] array: values) {
Assert.assertEquals(array[0], 10.0);
}
}
@Test
public void serializeDeserializeSampling() {
final int sketchSize = 16384;
final int numberOfUniques = sketchSize;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(sketchSize).setSamplingProbability(0.5f).build();
for (int i = 0; i < numberOfUniques; i++) {
sketch1.update(i, new double[] {1.0});
}
final ArrayOfDoublesSketch sketch2 = ArrayOfDoublesSketch.heapify(Memory.wrap(sketch1.toByteArray()));
Assert.assertTrue(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate() / numberOfUniques, 1.0, 0.01);
Assert.assertEquals(sketch2.getRetainedEntries() / (double) numberOfUniques, 0.5, 0.01);
Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta());
}
}
| 2,344 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketchTest.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.tuple.arrayofdoubles;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DirectArrayOfDoublesQuickSelectSketchTest {
@Test
public void isEmpty() {
final ArrayOfDoublesUpdatableSketch sketch =
new ArrayOfDoublesUpdatableSketchBuilder().
build(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
final ArrayOfDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
Assert.fail("empty sketch expected");
}
}
@Test
public void isEmptyWithSampling() {
final float samplingProbability = 0.1f;
final ArrayOfDoublesUpdatableSketch sketch =
new ArrayOfDoublesUpdatableSketchBuilder().
setSamplingProbability(samplingProbability).
build(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertTrue(sketch.isEmpty());
Assert.assertTrue(((DirectArrayOfDoublesQuickSelectSketch)sketch).isInSamplingMode());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
}
@Test
// very low probability of being sampled
// once the an input value is chosen so that it is rejected, the test will continue to work
// unless the hash function and the seed are the same
public void sampling() {
final float samplingProbability = 0.001f;
final ArrayOfDoublesUpdatableSketch sketch =
new ArrayOfDoublesUpdatableSketchBuilder().
setSamplingProbability(samplingProbability).
build(WritableMemory.writableWrap(new byte[1000000]));
sketch.update("a", new double[] {1.0});
Assert.assertFalse(sketch.isEmpty());
Assert.assertTrue(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertTrue(sketch.getUpperBound(1) > 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0, 0.0000001);
Assert.assertEquals(
(float)(sketch.getThetaLong() / (double) Long.MAX_VALUE), samplingProbability);
Assert.assertEquals((float)sketch.getTheta(), samplingProbability);
}
@Test
public void exactMode() {
final ArrayOfDoublesUpdatableSketch sketch =
new ArrayOfDoublesUpdatableSketchBuilder().
build(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertTrue(sketch.isEmpty());
Assert.assertEquals(sketch.getEstimate(), 0.0);
for (int i = 0; i < 4096; i++) {
sketch.update(i, new double[] {1.0});
}
Assert.assertFalse(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 4096.0);
Assert.assertEquals(sketch.getUpperBound(1), 4096.0);
Assert.assertEquals(sketch.getLowerBound(1), 4096.0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
final double[][] values = sketch.getValues();
Assert.assertEquals(values.length, 4096);
int count = 0;
for (int i = 0; i < values.length; i++) {
if (values[i] != null) {
count++;
}
}
Assert.assertEquals(count, 4096);
for (int i = 0; i < 4096; i++) {
Assert.assertEquals(values[i][0], 1.0);
}
sketch.reset();
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
final ArrayOfDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
Assert.fail("empty sketch expected");
}
}
@Test
// The moment of going into the estimation mode is, to some extent, an implementation detail
// Here we assume that presenting as many unique values as twice the nominal size of the sketch
// will result in estimation mode
public void estimationMode() {
final ArrayOfDoublesUpdatableSketch sketch =
new ArrayOfDoublesUpdatableSketchBuilder().
build(WritableMemory.writableWrap(new byte[4096 * 2 * 16 + 32]));
Assert.assertEquals(sketch.getEstimate(), 0.0);
for (int i = 1; i <= 8192; i++) {
sketch.update(i, new double[] {1.0});
}
Assert.assertTrue(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 8192, 8192 * 0.01);
Assert.assertTrue(sketch.getEstimate() >= sketch.getLowerBound(1));
Assert.assertTrue(sketch.getEstimate() < sketch.getUpperBound(1));
final double[][] values = sketch.getValues();
Assert.assertTrue(values.length >= 4096);
int count = 0;
for (final double[] array: values) {
if (array != null) {
count++;
Assert.assertEquals(array.length, 1);
Assert.assertEquals(array[0], 1.0);
}
}
Assert.assertEquals(count, values.length);
sketch.reset();
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
Assert.assertEquals(sketch.getSamplingProbability(), 1.0F);
final ArrayOfDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
Assert.fail("empty sketch expected");
}
}
@Test
public void updatesOfAllKeyTypes() {
final ArrayOfDoublesUpdatableSketch sketch =
new ArrayOfDoublesUpdatableSketchBuilder().
build(WritableMemory.writableWrap(new byte[1000000]));
sketch.update(1L, new double[] {1.0});
sketch.update(2.0, new double[] {1.0});
sketch.update(new byte[] {3}, new double[] {1.0});
sketch.update(new int[] {4}, new double[] {1.0});
sketch.update(new long[] {5L}, new double[] {1.0});
sketch.update("a", new double[] {1.0});
Assert.assertEquals(sketch.getEstimate(), 6.0);
}
@Test
public void doubleSum() {
final ArrayOfDoublesUpdatableSketch sketch =
new ArrayOfDoublesUpdatableSketchBuilder().
build(WritableMemory.writableWrap(new byte[1000000]));
sketch.update(1, new double[] {1.0});
Assert.assertEquals(sketch.getRetainedEntries(), 1);
Assert.assertEquals(sketch.getValues()[0][0], 1.0);
sketch.update(1, new double[] {0.7});
Assert.assertEquals(sketch.getRetainedEntries(), 1);
Assert.assertEquals(sketch.getValues()[0][0], 1.7);
sketch.update(1, new double[] {0.8});
Assert.assertEquals(sketch.getRetainedEntries(), 1);
Assert.assertEquals(sketch.getValues()[0][0], 2.5);
}
@Test
public void serializeDeserializeExact() throws Exception {
final ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().
build(WritableMemory.writableWrap(new byte[1000000]));
sketch1.update(1, new double[] {1.0});
final ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.wrap(WritableMemory.writableWrap(sketch1.toByteArray()));
Assert.assertEquals(sketch2.getEstimate(), 1.0);
final double[][] values = sketch2.getValues();
Assert.assertEquals(values.length, 1);
Assert.assertEquals(values[0][0], 1.0);
// the same key, so still one unique
sketch2.update(1, new double[] {1.0});
Assert.assertEquals(sketch2.getEstimate(), 1.0);
sketch2.update(2, new double[] {1.0});
Assert.assertEquals(sketch2.getEstimate(), 2.0);
}
@Test
public void serializeDeserializeEstimationNoResize() throws Exception {
final ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().setResizeFactor(ResizeFactor.X1).
build(WritableMemory.writableWrap(new byte[1000000]));
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 8192; i++) {
sketch1.update(i, new double[] {1.0});
}
}
final byte[] byteArray = sketch1.toByteArray();
//for visual testing
//TestUtil.writeBytesToFile(byteArray, "ArrayOfDoublesQuickSelectSketch4K.data");
final ArrayOfDoublesSketch sketch2 = ArrayOfDoublesSketch.wrap(WritableMemory.writableWrap(byteArray));
Assert.assertTrue(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 8192, 8192 * 0.99);
Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta());
final double[][] values = sketch2.getValues();
Assert.assertTrue(values.length >= 4096);
for (final double[] array: values) {
Assert.assertEquals(array[0], 10.0);
}
}
@Test
public void serializeDeserializeSampling() {
final int sketchSize = 16384;
final int numberOfUniques = sketchSize;
final ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().
setNominalEntries(sketchSize).setSamplingProbability(0.5f).
build(WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < numberOfUniques; i++) {
sketch1.update(i, new double[] {1.0});
}
final ArrayOfDoublesSketch sketch2 =
ArrayOfDoublesSketch.wrap(WritableMemory.writableWrap(sketch1.toByteArray()));
Assert.assertTrue(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate() / numberOfUniques, 1.0, 0.01);
Assert.assertEquals(sketch2.getRetainedEntries() / (double) numberOfUniques, 0.5, 0.01);
Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void notEnoughMemory() {
new ArrayOfDoublesUpdatableSketchBuilder().
setNominalEntries(32).build(WritableMemory.writableWrap(new byte[1055]));
}
}
| 2,345 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/AodSketchCrossLanguageTest.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.tuple.arrayofdoubles;
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 AodSketchCrossLanguageTest {
@Test(groups = {GENERATE_JAVA_FILES})
public void generateBinariesForCompatibilityTestingOneValue() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000};
for (int n: nArr) {
final ArrayOfDoublesUpdatableSketch sk = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < n; i++) sk.update(i, new double[] {i});
Files.newOutputStream(javaPath.resolve("aod_1_n" + n + "_java.sk")).write(sk.compact().toByteArray());
}
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateBinariesForCompatibilityTestingThreeValues() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000};
for (int n: nArr) {
final ArrayOfDoublesUpdatableSketch sk = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(3).build();
for (int i = 0; i < n; i++) sk.update(i, new double[] {i, i, i});
Files.newOutputStream(javaPath.resolve("aod_3_n" + n + "_java.sk")).write(sk.compact().toByteArray());
}
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateBinariesForCompatibilityTestingNonEmptyNoEntries() throws IOException {
final ArrayOfDoublesUpdatableSketch sk =
new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(0.01f).build();
sk.update(1, new double[] {1});
assertFalse(sk.isEmpty());
assertEquals(sk.getRetainedEntries(), 0);
Files.newOutputStream(javaPath.resolve("aod_1_non_empty_no_entries_java.sk")).write(sk.compact().toByteArray());
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCppOneValue() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("aod_1_n" + n + "_cpp.sk"));
final ArrayOfDoublesSketch sketch = ArrayOfDoublesSketch.wrap(Memory.wrap(bytes));
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
assertEquals(sketch.getEstimate(), n, n * 0.03);
assertEquals(sketch.getNumValues(), 1);
final ArrayOfDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
assertTrue(it.getKey() < sketch.getThetaLong());
}
}
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCppThreeValues() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("aod_3_n" + n + "_cpp.sk"));
final ArrayOfDoublesSketch sketch = ArrayOfDoublesSketch.wrap(Memory.wrap(bytes));
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
assertEquals(sketch.getEstimate(), n, n * 0.03);
assertEquals(sketch.getNumValues(), 3);
final ArrayOfDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
assertTrue(it.getKey() < sketch.getThetaLong());
assertEquals(it.getValues()[0], it.getValues()[1]);
assertEquals(it.getValues()[0], it.getValues()[2]);
}
}
}
@Test(groups = {CHECK_CPP_FILES})
public void deserializeFromCppOneValueNonEmptyNoEntries() throws IOException {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("aod_1_non_empty_no_entries_cpp.sk"));
final ArrayOfDoublesSketch sketch = ArrayOfDoublesSketch.wrap(Memory.wrap(bytes));
assertFalse(sketch.isEmpty());
assertEquals(sketch.getRetainedEntries(), 0);
}
}
| 2,346 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesCompactSketchTest.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.tuple.arrayofdoubles;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class HeapArrayOfDoublesCompactSketchTest {
@Test
public void emptyFromQuickSelectSketch() {
ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build();
ArrayOfDoublesCompactSketch sketch = us.compact();
Assert.assertTrue(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 0.0);
Assert.assertEquals(sketch.getLowerBound(1), 0.0);
Assert.assertEquals(sketch.getUpperBound(1), 0.0);
Assert.assertEquals(sketch.getRetainedEntries(), 0);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
Assert.assertNotNull(sketch.getValues());
Assert.assertEquals(sketch.getValues().length, 0);
ArrayOfDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
Assert.fail("empty sketch expected");
}
}
@Test
public void exactModeFromQuickSelectSketch() {
ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build();
us.update(1, new double[] {1.0});
us.update(2, new double[] {1.0});
us.update(3, new double[] {1.0});
us.update(1, new double[] {1.0});
us.update(2, new double[] {1.0});
us.update(3, new double[] {1.0});
ArrayOfDoublesCompactSketch sketch = us.compact();
Assert.assertFalse(sketch.isEmpty());
Assert.assertFalse(sketch.isEstimationMode());
Assert.assertEquals(sketch.getEstimate(), 3.0);
Assert.assertEquals(sketch.getLowerBound(1), 3.0);
Assert.assertEquals(sketch.getUpperBound(1), 3.0);
Assert.assertEquals(sketch.getRetainedEntries(), 3);
Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch.getTheta(), 1.0);
double[][] values = sketch.getValues();
Assert.assertEquals(values.length, 3);
for (double[] array: values) {
Assert.assertEquals(array[0], 2.0);
}
}
@Test
public void serializeDeserializeSmallExact() {
ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build();
us.update("a", new double[] {1.0});
us.update("b", new double[] {1.0});
us.update("c", new double[] {1.0});
ArrayOfDoublesCompactSketch sketch1 = us.compact();
ArrayOfDoublesSketch sketch2 =
ArrayOfDoublesSketches.heapifySketch(Memory.wrap(sketch1.toByteArray()));
Assert.assertFalse(sketch2.isEmpty());
Assert.assertFalse(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 3.0);
Assert.assertEquals(sketch2.getLowerBound(1), 3.0);
Assert.assertEquals(sketch2.getUpperBound(1), 3.0);
Assert.assertEquals(sketch2.getRetainedEntries(), 3);
Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch2.getTheta(), 1.0);
double[][] values = sketch2.getValues();
Assert.assertEquals(values.length, 3);
for (double[] array: values) {
Assert.assertEquals(array[0], 1.0);
}
}
@Test
public void serializeDeserializeEstimation() {
ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
us.update(i, new double[] {1.0});
}
WritableMemory wmem = WritableMemory.writableWrap(us.toByteArray());
ArrayOfDoublesUpdatableSketch wrappedUS = ArrayOfDoublesSketches.wrapUpdatableSketch(wmem);
Assert.assertFalse(wrappedUS.isEmpty());
Assert.assertTrue(wrappedUS.isEstimationMode());
Assert.assertEquals(wrappedUS.getEstimate(), us.getEstimate());
Assert.assertEquals(wrappedUS.getThetaLong(), us.getThetaLong());
ArrayOfDoublesUpdatableSketch heapUS = ArrayOfDoublesSketches.heapifyUpdatableSketch(wmem);
Assert.assertFalse(heapUS.isEmpty());
Assert.assertTrue(heapUS.isEstimationMode());
Assert.assertEquals(heapUS.getEstimate(), us.getEstimate());
Assert.assertEquals(heapUS.getThetaLong(), us.getThetaLong());
ArrayOfDoublesCompactSketch sketch1 = us.compact();
ArrayOfDoublesSketch sketch2 =
ArrayOfDoublesSketches.heapifySketch(Memory.wrap(sketch1.toByteArray()));
Assert.assertFalse(sketch2.isEmpty());
Assert.assertTrue(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), sketch1.getEstimate());
Assert.assertEquals(sketch2.getThetaLong(), sketch1.getThetaLong());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void deserializeWithWrongSeed() {
ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
us.update(i, new double[] {1.0});
}
ArrayOfDoublesCompactSketch sketch1 = us.compact();
Memory mem = Memory.wrap(sketch1.toByteArray());
ArrayOfDoublesSketches.heapifySketch(mem, 123);
}
}
| 2,347 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBTest.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.tuple.arrayofdoubles;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.ResizeFactor;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ArrayOfDoublesAnotBTest {
@Test
public void nullOrEmptyInput() {
// calling getResult() before calling update() should yield an empty set
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB();
ArrayOfDoublesCompactSketch result = aNotB.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
ArrayOfDoublesSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build();
try {
aNotB.update(sketch, null);
fail();
} catch (SketchesArgumentException e) {}
try {
aNotB.update(null, sketch);
fail();
} catch (SketchesArgumentException e) {}
aNotB.update(sketch, sketch);
result = aNotB.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
}
@Test
public void emptyA() {
ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketchB.update(1, new double[] {1.0});
sketchB.update(2, new double[] {1.0});
sketchB.update(3, new double[] {1.0});
sketchB.update(4, new double[] {1.0});
sketchB.update(5, new double[] {1.0});
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB();
ArrayOfDoublesSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().build();
aNotB.update(sketchA, sketchB);
ArrayOfDoublesCompactSketch result = aNotB.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
}
@Test
public void emptyB() {
ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketchA.update(1, new double[] {1.0});
sketchA.update(2, new double[] {1.0});
sketchA.update(3, new double[] {1.0});
sketchA.update(4, new double[] {1.0});
sketchA.update(5, new double[] {1.0});
ArrayOfDoublesSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().build();
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB();
aNotB.update(sketchA, sketchB);
ArrayOfDoublesCompactSketch result = aNotB.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 5);
Assert.assertEquals(result.getEstimate(), 5.0);
Assert.assertEquals(result.getLowerBound(1), 5.0);
Assert.assertEquals(result.getUpperBound(1), 5.0);
ArrayOfDoublesSketchIterator it = result.iterator();
while (it.next()) {
Assert.assertEquals(it.getValues(), new double[] {1});
}
}
@Test
public void aSameAsB() {
ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch.update(1, new double[] {1.0});
sketch.update(2, new double[] {1.0});
sketch.update(3, new double[] {1.0});
sketch.update(4, new double[] {1.0});
sketch.update(5, new double[] {1.0});
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB();
aNotB.update(sketch, sketch);
ArrayOfDoublesCompactSketch result = aNotB.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 0);
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
}
@Test
public void exactMode() {
ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketchA.update(1, new double[] {1});
sketchA.update(2, new double[] {1});
sketchA.update(3, new double[] {1});
sketchA.update(4, new double[] {1});
sketchA.update(5, new double[] {1});
ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketchB.update(3, new double[] {1});
sketchB.update(4, new double[] {1});
sketchB.update(5, new double[] {1});
sketchB.update(6, new double[] {1});
sketchB.update(7, new double[] {1});
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB();
aNotB.update(sketchA, sketchB);
ArrayOfDoublesCompactSketch result = aNotB.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 2);
Assert.assertEquals(result.getEstimate(), 2.0);
Assert.assertEquals(result.getLowerBound(1), 2.0);
Assert.assertEquals(result.getUpperBound(1), 2.0);
ArrayOfDoublesSketchIterator it = result.iterator();
while (it.next()) {
Assert.assertEquals(it.getValues(), new double[] {1});
}
}
@Test
public void exactModeTwoDoubles() {
ArrayOfDoublesUpdatableSketchBuilder bldr = new ArrayOfDoublesUpdatableSketchBuilder();
bldr.setNominalEntries(16);
bldr.setNumberOfValues(2);
bldr.setResizeFactor(ResizeFactor.X1);
double[] valuesArr1 = {1.0, 2.0};
double[] valuesArr2 = {2.0, 4.0};
ArrayOfDoublesUpdatableSketch sketch1 = bldr.build();
sketch1.update("a", valuesArr1);
sketch1.update("b", valuesArr2);
sketch1.update("c", valuesArr1);
sketch1.update("d", valuesArr1);
ArrayOfDoublesUpdatableSketch sketch2 = bldr.build();
sketch2.update("c", valuesArr2);
sketch2.update("d", valuesArr2);
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB();
aNotB.update(sketch1, sketch2);
ArrayOfDoublesCompactSketch result = aNotB.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 2);
double[] resultArr = new double[] {2.0,4.0,1.0,2.0}; //order specific to this test
Assert.assertEquals(result.getValuesAsOneDimension(), resultArr);
}
@Test
public void exactModeCustomSeed() {
long seed = 1234567890;
ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build();
sketchA.update(1, new double[] {1});
sketchA.update(2, new double[] {1});
sketchA.update(3, new double[] {1});
sketchA.update(4, new double[] {1});
sketchA.update(5, new double[] {1});
ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build();
sketchB.update(3, new double[] {1});
sketchB.update(4, new double[] {1});
sketchB.update(5, new double[] {1});
sketchB.update(6, new double[] {1});
sketchB.update(7, new double[] {1});
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().setSeed(seed).buildAnotB();
aNotB.update(sketchA, sketchB);
ArrayOfDoublesCompactSketch result = aNotB.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getRetainedEntries(), 2);
Assert.assertEquals(result.getEstimate(), 2.0);
Assert.assertEquals(result.getLowerBound(1), 2.0);
Assert.assertEquals(result.getUpperBound(1), 2.0);
ArrayOfDoublesSketchIterator it = result.iterator();
while (it.next()) {
Assert.assertEquals(it.getValues(), new double[] {1});
}
}
@Test
public void estimationMode() {
int key = 0;
ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
sketchA.update(key++, new double[] {1});
}
key -= 4096; // overlap half of the entries
ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
sketchB.update(key++, new double[] {1});
}
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB();
aNotB.update(sketchA, sketchB);
ArrayOfDoublesCompactSketch result = aNotB.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 4096.0, 4096 * 0.03); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries())
Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate());
Assert.assertTrue(result.getUpperBound(1) > result.getEstimate());
ArrayOfDoublesSketchIterator it = result.iterator();
while (it.next()) {
Assert.assertEquals(it.getValues(), new double[] {1});
}
// same operation, but compact sketches and off-heap result
aNotB.update(sketchA.compact(), sketchB.compact());
result = aNotB.getResult(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 4096.0, 4096 * 0.03); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries())
Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate());
Assert.assertTrue(result.getUpperBound(1) > result.getEstimate());
it = result.iterator();
while (it.next()) {
Assert.assertEquals(it.getValues(), new double[] {1});
}
}
@Test
public void estimationModeLargeB() {
int key = 0;
ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 10000; i++) {
sketchA.update(key++, new double[] {1});
}
key -= 2000; // overlap
ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 100000; i++) {
sketchB.update(key++, new double[] {1});
}
final int expected = 10000 - 2000;
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB();
aNotB.update(sketchA, sketchB);
ArrayOfDoublesCompactSketch result = aNotB.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), expected, expected * 0.1); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries())
Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate());
Assert.assertTrue(result.getUpperBound(1) > result.getEstimate());
ArrayOfDoublesSketchIterator it = result.iterator();
while (it.next()) {
Assert.assertEquals(it.getValues(), new double[] {1});
}
// same operation, but compact sketches and off-heap result
aNotB.update(sketchA.compact(), sketchB.compact());
result = aNotB.getResult(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), expected, expected * 0.1); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries())
Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate());
Assert.assertTrue(result.getUpperBound(1) > result.getEstimate());
it = result.iterator();
while (it.next()) {
Assert.assertEquals(it.getValues(), new double[] {1});
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void incompatibleSeedA() {
ArrayOfDoublesSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(1).build();
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB();
aNotB.update(sketch, null);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void incompatibleSeedB() {
ArrayOfDoublesSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(1).build();
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB();
aNotB.update(null, sketch);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void incompatibleSeeds() {
ArrayOfDoublesSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(1).build();
ArrayOfDoublesSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(2).build();
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().setSeed(3).buildAnotB();
aNotB.update(sketchA, sketchB);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void incompatibleNumValues() {
ArrayOfDoublesSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(1).build();
ArrayOfDoublesSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build();
ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().setSeed(3).buildAnotB();
aNotB.update(sketchA, sketchB);
}
}
| 2,348 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketchTest.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.tuple.arrayofdoubles;
import static org.testng.Assert.assertEquals;
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;
public class ArrayOfDoublesCompactSketchTest {
@Test
public void heapToDirectExactTwoDoubles() {
ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build();
sketch1.update("a", new double[] {1, 2});
sketch1.update("b", new double[] {1, 2});
sketch1.update("c", new double[] {1, 2});
sketch1.update("d", new double[] {1, 2});
sketch1.update("a", new double[] {1, 2});
sketch1.update("b", new double[] {1, 2});
sketch1.update("c", new double[] {1, 2});
sketch1.update("d", new double[] {1, 2});
ArrayOfDoublesCompactSketch csk = sketch1.compact();
Memory mem = Memory.wrap(csk.toByteArray());
ArrayOfDoublesSketch sketch2 = new DirectArrayOfDoublesCompactSketch(mem);
Assert.assertFalse(sketch2.isEmpty());
Assert.assertFalse(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 4.0);
Assert.assertEquals(sketch2.getUpperBound(1), 4.0);
Assert.assertEquals(sketch2.getLowerBound(1), 4.0);
Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch2.getTheta(), 1.0);
double[][] values = sketch2.getValues();
Assert.assertEquals(values.length, 4);
for (double[] array: values) {
Assert.assertEquals(array.length, 2);
Assert.assertEquals(array[0], 2.0);
Assert.assertEquals(array[1], 4.0);
}
}
@Test
public void directToHeapExactTwoDoubles() {
ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(WritableMemory.writableWrap(new byte[1000000]));
sketch1.update("a", new double[] {1, 2});
sketch1.update("b", new double[] {1, 2});
sketch1.update("c", new double[] {1, 2});
sketch1.update("d", new double[] {1, 2});
sketch1.update("a", new double[] {1, 2});
sketch1.update("b", new double[] {1, 2});
sketch1.update("c", new double[] {1, 2});
sketch1.update("d", new double[] {1, 2});
ArrayOfDoublesSketch sketch2 =
new HeapArrayOfDoublesCompactSketch(
Memory.wrap(sketch1.compact(WritableMemory.writableWrap(new byte[1000000])).toByteArray()));
Assert.assertFalse(sketch2.isEmpty());
Assert.assertFalse(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 4.0);
Assert.assertEquals(sketch2.getUpperBound(1), 4.0);
Assert.assertEquals(sketch2.getLowerBound(1), 4.0);
Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch2.getTheta(), 1.0);
double[][] values = sketch2.getValues();
Assert.assertEquals(values.length, 4);
for (double[] array: values) {
Assert.assertEquals(array.length, 2);
Assert.assertEquals(array[0], 2.0);
Assert.assertEquals(array[1], 4.0);
}
}
@SuppressWarnings("unused")
@Test
public void checkGetValuesAndKeysMethods() {
ArrayOfDoublesUpdatableSketchBuilder bldr = new ArrayOfDoublesUpdatableSketchBuilder();
bldr.setNominalEntries(16).setNumberOfValues(2);
HeapArrayOfDoublesQuickSelectSketch hqssk = (HeapArrayOfDoublesQuickSelectSketch) bldr.build();
hqssk.update("a", new double[] {1, 2});
hqssk.update("b", new double[] {3, 4});
hqssk.update("c", new double[] {5, 6});
hqssk.update("d", new double[] {7, 8});
final double[][] values = hqssk.getValues();
final double[] values1d = hqssk.getValuesAsOneDimension();
final long[] keys = hqssk.getKeys();
HeapArrayOfDoublesCompactSketch hcsk = (HeapArrayOfDoublesCompactSketch)hqssk.compact();
final double[][] values2 = hcsk.getValues();
final double[] values1d2 = hcsk.getValuesAsOneDimension();
final long[] keys2 = hcsk.getKeys();
assertEquals(values2, values);
assertEquals(values1d2, values1d);
assertEquals(keys2, keys);
Memory hqsskMem = Memory.wrap(hqssk.toByteArray());
DirectArrayOfDoublesQuickSelectSketchR dqssk =
(DirectArrayOfDoublesQuickSelectSketchR)ArrayOfDoublesSketch.wrap(hqsskMem, ThetaUtil.DEFAULT_UPDATE_SEED);
final double[][] values3 = dqssk.getValues();
final double[] values1d3 = dqssk.getValuesAsOneDimension();
final long[] keys3 = dqssk.getKeys();
assertEquals(values3, values);
assertEquals(values1d3, values1d);
assertEquals(keys3, keys);
Memory hcskMem = Memory.wrap(hcsk.toByteArray());
DirectArrayOfDoublesCompactSketch dcsk2 =
(DirectArrayOfDoublesCompactSketch)ArrayOfDoublesSketch.wrap(hcskMem, ThetaUtil.DEFAULT_UPDATE_SEED);
final double[][] values4 = dqssk.getValues();
final double[] values1d4 = dqssk.getValuesAsOneDimension();
final long[] keys4 = dqssk.getKeys();
assertEquals(values4, values);
assertEquals(values1d4, values1d);
assertEquals(keys4, keys);
}
}
| 2,349 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnionTest.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.tuple.arrayofdoubles;
import java.util.Arrays;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ArrayOfDoublesUnionTest {
@Test
public void heapExactMode() {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch1.update(1, new double[] {1.0});
sketch1.update(1, new double[] {1.0});
sketch1.update(1, new double[] {1.0});
sketch1.update(2, new double[] {1.0});
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch2.update(2, new double[] {1.0});
sketch2.update(2, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().buildUnion();
union.union(sketch1);
union.union(sketch2);
final int maxBytes = ArrayOfDoublesUnion.getMaxBytes(
ArrayOfDoublesSetOperationBuilder.DEFAULT_NOMINAL_ENTRIES,
ArrayOfDoublesSetOperationBuilder.DEFAULT_NUMBER_OF_VALUES);
Assert.assertEquals(maxBytes, 131120); // 48 bytes preamble + 2 * nominal entries * (key size + value size)
ArrayOfDoublesCompactSketch result = union.getResult();
Assert.assertEquals(result.getEstimate(), 3.0);
double[][] values = result.getValues();
Assert.assertEquals(values[0][0], 3.0);
Assert.assertEquals(values[1][0], 3.0);
Assert.assertEquals(values[2][0], 3.0);
final WritableMemory wmem = WritableMemory.writableWrap(union.toByteArray());
final ArrayOfDoublesUnion wrappedUnion = ArrayOfDoublesSketches.wrapUnion(wmem);
result = wrappedUnion.getResult();
Assert.assertEquals(result.getEstimate(), 3.0);
values = result.getValues();
Assert.assertEquals(values[0][0], 3.0);
Assert.assertEquals(values[1][0], 3.0);
Assert.assertEquals(values[2][0], 3.0);
union.reset();
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertFalse(result.isEstimationMode());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getTheta(), 1.0);
}
@Test
public void heapEstimationMode() {
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, new double[] {1.0});
}
key -= 4096; // overlap half of the entries
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, new double[] {1.0});
}
final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().buildUnion();
union.union(sketch1);
union.union(sketch2);
ArrayOfDoublesCompactSketch result = union.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertTrue(result.isEstimationMode());
Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01);
union.reset();
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertFalse(result.isEstimationMode());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getTheta(), 1.0);
}
@Test
public void heapEstimationModeFullOverlapTwoValuesAndDownsizing() {
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build();
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, new double[] {1.0, 2.0});
}
key = 0; // full overlap
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build();
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, new double[] {1.0, 2.0});
}
final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().setNumberOfValues(2).setNominalEntries(1024).buildUnion();
union.union(sketch1);
union.union(sketch2);
final ArrayOfDoublesCompactSketch result = union.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertTrue(result.isEstimationMode());
Assert.assertEquals(result.getEstimate(), 8192.0, 8192 * 0.01);
Assert.assertEquals(result.getRetainedEntries(), 1024); // union was downsampled
final ArrayOfDoublesSketchIterator it = result.iterator();
final double[] expected = {2, 4};
while (it.next()) {
Assert.assertEquals(it.getValues(), expected, Arrays.toString(it.getValues()) + " != " + Arrays.toString(expected));
}
}
@Test
public void heapMixedMode() {
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 1000; i++) {
sketch1.update(key++, new double[] {1.0});
}
key -= 500; // overlap half of the entries
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(0.2f).build();
for (int i = 0; i < 20000; i++) {
sketch2.update(key++, new double[] {1.0});
}
final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().buildUnion();
union.union(sketch1);
union.union(sketch2);
final ArrayOfDoublesCompactSketch result = union.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertTrue(result.isEstimationMode());
Assert.assertEquals(result.getEstimate(), 20500.0, 20500 * 0.01);
}
@Test
public void heapSerializeDeserialize() {
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, new double[] {1.0});
}
key -= 4096; // overlap half of the entries
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, new double[] {1.0});
}
final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().buildUnion();
union1.union(sketch1);
union1.union(sketch2);
final ArrayOfDoublesUnion union2 = ArrayOfDoublesUnion.heapify(Memory.wrap(union1.toByteArray()));
ArrayOfDoublesCompactSketch result = union2.getResult();
Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01);
union2.reset();
result = union2.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertFalse(result.isEstimationMode());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getTheta(), 1.0);
final double[][] values = result.getValues();
for (int i = 0; i < values.length; i++) {
Assert.assertEquals(values[i][0], 2.0);
}
}
@Test
public void heapSerializeDeserializeWithSeed() {
final long seed = 1;
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build();
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, new double[] {1.0});
}
key -= 4096; // overlap half of the entries
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build();
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, new double[] {1.0});
}
final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().setSeed(seed).buildUnion();
union1.union(sketch1);
union1.union(sketch2);
final ArrayOfDoublesUnion union2 = ArrayOfDoublesUnion.heapify(Memory.wrap(union1.toByteArray()), seed);
final ArrayOfDoublesCompactSketch result = union2.getResult();
Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01);
}
@Test
public void directSerializeDeserialize() {
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(
WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, new double[] {1.0});
}
key -= 4096; // overlap half of the entries
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(
WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, new double[] {1.0});
}
final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().buildUnion(
WritableMemory.writableWrap(new byte[1000000]));
union1.union(sketch1);
union1.union(sketch2);
final ArrayOfDoublesUnion union2 = ArrayOfDoublesUnion.wrap(WritableMemory.writableWrap(union1.toByteArray()));
ArrayOfDoublesCompactSketch result = union2.getResult(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01);
union2.reset();
result = union2.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertFalse(result.isEstimationMode());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getTheta(), 1.0);
final double[][] values = result.getValues();
for (int i = 0; i < values.length; i++) {
Assert.assertEquals(values[i][0], 2.0);
}
}
@Test
public void directSerializeDeserializeWithSeed() {
final long seed = 1;
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed)
.build(WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, new double[] {1.0});
}
key -= 4096; // overlap half of the entries
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed)
.build(WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, new double[] {1.0});
}
final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().setSeed(seed)
.buildUnion(WritableMemory.writableWrap(new byte[1000000]));
union1.union(sketch1);
union1.union(sketch2);
final ArrayOfDoublesUnion union2 = ArrayOfDoublesUnion.wrap(WritableMemory.writableWrap(union1.toByteArray()), seed);
final ArrayOfDoublesCompactSketch result = union2.getResult(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01);
}
@Test
public void directExactMode() {
final ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
sketch1.update(1, new double[] {1.0});
sketch1.update(1, new double[] {1.0});
sketch1.update(1, new double[] {1.0});
sketch1.update(2, new double[] {1.0});
final ArrayOfDoublesUpdatableSketch sketch2 =
new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
sketch2.update(2, new double[] {1.0});
sketch2.update(2, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
final ArrayOfDoublesUnion union =
new ArrayOfDoublesSetOperationBuilder().buildUnion(WritableMemory.writableWrap(new byte[1000000]));
union.union(sketch1);
union.union(sketch2);
ArrayOfDoublesCompactSketch result = union.getResult(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertEquals(result.getEstimate(), 3.0);
final double[][] values = result.getValues();
Assert.assertEquals(values[0][0], 3.0);
Assert.assertEquals(values[1][0], 3.0);
Assert.assertEquals(values[2][0], 3.0);
union.reset();
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertFalse(result.isEstimationMode());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getTheta(), 1.0);
}
@Test
public void directEstimationMode() {
int key = 0;
final ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
sketch1.update(key++, new double[] {1.0});
}
key -= 4096; // overlap half of the entries
final ArrayOfDoublesUpdatableSketch sketch2 =
new ArrayOfDoublesUpdatableSketchBuilder().build(WritableMemory.writableWrap(new byte[1000000]));
for (int i = 0; i < 8192; i++) {
sketch2.update(key++, new double[] {1.0});
}
final ArrayOfDoublesUnion union =
new ArrayOfDoublesSetOperationBuilder().buildUnion(WritableMemory.writableWrap(new byte[1000000]));
union.union(sketch1);
union.union(sketch2);
ArrayOfDoublesCompactSketch result = union.getResult(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01);
union.reset();
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertFalse(result.isEstimationMode());
Assert.assertEquals(result.getEstimate(), 0.0);
Assert.assertEquals(result.getUpperBound(1), 0.0);
Assert.assertEquals(result.getLowerBound(1), 0.0);
Assert.assertEquals(result.getTheta(), 1.0);
}
@Test
public void heapToDirect() {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch1.update(1, new double[] {1.0});
sketch1.update(1, new double[] {1.0});
sketch1.update(1, new double[] {1.0});
sketch1.update(2, new double[] {1.0});
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch2.update(2, new double[] {1.0});
sketch2.update(2, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
final ArrayOfDoublesUnion heapUnion = new ArrayOfDoublesSetOperationBuilder().buildUnion();
heapUnion.union(sketch1);
final ArrayOfDoublesUnion directUnion =
ArrayOfDoublesUnion.wrap(WritableMemory.writableWrap(heapUnion.toByteArray()));
directUnion.union(sketch2);
final ArrayOfDoublesCompactSketch result = directUnion.getResult(WritableMemory.writableWrap(new byte[1000000]));
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 3.0);
final double[][] values = result.getValues();
Assert.assertEquals(values.length, 3);
Assert.assertEquals(values[0][0], 3.0);
Assert.assertEquals(values[1][0], 3.0);
Assert.assertEquals(values[2][0], 3.0);
}
@Test
public void directToHeap() {
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch1.update(1, new double[] {1.0});
sketch1.update(1, new double[] {1.0});
sketch1.update(1, new double[] {1.0});
sketch1.update(2, new double[] {1.0});
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
sketch2.update(2, new double[] {1.0});
sketch2.update(2, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
sketch2.update(3, new double[] {1.0});
final ArrayOfDoublesUnion directUnion =
new ArrayOfDoublesSetOperationBuilder().buildUnion(WritableMemory.writableWrap(new byte[1000000]));
directUnion.union(sketch1);
final ArrayOfDoublesUnion heapUnion = ArrayOfDoublesUnion.heapify(Memory.wrap(directUnion.toByteArray()));
heapUnion.union(sketch2);
final ArrayOfDoublesCompactSketch result = heapUnion.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getEstimate(), 3.0);
final double[][] values = result.getValues();
Assert.assertEquals(values.length, 3);
Assert.assertEquals(values[0][0], 3.0);
Assert.assertEquals(values[1][0], 3.0);
Assert.assertEquals(values[2][0], 3.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void incompatibleSeeds() {
final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(1).build();
final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().setSeed(2).buildUnion();
union.union(sketch);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void incompatibleInputSketchFewerValues() {
final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build();
final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().setNumberOfValues(2).buildUnion();
union.union(sketch);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void incompatibleInputSketchMoreValues() {
final ArrayOfDoublesUpdatableSketch sketch =
new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build();
final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().buildUnion();
union.union(sketch);
}
@Test
public void directDruidUsageOneSketch() {
final WritableMemory mem = WritableMemory.writableWrap(new byte[1_000_000]);
new ArrayOfDoublesSetOperationBuilder().buildUnion(mem); // just set up memory to wrap later
final int n = 100_000; // estimation mode
final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < n; i++) {
sketch.update(i, new double[] {1.0});
}
sketch.trim(); // pretend this is a result from a union
// as Druid wraps memory
WritableMemory mem2 = WritableMemory.writableWrap(new byte[1_000_000]);
ArrayOfDoublesCompactSketch dcsk = sketch.compact(mem2);
ArrayOfDoublesUnion union = ArrayOfDoublesSketches.wrapUnion(mem); //empty union
union.union(dcsk);
//ArrayOfDoublesSketches.wrapUnion(mem).union(sketch.compact(WritableMemory.writableWrap(new byte[1_000_000])));
final ArrayOfDoublesSketch result = ArrayOfDoublesUnion.wrap(mem).getResult();
Assert.assertEquals(result.getEstimate(), sketch.getEstimate());//expected [98045.91060164096] but found [4096.0]
Assert.assertEquals(result.isEstimationMode(), sketch.isEstimationMode());
}
@Test
public void directDruidUsageTwoSketches() {
final WritableMemory mem = WritableMemory.writableWrap(new byte[1000000]);
new ArrayOfDoublesSetOperationBuilder().buildUnion(mem); // just set up memory to wrap later
int key = 0;
final int n1 = 100000; // estimation mode
final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < n1; i++) {
sketch1.update(key++, new double[] {1.0});
}
// as Druid wraps memory
ArrayOfDoublesSketches.wrapUnion(mem).union(sketch1.compact(WritableMemory.writableWrap(new byte[1000000])));
final int n2 = 1000000; // estimation mode
final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < n2; i++) {
sketch2.update(key++, new double[] {1.0});
}
// as Druid wraps memory
ArrayOfDoublesSketches.wrapUnion(mem).union(sketch2.compact(WritableMemory.writableWrap(new byte[1000000])));
// build one sketch that must be the same as union
key = 0; // reset to have the same keys
final int n = n1 + n2;
final ArrayOfDoublesUpdatableSketch expected = new ArrayOfDoublesUpdatableSketchBuilder().build();
for (int i = 0; i < n; i++) {
expected.update(key++, new double[] {1.0});
}
expected.trim(); // union result is trimmed, so we need to trim this sketch for valid comparison
final ArrayOfDoublesSketch result = ArrayOfDoublesUnion.wrap(mem).getResult();
Assert.assertEquals(result.getEstimate(), expected.getEstimate());
Assert.assertEquals(result.isEstimationMode(), expected.isEstimationMode());
Assert.assertEquals(result.getUpperBound(1), expected.getUpperBound(1));
Assert.assertEquals(result.getLowerBound(1), expected.getLowerBound(1));
Assert.assertEquals(result.getRetainedEntries(), expected.getRetainedEntries());
Assert.assertEquals(result.getNumValues(), expected.getNumValues());
}
}
| 2,350 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/CornerCaseArrayOfDoublesSetOperationsTest.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.tuple.arrayofdoubles;
import static org.apache.datasketches.common.Util.zeroPad;
import static org.apache.datasketches.hash.MurmurHash3.hash;
import static org.testng.Assert.assertTrue;
import org.apache.datasketches.thetacommon.ThetaUtil;
import org.testng.annotations.Test;
public class CornerCaseArrayOfDoublesSetOperationsTest {
//Stateful Intersection with intersect(sketch A, combiner), followed by getResult()
//Essentially Stateless AnotB with update(Sketch A, Sketch B), followed by getResult()
//Stateful Union with union(Sketch A), followed by getResult()
/* Hashes and Hash Equivalents
* Top8bits Hex Decimal
* MAX: 01111111, 7fffffffffffffff, 9223372036854775807
* GT_MIDP: 01011101, 5d6906dac1b340ba, 6730918654704304314 3L
* MIDP_THETALONG:01000000, 4000000000000000, 4611686018427387904
* GT_LOWP: 00010000, 10bc98fb132116fe, 1206007004353599230 6L
* LOWP_THETALONG:00010000, 1000000000000000, 1152921504606846976
* LT_LOWP: 00001000, 83ddbc9e12ede40, 593872385995628096 4L
*/
private static final float MIDP_FLT = 0.5f;
private static final float LOWP_FLT = 0.125f;
private static final long GT_MIDP_KEY = 3L;
private static final long GT_LOWP_KEY = 6L;
private static final long LT_LOWP_KEY = 4L;
private static final long MAX_LONG = Long.MAX_VALUE;
private static final long HASH_GT_MIDP = getLongHash(GT_MIDP_KEY);
private static final long MIDP_THETALONG = (long)(MAX_LONG * MIDP_FLT);
private static final long HASH_GT_LOWP = getLongHash(GT_LOWP_KEY);
private static final long LOWP_THETALONG = (long)(MAX_LONG * LOWP_FLT);
private static final long HASH_LT_LOWP = getLongHash(LT_LOWP_KEY);
private static final String LS = System.getProperty("line.separator");
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
}
private static class MinCombiner implements ArrayOfDoublesCombiner {
MinCombiner() {}
@Override
public double[] combine(double[] a, double[] b) {
return new double[] { Math.min(a[0], b[0]) };
}
}
private static MinCombiner minCombiner = new MinCombiner();
//=================================f
@Test
public void emptyEmpty() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EMPTY, 0, 0);
ArrayOfDoublesUpdatableSketch 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() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EMPTY, 0, 0);
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EXACT, 0, GT_MIDP_KEY);
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() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EMPTY, 0, 0);
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY);
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_FLT;
final int expectedUnionCount = 0;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void emptyEstimation() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EMPTY, 0, 0);
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY);
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_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
@Test
public void exactEmpty() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EXACT, 0, GT_MIDP_KEY);
ArrayOfDoublesUpdatableSketch 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() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EXACT, 0, GT_MIDP_KEY);
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EXACT, 0, GT_MIDP_KEY);
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() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EXACT, 0, LT_LOWP_KEY);
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY); //entries = 0
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 1;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void exactEstimation() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EXACT, 0, LT_LOWP_KEY);
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 1;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
@Test
public void estimationEmpty() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY);
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EMPTY, 0, 0);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = true;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 1;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void estimationExact() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY);
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EXACT, 0, LT_LOWP_KEY);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 1;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void estimationDegenerate() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.ESTIMATION, MIDP_FLT, LT_LOWP_KEY);
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 1;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void estimationEstimation() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.ESTIMATION, MIDP_FLT, LT_LOWP_KEY);
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 1;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
@Test
public void degenerateEmpty() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY); //entries = 0
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EMPTY, 0, 0);
final double expectedIntersectTheta = 1.0;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = true;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 0;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void degenerateExact() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY); //entries = 0
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EXACT, 0, LT_LOWP_KEY);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void degenerateDegenerate() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.DEGENERATE, MIDP_FLT, GT_MIDP_KEY); //entries = 0
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 0;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
@Test
public void degenerateEstimation() {
ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.DEGENERATE, MIDP_FLT, GT_MIDP_KEY); //entries = 0
ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY);
final double expectedIntersectTheta = LOWP_FLT;
final int expectedIntersectCount = 0;
final boolean expectedIntersectEmpty = false;
final double expectedAnotbTheta = LOWP_FLT;
final int expectedAnotbCount = 0;
final boolean expectedAnotbEmpty = false;
final double expectedUnionTheta = LOWP_FLT;
final int expectedUnionCount = 1;
final boolean expectedUnionEmpty = false;
checks(thetaA, thetaB,
expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty,
expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty,
expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
//=================================
//=================================
private static void checks(
ArrayOfDoublesUpdatableSketch tupleA,
ArrayOfDoublesUpdatableSketch tupleB,
double expectedIntersectTheta,
int expectedIntersectCount,
boolean expectedIntersectEmpty,
double expectedAnotbTheta,
int expectedAnotbCount,
boolean expectedAnotbEmpty,
double expectedUnionTheta,
int expectedUnionCount,
boolean expectedUnionEmpty) {
ArrayOfDoublesCompactSketch csk;
ArrayOfDoublesIntersection inter = new ArrayOfDoublesSetOperationBuilder().buildIntersection();
ArrayOfDoublesAnotB anotb = new ArrayOfDoublesSetOperationBuilder().buildAnotB();
ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().buildUnion();
//Intersection Tuple, Tuple Updatable Stateful
inter.intersect(tupleA, minCombiner);
inter.intersect(tupleB, minCombiner);
csk = inter.getResult();
inter.reset();
checkResult("Intersect Stateless Theta, Theta", csk, expectedIntersectTheta, expectedIntersectCount,
expectedIntersectEmpty);
//Intersection Tuple, Tuple Compact Stateful
inter.intersect(tupleA.compact(), minCombiner);
inter.intersect(tupleB.compact(), minCombiner);
csk = inter.getResult();
inter.reset();
checkResult("Intersect Stateless Theta, Theta", csk, expectedIntersectTheta, expectedIntersectCount,
expectedIntersectEmpty);
//AnotB Stateless Tuple, Tuple Updatable
anotb.update(tupleA, tupleB);
csk = anotb.getResult();
checkResult("AnotB Stateless Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//AnotB Stateless Tuple, Tuple Compact
anotb.update(tupleA, tupleB);
csk = anotb.getResult();
checkResult("AnotB Stateless Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty);
//Union Stateful Tuple, Tuple Updatable
union.union(tupleA);
union.union(tupleB);
csk = union.getResult();
union.reset();
checkResult("Union Stateless Theta, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
//Union Stateful Tuple, Tuple Compact
union.union(tupleA.compact());
union.union(tupleB.compact());
csk = union.getResult();
union.reset();
checkResult("Union Stateless Theta, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty);
}
private static void checkResult(
String comment,
ArrayOfDoublesCompactSketch 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 ArrayOfDoublesUpdatableSketch getSketch(
SkType skType,
float p,
long updateKey) {
ArrayOfDoublesUpdatableSketchBuilder bldr = new ArrayOfDoublesUpdatableSketchBuilder();
bldr.setNominalEntries(16);
//Assume defaults: 1 double value, resize factor, seed
double[] summaryVal = {1.0};
ArrayOfDoublesUpdatableSketch 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(updateKey, summaryVal);
break;
}
case ESTIMATION: { // {<1.0, >0, F}
checkValidUpdate(p, updateKey);
bldr.setSamplingProbability(p);
sk = bldr.build();
sk.update(updateKey, summaryVal);
break;
}
case DEGENERATE: { // {<1.0, 0, F}
checkInvalidUpdate(p, updateKey);
bldr.setSamplingProbability(p);
sk = bldr.build();
sk.update(updateKey, summaryVal); // > theta
break;
}
default: { return null; } // should not happen
}
return sk;
}
private static void checkValidUpdate(float p, long updateKey) {
assertTrue( getLongHash(updateKey) < (long) (p * Long.MAX_VALUE));
}
private static void checkInvalidUpdate(float p, long updateKey) {
assertTrue( getLongHash(updateKey) > (long) (p * Long.MAX_VALUE));
}
//*******************************************
//Helper functions for setting the hash values
//@Test
public void printTable() {
println(" Top8bits Hex Decimal");
printf("MAX: %8s, %16x, %19d" + LS, getTop8(MAX_LONG), MAX_LONG, MAX_LONG);
printf("GT_MIDP: %8s, %16x, %19d" + LS, getTop8(HASH_GT_MIDP), HASH_GT_MIDP, HASH_GT_MIDP);
printf("MIDP_THETALONG:%8s, %16x, %19d" + LS, getTop8(MIDP_THETALONG), MIDP_THETALONG, MIDP_THETALONG);
printf("GT_LOWP: %8s, %16x, %19d" + LS, getTop8(HASH_GT_LOWP), HASH_GT_LOWP, HASH_GT_LOWP);
printf("LOWP_THETALONG:%8s, %16x, %19d" + LS, getTop8(LOWP_THETALONG), LOWP_THETALONG, LOWP_THETALONG);
printf("LT_LOWP: %8s, %16x, %19d" + LS, getTop8(HASH_LT_LOWP), HASH_LT_LOWP, HASH_LT_LOWP);
println(LS +"Doubles");
println(LS + "Longs");
for (long v = 1L; v < 10; v++) {
long hash = (hash(v, ThetaUtil.DEFAULT_UPDATE_SEED)[0]) >>> 1;
printLong(v, hash);
}
}
static long getLongHash(long v) {
return (hash(v, ThetaUtil.DEFAULT_UPDATE_SEED)[0]) >>> 1;
}
static void printLong(long v, long hash) {
System.out.printf(" %8d, %8s, %16x, %19d" + LS,v, getTop8(hash), hash, hash);
}
static String getTop8(final long v) {
int i = (int) (v >>> 56);
String s = Integer.toBinaryString(i);
return zeroPad(s, 8);
}
private static void println(Object o) {
System.out.println(o.toString());
}
private static void printf(String fmt, Object ...args) {
System.out.printf(fmt, args);
}
}
| 2,351 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hllmap/UniqueCountMapTest.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.hllmap;
import static org.apache.datasketches.hash.MurmurHash3.hash;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.Util;
public class UniqueCountMapTest {
private final static int INIT_ENTRIES = 211;
@Test
public void nullKey() {
UniqueCountMap map = new UniqueCountMap(4);
double estimate = map.update(null, null);
Assert.assertTrue(Double.isNaN(estimate));
Assert.assertTrue(Double.isNaN(map.getEstimate(null)));
Assert.assertTrue(Double.isNaN(map.getUpperBound(null)));
Assert.assertTrue(Double.isNaN(map.getLowerBound(null)));
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void wrongSizeKeyUpdate() {
UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4);
byte[] key = new byte[] {0};
map.update(key, null);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void wrongSizeKey() {
UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 2);
println(map.toString());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void wrongSizeKeyGetEstimate() {
UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4);
byte[] key = new byte[] {0};
map.getEstimate(key);
}
@Test
public void emptyMapNullValue() {
UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4);
double estimate = map.update("1234".getBytes(UTF_8), null);
Assert.assertEquals(estimate, 0.0);
}
@Test
public void oneEntry() {
UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4);
double estimate = map.update("1234".getBytes(UTF_8), "a".getBytes(UTF_8));
Assert.assertEquals(estimate, 1.0, 0.01);
}
@Test
public void duplicateEntry() {
UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4);
byte[] key = "1234".getBytes(UTF_8);
double estimate = map.update(key, "a".getBytes(UTF_8));
Assert.assertEquals(estimate, 1.0);
estimate = map.update(key, "a".getBytes(UTF_8));
Assert.assertEquals(estimate, 1.0);
estimate = map.update(key, null);
Assert.assertEquals(estimate, 1.0);
}
@Test
public void oneKeyTwoValues() {
UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4);
double estimate = map.update("1234".getBytes(UTF_8), "a".getBytes(UTF_8));
Assert.assertEquals(estimate, 1.0);
estimate = map.update("1234".getBytes(UTF_8), "b".getBytes(UTF_8));
Assert.assertEquals(estimate, 2.0, 0.02);
}
@Test
public void oneKeyThreeValues() {
UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4);
byte[] key = "1234".getBytes(UTF_8);
double estimate = map.update(key, "a".getBytes(UTF_8));
Assert.assertEquals(estimate, 1.0);
estimate = map.update(key, "b".getBytes(UTF_8));
Assert.assertEquals(estimate, 2.0);
estimate = map.update(key, "c".getBytes(UTF_8));
Assert.assertEquals(estimate, 3.0);
}
@Test
public void oneKeyManyValues() {
UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4);
byte[] key = "1234".getBytes(UTF_8);
byte[] id = new byte[4];
for (int i = 1; i <= 1000; i++) {
id = Util.intToBytes(i, id);
double estimate = map.update(key, id);
if ((i % 100) == 0) {
double err = ((estimate/i) -1.0) * 100;
String eStr = String.format("%.3f%%", err);
println("i: "+i + "\t Est: " + estimate + "\t" + eStr);
}
Assert.assertEquals(estimate, i, i * 0.10);
Assert.assertEquals(map.getEstimate(key), estimate);
Assert.assertTrue(map.getUpperBound(key) >= estimate);
Assert.assertTrue(map.getLowerBound(key) <= estimate);
}
String out = map.toString();
println(out);
}
@Test
public void manyKeys() {
UniqueCountMap map = new UniqueCountMap(2000, 4);
for (int i = 1; i <= 1000; i++) {
byte[] key = String.format("%4s", i).getBytes(UTF_8);
double estimate = map.update(key, new byte[] {1});
Assert.assertEquals(estimate, 1.0);
}
Assert.assertEquals(1000, map.getActiveEntries());
for (int i = 1; i <= 1000; i++) {
byte[] key = String.format("%4s", i).getBytes(UTF_8);
double estimate = map.update(key, new byte[] {2});
Assert.assertEquals(estimate, 2.0);
}
Assert.assertEquals(1000, map.getActiveEntries());
for (int i = 1; i <= 1000; i++) {
byte[] key = String.format("%4s", i).getBytes(UTF_8);
double estimate = map.update(key, new byte[] {3});
Assert.assertEquals(estimate, 3.0);
}
Assert.assertEquals(1000, map.getActiveEntries());
String out = map.toString();
println(out);
}
@Test
public void forceDeletesAndReuse() {
UniqueCountMap map = new UniqueCountMap(156, 4);
byte[] key = new byte[4];
byte[] id = new byte[8];
for (int v = 1; v <= 200; v++) {
long h = (int) hash(new long[]{v}, 0L)[0];
id = Util.longToBytes(h, id);
for(int k = 1; k <= 147; k++) {
key = Util.intToBytes(k, key);
map.update(key, id);
}
}
//reuse
for (int v = 1; v <= 200; v++) {
long h = (int) hash(new long[]{v}, 0L)[0];
id = Util.longToBytes(h, id);
for(int k = 1+147; k <= (2 * 147); k++) {
key = Util.intToBytes(k, key);
map.update(key, id);
}
}
Assert.assertNotNull(map.getBaseMap());
Assert.assertNotNull(map.getHllMap());
//println(map.toString());
}
@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,352 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hllmap/CouponTraverseMapTest.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.hllmap;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.testng.Assert;
import org.testng.annotations.Test;
public class CouponTraverseMapTest {
@Test
public void getEstimateNoEntry() {
CouponTraverseMap map = CouponTraverseMap.getInstance(4, 1);
byte[] key = new byte[] {0, 0, 0 ,0};
Assert.assertEquals(map.getEstimate(key), 0.0);
Assert.assertEquals(map.getUpperBound(key), 0.0);
Assert.assertEquals(map.getLowerBound(key), 0.0);
}
@Test
public void oneKeyOneEntry() {
CouponTraverseMap map = CouponTraverseMap.getInstance(4, 1);
byte[] key = new byte[] {0, 0, 0 ,0};
double estimate = map.update(key, (short) 1);
Assert.assertEquals(estimate, 1.0);
Assert.assertEquals(map.getEstimate(key), 1.0);
Assert.assertTrue(map.getUpperBound(key) >= 1.0);
Assert.assertTrue(map.getLowerBound(key) <= 1.0);
}
@Test
public void delete() {
CouponTraverseMap map = CouponTraverseMap.getInstance(4, 1);
double estimate = map.update("1234".getBytes(UTF_8), (short) 1);
Assert.assertEquals(estimate, 1.0);
int index1 = map.findKey("1234".getBytes(UTF_8));
Assert.assertTrue(index1 >= 0);
map.deleteKey(index1);
int index2 = map.findKey("1234".getBytes(UTF_8));
// should be complement of the same index as before
Assert.assertEquals(~index2, index1);
Assert.assertEquals(map.getEstimate("1".getBytes(UTF_8)), 0.0);
}
@Test
public void growAndShrink() {
CouponTraverseMap map = CouponTraverseMap.getInstance(4, 1);
long sizeBytes1 = map.getMemoryUsageBytes();
for (int i = 0; i < 1000; i ++) {
byte[] key = String.format("%4s", i).getBytes(UTF_8);
map.update(key, (short) 1);
}
long sizeBytes2 = map.getMemoryUsageBytes();
Assert.assertTrue(sizeBytes2 > sizeBytes1);
for (int i = 0; i < 1000; i ++) {
byte[] key = String.format("%4s", i).getBytes(UTF_8);
int index = map.findKey(key);
Assert.assertTrue(index >= 0);
map.deleteKey(index);
}
long sizeBytes3 = map.getMemoryUsageBytes();
Assert.assertTrue(sizeBytes3 < sizeBytes2);
println(map.toString());
}
@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,353 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hllmap/SingleCouponMapTest.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.hllmap;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SingleCouponMapTest {
@Test
public void getEstimateNoEntry() {
SingleCouponMap map = SingleCouponMap.getInstance(1000, 4);
byte[] key = new byte[] {0, 0, 0, 1};
Assert.assertEquals(map.getEstimate(key), 0.0);
Assert.assertEquals(map.getUpperBound(key), 0.0);
Assert.assertEquals(map.getLowerBound(key), 0.0);
}
@Test
public void oneKeyOneEntry() {
int entries = 16;
int keySizeBytes = 4;
SingleCouponMap map = SingleCouponMap.getInstance(entries, keySizeBytes);
byte[] key = new byte[] {0, 0, 0, 0}; // zero key must work
byte[] id = new byte[] {1, 0, 0, 0};
short coupon = (short) Map.coupon16(id);
double estimate = map.update(key, coupon);
Assert.assertEquals(estimate, 1.0);
Assert.assertEquals(map.getEstimate(key), 1.0);
Assert.assertTrue(map.getUpperBound(key) >= 1.0);
Assert.assertTrue(map.getLowerBound(key) <= 1.0);
}
@Test
public void resize() {
int entries = 17;
int numKeys = 1000;
int keySizeBytes = 4;
SingleCouponMap map = SingleCouponMap.getInstance(entries, keySizeBytes);
for (int i = 0; i < numKeys; i++) {
byte[] key = String.format("%4s", i).getBytes(UTF_8);
byte[] id = new byte[] {1, 0, 0, 0};
short coupon = (short) Map.coupon16(id);
double estimate = map.update(key, coupon);
Assert.assertEquals(estimate, 1.0);
Assert.assertEquals(map.getEstimate(key), 1.0);
Assert.assertTrue(map.getUpperBound(key) >= 1.0);
Assert.assertTrue(map.getLowerBound(key) <= 1.0);
}
for (int i = 0; i < numKeys; i++) {
byte[] key = String.format("%4s", i).getBytes(UTF_8);
Assert.assertEquals(map.getEstimate(key), 1.0);
Assert.assertTrue(map.getUpperBound(key) >= 1.0);
Assert.assertTrue(map.getLowerBound(key) <= 1.0);
}
println(map.toString());
Assert.assertEquals(map.getCurrentCountEntries(), numKeys);
}
@Test
public void manyKeys() {
SingleCouponMap map = SingleCouponMap.getInstance(2000, 4);
for (int i = 1; i <= 1000; i++) {
byte[] key = String.format("%4s", i).getBytes(UTF_8);
double estimate = map.update(key, (short) 1); //bogus coupon
Assert.assertEquals(estimate, 1.0);
Assert.assertEquals(map.getEstimate(key), 1.0);
Assert.assertTrue(map.getUpperBound(key) >= 1.0);
Assert.assertTrue(map.getLowerBound(key) <= 1.0);
}
for (int i = 1; i <= 1000; i++) {
byte[] key = String.format("%4s", i).getBytes(UTF_8);
double estimate = map.update(key, (short) 2); //different bogus coupon
Assert.assertEquals(estimate, 0.0); // signal to promote
}
Assert.assertEquals(map.getCurrentCountEntries(), 1000);
}
@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,354 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hllmap/HllMapTest.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.hllmap;
import org.apache.datasketches.common.Util;
import org.testng.Assert;
import org.testng.annotations.Test;
public class HllMapTest {
@Test
public void singleKeyTest() {
int k = 1024;
int u = 1000;
int keySize = 4;
HllMap map = HllMap.getInstance(keySize, k);
Assert.assertTrue(Double.isNaN(map.getEstimate(null)));
Assert.assertTrue(map.getEntrySizeBytes() > 800);
Assert.assertEquals(map.getCapacityEntries(), 147);
Assert.assertEquals(map.getTableEntries(), 157);
Assert.assertTrue(map.getMemoryUsageBytes() < 140000);
// println("Entry bytes : " + map.getEntrySizeBytes());
// println("Capacity : " + map.getCapacityEntries());
// println("Table Entries : " + map.getTableEntries());
// println("Est Arr Size : " + (map.getEntrySizeBytes() * map.getTableEntries()));
// println("Size of Arrays: "+ map.getMemoryUsageBytes());
byte[] key = new byte[4];
byte[] id = new byte[4];
double est;
key = Util.intToBytes(1, key);
for (int i=1; i<= u; i++) {
id = Util.intToBytes(i, id);
short coupon = (short) Map.coupon16(id);
est = map.update(key, coupon);
if ((i % 100) == 0) {
double err = ((est/i) -1.0) * 100;
String eStr = String.format("%.3f%%", err);
println("i: "+i + "\t Est: " + est + "\t" + eStr);
}
}
byte[] key2 = Util.intToBytes(2, key);
Assert.assertEquals(map.getEstimate(key2), 0.0);
Assert.assertEquals(map.getKeySizeBytes(), 4);
// println("Table Entries : " + map.getTableEntries());
Assert.assertEquals(map.getCurrentCountEntries(), 1);
// println("Cur Count : " + map.getCurrentCountEntries());
// println("RSE : " + (1/Math.sqrt(k)));
//map.printEntry(key);
}
@Test
public void resizeTest() {
int k = 1024;
int u = 257;
int keys = 200;
int keySize = 4;
long v = 0;
HllMap map = HllMap.getInstance(keySize, k);
Assert.assertTrue(map.getEntrySizeBytes() > 800);
Assert.assertEquals(map.getCapacityEntries(), 147);
Assert.assertEquals(map.getTableEntries(), 157);
Assert.assertTrue(map.getMemoryUsageBytes() < 140000);
// println("Entry bytes : " + map.getEntrySizeBytes());
// println("Capacity : " + map.getCapacityEntries());
// println("Table Entries : " + map.getTableEntries());
// println("Size of Arrays: " + map.getMemoryUsageBytes());
byte[] key = new byte[4];
byte[] id = new byte[8];
int i, j;
for (j=1; j<=keys; j++) {
key = Util.intToBytes(j, key);
for (i=0; i< u; i++) {
id = Util.longToBytes(++v, id);
short coupon = (short) Map.coupon16(id);
map.update(key, coupon);
}
double est = map.getEstimate(key);
Assert.assertTrue(map.getUpperBound(key) > est);
Assert.assertTrue(map.getLowerBound(key) < est);
double err = ((est/u) -1.0) * 100;
String eStr = String.format("%.3f%%", err);
println("key: " + j + "\tu: "+u + "\t Est: " + est + "\t" + eStr);
}
Assert.assertEquals(317, map.getTableEntries());
// println("Table Entries : " + map.getTableEntries());
Assert.assertEquals(200, map.getCurrentCountEntries());
// println("Cur Count : " + map.getCurrentCountEntries());
// println("Theoretical RSE: " + (1/Math.sqrt(k)));
for (j=1; j<=keys; j++) {
key = Util.intToBytes(j, key);
double est = map.getEstimate(key);
double err = ((est/u) -1.0) * 100;
String eStr = String.format("%.3f%%", err);
println("key: " + j + "\tu: "+u + "\t Est: " + est + "\t" + eStr);
}
//println(map.toString());
}
@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,355 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/hllmap/CouponHashMapTest.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.hllmap;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.apache.datasketches.common.SketchesArgumentException;
import org.testng.Assert;
import org.testng.annotations.Test;
public class CouponHashMapTest {
@Test
public void getEstimateNoEntry() {
CouponHashMap map = CouponHashMap.getInstance(4, 16);
byte[] key = new byte[] {0, 0, 0, 0};
Assert.assertEquals(map.getEstimate(key), 0.0);
Assert.assertEquals(map.getUpperBound(key), 0.0);
Assert.assertEquals(map.getLowerBound(key), 0.0);
}
@Test
public void oneKeyOneEntry() {
CouponHashMap map = CouponHashMap.getInstance(4, 16);
byte[] key = new byte[] {0, 0, 0, 0};
double estimate = map.update(key, (short) 1);
Assert.assertEquals(estimate, 1.0);
Assert.assertEquals(map.getEstimate(key), 1.0);
Assert.assertTrue(map.getUpperBound(key) > 1.0);
Assert.assertTrue(map.getLowerBound(key) < 1.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void keyNotFound() {
CouponHashMap map = CouponHashMap.getInstance(4, 16);
byte[] key = new byte[] {0, 0, 0, 0};
map.update(key, (short) 1);
map.updateEstimate(map.findKey(new byte[] {1,0,0,0}), 2.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void wrongCouponsPerKey() {
CouponHashMap map = CouponHashMap.getInstance(4, 8);
println(map.toString()); //required otherwise FindBugs will show error
}
@Test
public void delete() {
CouponHashMap map = CouponHashMap.getInstance(4, 16);
double estimate = map.update("1234".getBytes(UTF_8), (short) 1);
Assert.assertEquals(estimate, 1.0);
int index1 = map.findKey("1234".getBytes(UTF_8));
Assert.assertTrue(index1 >= 0);
map.deleteKey(index1);
int index2 = map.findKey("1234".getBytes(UTF_8));
// should be complement of the same index as before
Assert.assertEquals(~index2, index1);
Assert.assertEquals(map.getEstimate("1234".getBytes(UTF_8)), 0.0);
}
@Test
public void growAndShrink() {
CouponHashMap map = CouponHashMap.getInstance(4, 16);
long sizeBytes1 = map.getMemoryUsageBytes();
for (int i = 0; i < 1000; i ++) {
byte[] key = String.format("%4s", i).getBytes(UTF_8);
map.update(key, (short) Map.coupon16(new byte[] {1}));
}
long sizeBytes2 = map.getMemoryUsageBytes();
Assert.assertTrue(sizeBytes2 > sizeBytes1);
for (int i = 0; i < 1000; i ++) {
byte[] key = String.format("%4s", i).getBytes(UTF_8);
int index = map.findKey(key);
Assert.assertTrue(index >= 0);
map.deleteKey(index);
}
long sizeBytes3 = map.getMemoryUsageBytes();
Assert.assertTrue(sizeBytes3 < sizeBytes2);
println(map.toString());
}
@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,356 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/frequencies/LongsSketchTest.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.frequencies;
import static org.apache.datasketches.common.Util.LS;
import static org.apache.datasketches.frequencies.DistTest.randomGeometricDist;
import static org.apache.datasketches.frequencies.PreambleUtil.FAMILY_BYTE;
import static org.apache.datasketches.frequencies.PreambleUtil.FLAGS_BYTE;
import static org.apache.datasketches.frequencies.PreambleUtil.PREAMBLE_LONGS_BYTE;
import static org.apache.datasketches.frequencies.PreambleUtil.SER_VER_BYTE;
import static org.apache.datasketches.frequencies.Util.LG_MIN_MAP_SIZE;
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;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.Util;
import org.apache.datasketches.frequencies.LongsSketch.Row;
public class LongsSketchTest {
@Test
public void hashMapSerialTest() {
ReversePurgeLongHashMap map = new ReversePurgeLongHashMap(8);
map.adjustOrPutValue(10, 15);
map.adjustOrPutValue(10, 5);
map.adjustOrPutValue(1, 1);
map.adjustOrPutValue(2, 3);
String string = map.serializeToString();
//println(string);
//println(map.toString());
ReversePurgeLongHashMap new_map =
ReversePurgeLongHashMap.getInstance(string);
String new_string = new_map.serializeToString();
Assert.assertTrue(string.equals(new_string));
}
@Test
public void frequentItemsStringSerialTest() {
LongsSketch sketch = new LongsSketch(8);
LongsSketch sketch2 = new LongsSketch(128);
sketch.update(10, 100);
sketch.update(10, 100);
sketch.update(15, 3443);
sketch.update(1000001, 1010230);
sketch.update(1000002, 1010230);
String string0 = sketch.serializeToString();
LongsSketch new_sketch0 = LongsSketch.getInstance(string0);
String new_string0 = new_sketch0.serializeToString();
Assert.assertTrue(string0.equals(new_string0));
Assert.assertTrue(new_sketch0.getMaximumMapCapacity() == sketch.getMaximumMapCapacity());
Assert.assertTrue(new_sketch0.getCurrentMapCapacity() == sketch.getCurrentMapCapacity());
sketch2.update(190, 12902390);
sketch2.update(191, 12902390);
sketch2.update(192, 12902390);
sketch2.update(193, 12902390);
sketch2.update(194, 12902390);
sketch2.update(195, 12902390);
sketch2.update(196, 12902390);
sketch2.update(197, 12902390);
sketch2.update(198, 12902390);
sketch2.update(199, 12902390);
sketch2.update(200, 12902390);
sketch2.update(201, 12902390);
sketch2.update(202, 12902390);
sketch2.update(203, 12902390);
sketch2.update(204, 12902390);
sketch2.update(205, 12902390);
sketch2.update(206, 12902390);
sketch2.update(207, 12902390);
sketch2.update(208, 12902390);
String string2 = sketch2.serializeToString();
LongsSketch new_sketch2 = LongsSketch.getInstance(string2);
String new_string2 = new_sketch2.serializeToString();
Assert.assertTrue(string2.equals(new_string2));
Assert.assertTrue(new_sketch2.getMaximumMapCapacity() == sketch2.getMaximumMapCapacity());
Assert.assertTrue(new_sketch2.getCurrentMapCapacity() == sketch2.getCurrentMapCapacity());
Assert.assertTrue(new_sketch2.getStreamLength() == sketch2.getStreamLength());
LongsSketch merged_sketch = sketch.merge(sketch2);
String string = merged_sketch.serializeToString();
LongsSketch new_sketch = LongsSketch.getInstance(string);
String new_string = new_sketch.serializeToString();
Assert.assertTrue(string.equals(new_string));
Assert.assertTrue(new_sketch.getMaximumMapCapacity() == merged_sketch.getMaximumMapCapacity());
Assert.assertTrue(new_sketch.getCurrentMapCapacity() == merged_sketch.getCurrentMapCapacity());
Assert.assertTrue(new_sketch.getStreamLength() == merged_sketch.getStreamLength());
}
@Test
public void frequentItemsByteSerialTest() {
//Empty Sketch
LongsSketch sketch = new LongsSketch(16);
byte[] bytearray0 = sketch.toByteArray();
WritableMemory mem0 = WritableMemory.writableWrap(bytearray0);
LongsSketch new_sketch0 = LongsSketch.getInstance(mem0);
String str0 = LongsSketch.toString(mem0);
println(str0);
String string0 = sketch.serializeToString();
String new_string0 = new_sketch0.serializeToString();
Assert.assertTrue(string0.equals(new_string0));
LongsSketch sketch2 = new LongsSketch(128);
sketch.update(10, 100);
sketch.update(10, 100);
sketch.update(15, 3443);
sketch.update(1000001, 1010230);
sketch.update(1000002, 1010230);
byte[] bytearray1 = sketch.toByteArray();
Memory mem1 = Memory.wrap(bytearray1);
LongsSketch new_sketch1 = LongsSketch.getInstance(mem1);
String str1 = LongsSketch.toString(bytearray1);
println(str1);
String string1 = sketch.serializeToString();
String new_string1 = new_sketch1.serializeToString();
Assert.assertTrue(string1.equals(new_string1));
Assert.assertTrue(new_sketch1.getMaximumMapCapacity() == sketch.getMaximumMapCapacity());
Assert.assertTrue(new_sketch1.getCurrentMapCapacity() == sketch.getCurrentMapCapacity());
sketch2.update(190, 12902390);
sketch2.update(191, 12902390);
sketch2.update(192, 12902390);
sketch2.update(193, 12902390);
sketch2.update(194, 12902390);
sketch2.update(195, 12902390);
sketch2.update(196, 12902390);
sketch2.update(197, 12902390);
sketch2.update(198, 12902390);
sketch2.update(199, 12902390);
sketch2.update(200, 12902390);
sketch2.update(201, 12902390);
sketch2.update(202, 12902390);
sketch2.update(203, 12902390);
sketch2.update(204, 12902390);
sketch2.update(205, 12902390);
sketch2.update(206, 12902390);
sketch2.update(207, 12902390);
sketch2.update(208, 12902390);
byte[] bytearray2 = sketch2.toByteArray();
Memory mem2 = Memory.wrap(bytearray2);
LongsSketch new_sketch2 = LongsSketch.getInstance(mem2);
String string2 = sketch2.serializeToString();
String new_string2 = new_sketch2.serializeToString();
Assert.assertTrue(string2.equals(new_string2));
Assert.assertTrue(new_sketch2.getMaximumMapCapacity() == sketch2.getMaximumMapCapacity());
Assert.assertTrue(new_sketch2.getCurrentMapCapacity() == sketch2.getCurrentMapCapacity());
Assert.assertTrue(new_sketch2.getStreamLength() == sketch2.getStreamLength());
LongsSketch merged_sketch = sketch.merge(sketch2);
byte[] bytearray = sketch.toByteArray();
Memory mem = Memory.wrap(bytearray);
LongsSketch new_sketch = LongsSketch.getInstance(mem);
String string = sketch.serializeToString();
String new_string = new_sketch.serializeToString();
Assert.assertTrue(string.equals(new_string));
Assert.assertTrue(new_sketch.getMaximumMapCapacity() == merged_sketch.getMaximumMapCapacity());
Assert.assertTrue(new_sketch.getCurrentMapCapacity() == merged_sketch.getCurrentMapCapacity());
Assert.assertTrue(new_sketch.getStreamLength() == merged_sketch.getStreamLength());
}
@Test
public void frequentItemsByteResetAndEmptySerialTest() {
LongsSketch sketch = new LongsSketch(16);
sketch.update(10, 100);
sketch.update(10, 100);
sketch.update(15, 3443);
sketch.update(1000001, 1010230);
sketch.update(1000002, 1010230);
sketch.reset();
byte[] bytearray0 = sketch.toByteArray();
Memory mem0 = Memory.wrap(bytearray0);
LongsSketch new_sketch0 = LongsSketch.getInstance(mem0);
String string0 = sketch.serializeToString();
String new_string0 = new_sketch0.serializeToString();
Assert.assertTrue(string0.equals(new_string0));
Assert.assertTrue(new_sketch0.getMaximumMapCapacity() == sketch.getMaximumMapCapacity());
Assert.assertTrue(new_sketch0.getCurrentMapCapacity() == sketch.getCurrentMapCapacity());
}
@Test
public void checkFreqLongsMemSerDe() {
int minSize = 1 << LG_MIN_MAP_SIZE;
LongsSketch sk1 = new LongsSketch(minSize);
sk1.update(10, 100);
sk1.update(10, 100);
sk1.update(15, 3443); println(sk1.toString());
sk1.update(1000001, 1010230); println(sk1.toString());
sk1.update(1000002, 1010230); println(sk1.toString());
byte[] bytearray0 = sk1.toByteArray();
Memory mem0 = Memory.wrap(bytearray0);
LongsSketch sk2 = LongsSketch.getInstance(mem0);
checkEquality(sk1, sk2);
}
@Test
public void checkFreqLongsStringSerDe() {
int minSize = 1 << LG_MIN_MAP_SIZE;
LongsSketch sk1 = new LongsSketch(minSize);
sk1.update(10, 100);
sk1.update(10, 100);
sk1.update(15, 3443);
sk1.update(1000001, 1010230);
sk1.update(1000002, 1010230);
String string1 = sk1.serializeToString();
LongsSketch sk2 = LongsSketch.getInstance(string1);
checkEquality(sk1, sk2);
}
private static void checkEquality(LongsSketch sk1, LongsSketch sk2) {
assertEquals(sk1.getNumActiveItems(), sk2.getNumActiveItems());
assertEquals(sk1.getCurrentMapCapacity(), sk2.getCurrentMapCapacity());
assertEquals(sk1.getMaximumError(), sk2.getMaximumError());
assertEquals(sk1.getMaximumMapCapacity(), sk2.getMaximumMapCapacity());
assertEquals(sk1.getStorageBytes(), sk2.getStorageBytes());
assertEquals(sk1.getStreamLength(), sk2.getStreamLength());
assertEquals(sk1.isEmpty(), sk2.isEmpty());
ErrorType NFN = ErrorType.NO_FALSE_NEGATIVES;
ErrorType NFP = ErrorType.NO_FALSE_POSITIVES;
Row[] rowArr1 = sk1.getFrequentItems(NFN);
Row[] rowArr2 = sk2.getFrequentItems(NFN);
assertEquals(sk1.getFrequentItems(NFN).length, sk2.getFrequentItems(NFN).length);
for (int i=0; i<rowArr1.length; i++) {
String s1 = rowArr1[i].toString();
String s2 = rowArr2[i].toString();
assertEquals(s1, s2);
}
rowArr1 = sk1.getFrequentItems(NFP);
rowArr2 = sk2.getFrequentItems(NFP);
assertEquals(sk1.getFrequentItems(NFP).length, sk2.getFrequentItems(NFP).length);
for (int i=0; i<rowArr1.length; i++) {
String s1 = rowArr1[i].toString();
String s2 = rowArr2[i].toString();
assertEquals(s1, s2);
}
}
@Test
public void checkFreqLongsMemDeSerExceptions() {
int minSize = 1 << LG_MIN_MAP_SIZE;
LongsSketch sk1 = new LongsSketch(minSize);
sk1.update(1L);
byte[] bytearray0 = sk1.toByteArray();
WritableMemory mem = WritableMemory.writableWrap(bytearray0);
long pre0 = mem.getLong(0);
tryBadMem(mem, PREAMBLE_LONGS_BYTE, 2); //Corrupt
mem.putLong(0, pre0); //restore
tryBadMem(mem, SER_VER_BYTE, 2); //Corrupt
mem.putLong(0, pre0); //restore
tryBadMem(mem, FAMILY_BYTE, 2); //Corrupt
mem.putLong(0, pre0); //restore
tryBadMem(mem, FLAGS_BYTE, 4); //Corrupt to true
mem.putLong(0, pre0); //restore
}
private static void tryBadMem(WritableMemory mem, int byteOffset, int byteValue) {
try {
mem.putByte(byteOffset, (byte) byteValue); //Corrupt
LongsSketch.getInstance(mem);
fail();
} catch (SketchesArgumentException e) {
//expected
}
}
@Test
public void checkFreqLongsStringDeSerExceptions() {
//FrequentLongsSketch sk1 = new FrequentLongsSketch(8);
//String str1 = sk1.serializeToString();
//String correct = "1,10,2,4,0,0,0,4,";
tryBadString("2,10,2,4,0,0,0,4,"); //bad SerVer of 2
tryBadString("1,10,2,0,0,0,0,4,"); //bad empty of 0
tryBadString( "1,10,2,4,0,0,0,4,0,"); //one extra
}
private static void tryBadString(String badString) {
try {
LongsSketch.getInstance(badString);
fail("Should have thrown SketchesArgumentException");
} catch (SketchesArgumentException e) {
//expected
}
}
@Test
public void checkFreqLongs(){
int numSketches = 1;
int n = 2222;
double error_tolerance = 1.0/100;
LongsSketch[] sketches = new LongsSketch[numSketches];
for (int h = 0; h < numSketches; h++) {
sketches[h] = newFrequencySketch(error_tolerance);
}
long item;
double prob = .001;
for (int i = 0; i < n; i++) {
item = randomGeometricDist(prob) + 1;
for (int h = 0; h < numSketches; h++) {
sketches[h].update(item);
}
}
for (int h = 0; h < numSketches; h++) {
long threshold = sketches[h].getMaximumError();
Row[] rows = sketches[h].getFrequentItems(ErrorType.NO_FALSE_NEGATIVES);
for (int i = 0; i < rows.length; i++) {
Assert.assertTrue(rows[i].getUpperBound() > threshold);
}
rows = sketches[h].getFrequentItems(ErrorType.NO_FALSE_POSITIVES);
for (int i = 0; i < rows.length; i++) {
Assert.assertTrue(rows[i].getLowerBound() > threshold);
}
rows = sketches[h].getFrequentItems(Long.MAX_VALUE, ErrorType.NO_FALSE_POSITIVES);
Assert.assertEquals(rows.length, 0);
}
}
@Test
public void updateOneTime() {
int size = 100;
double error_tolerance = 1.0 / size;
//double delta = .01;
int numSketches = 1;
for (int h = 0; h < numSketches; h++) {
LongsSketch sketch = newFrequencySketch(error_tolerance);
Assert.assertEquals(sketch.getUpperBound(13L), 0);
Assert.assertEquals(sketch.getLowerBound(13L), 0);
Assert.assertEquals(sketch.getMaximumError(), 0);
Assert.assertEquals(sketch.getEstimate(13L), 0);
sketch.update(13L);
// Assert.assertEquals(sketch.getEstimate(13L), 1);
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkGetInstanceMemory() {
WritableMemory mem = WritableMemory.writableWrap(new byte[4]);
LongsSketch.getInstance(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkGetInstanceString() {
String s = "";
LongsSketch.getInstance(s);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkUpdateNegative() {
int minSize = 1 << LG_MIN_MAP_SIZE;
LongsSketch fls = new LongsSketch(minSize);
fls.update(1, 0);
fls.update(1, -1);
}
@SuppressWarnings("unlikely-arg-type")
@Test
public void checkGetFrequentItems1() {
int minSize = 1 << LG_MIN_MAP_SIZE;
LongsSketch fis = new LongsSketch(minSize);
fis.update(1);
Row[] rowArr = fis.getFrequentItems(ErrorType.NO_FALSE_POSITIVES);
Row row = rowArr[0];
assertTrue(row.hashCode() != 0);
assertTrue(row.equals(row));
assertFalse(row.equals(fis));
assertNotNull(row);
assertEquals(row.est, 1L);
assertEquals(row.item, 1L);
assertEquals(row.lb, 1L);
assertEquals(row.ub, 1L);
Row newRow = new Row(row.item, row.est+1, row.ub, row.lb);
assertFalse(row.equals(newRow));
newRow = new Row(row.item, row.est, row.ub, row.lb);
assertTrue(row.equals(newRow));
}
@Test
public void checkGetStorageBytes() {
int minSize = 1 << LG_MIN_MAP_SIZE;
LongsSketch fls = new LongsSketch(minSize);
assertEquals(fls.toByteArray().length, fls.getStorageBytes());
fls.update(1);
assertEquals(fls.toByteArray().length, fls.getStorageBytes());
}
@Test
public void checkDeSerFromStringArray() {
int minSize = 1 << LG_MIN_MAP_SIZE;
LongsSketch fls = new LongsSketch(minSize);
String ser = fls.serializeToString();
println(ser);
fls.update(1);
ser = fls.serializeToString();
println(ser);
}
@Test
public void checkMerge() {
int minSize = 1 << LG_MIN_MAP_SIZE;
LongsSketch fls1 = new LongsSketch(minSize);
LongsSketch fls2 = null;
LongsSketch fle = fls1.merge(fls2);
assertTrue(fle.isEmpty());
fls2 = new LongsSketch(minSize);
fle = fls1.merge(fls2);
assertTrue(fle.isEmpty());
}
@Test
public void checkSortItems() {
int numSketches = 1;
int n = 2222;
double error_tolerance = 1.0/100;
int sketchSize = Util.ceilingIntPowerOf2((int) (1.0 /(error_tolerance*ReversePurgeLongHashMap.getLoadFactor())));
//println("sketchSize: "+sketchSize);
LongsSketch[] sketches = new LongsSketch[numSketches];
for (int h = 0; h < numSketches; h++) {
sketches[h] = new LongsSketch(sketchSize);
}
long item;
double prob = .001;
for (int i = 0; i < n; i++) {
item = randomGeometricDist(prob) + 1;
for (int h = 0; h < numSketches; h++) {
sketches[h].update(item);
}
}
for(int h=0; h<numSketches; h++) {
long threshold = sketches[h].getMaximumError();
Row[] rows = sketches[h].getFrequentItems(ErrorType.NO_FALSE_NEGATIVES);
//println("ROWS: "+rows.length);
for (int i = 0; i < rows.length; i++) {
Assert.assertTrue(rows[i].ub > threshold);
}
Row first = rows[0];
long anItem = first.getItem();
long anEst = first.getEstimate();
long aLB = first.getLowerBound();
String s = first.toString();
println(s);
assertTrue(anEst >= 0);
assertTrue(aLB >= 0);
assertEquals(anItem, anItem); //dummy test
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkGetAndCheckPreLongs() {
byte[] byteArr = new byte[8];
byteArr[0] = (byte) 2;
PreambleUtil.checkPreambleSize(Memory.wrap(byteArr));
}
@Test
public void checkToString1() {
int size = 1 << LG_MIN_MAP_SIZE;
printSketch(size, new long[] {1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5});
printSketch(size, new long[] {5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1});
}
@Test
public void checkStringDeserEmptyNotCorrupt() {
int size = 1 << LG_MIN_MAP_SIZE;
int thresh = (size * 3) / 4;
String fmt = "%6d%10s%s";
LongsSketch fls = new LongsSketch(size);
println("Sketch Size: " + size);
String s = null;
int i = 0;
for ( ; i <= thresh; i++) {
fls.update(i+1, 1);
s = fls.serializeToString();
println(String.format("SER " + fmt, (i + 1), fls.isEmpty() + " : ", s ));
LongsSketch fls2 = LongsSketch.getInstance(s);
println(String.format("DESER " + fmt, (i + 1), fls2.isEmpty() + " : ", s ));
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkStringDeserEmptyCorrupt() {
String s = "1," //serVer
+ "10," //FamID
+ "3," //lgMaxMapSz
+ "0," //Empty Flag = false ... corrupted, should be true
+ "7," //stream Len so far
+ "1," //error offset
+ "0," //numActive ...conflict with empty
+ "8,"; //curMapLen
LongsSketch.getInstance(s);
}
@Test
public void checkGetEpsilon() {
assertEquals(LongsSketch.getEpsilon(1024), 3.5 / 1024, 0.0);
try {
LongsSketch.getEpsilon(1000);
} catch (SketchesArgumentException e) { }
}
@Test
public void checkGetAprioriError() {
double eps = 3.5 / 1024;
assertEquals(LongsSketch.getAprioriError(1024, 10_000), eps * 10_000);
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
//Restricted methods
public void printSketch(int size, long[] freqArr) {
LongsSketch fls = new LongsSketch(size);
StringBuilder sb = new StringBuilder();
for (int i = 0; i<freqArr.length; i++) {
fls.update(i+1, freqArr[i]);
}
sb.append("Sketch Size: "+size).append(LS);
String s = fls.toString();
sb.append(s);
println(sb.toString());
printRows(fls, ErrorType.NO_FALSE_NEGATIVES);
println("");
printRows(fls, ErrorType.NO_FALSE_POSITIVES);
println("");
}
private static void printRows(LongsSketch fls, ErrorType eType) {
Row[] rows = fls.getFrequentItems(eType);
String s1 = eType.toString();
println(s1);
String hdr = Row.getRowHeader();
println(hdr);
for (int i=0; i<rows.length; i++) {
Row row = rows[i];
String s2 = row.toString();
println(s2);
}
if (rows.length > 0) { //check equals null case
Row nullRow = null;
assertFalse(rows[0].equals(nullRow));
}
}
/**
* @param s value to print
*/
static void println(String s) {
//System.err.println(s); //disable here
}
private static LongsSketch newFrequencySketch(double eps) {
double loadFactor = ReversePurgeLongHashMap.getLoadFactor();
int maxMapSize = Util.ceilingIntPowerOf2((int) (1.0 /(eps*loadFactor)));
return new LongsSketch(maxMapSize);
}
}
| 2,357 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/frequencies/HashMapStressTest.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.frequencies;
import org.apache.datasketches.hash.MurmurHash3;
//import org.testng.annotations.Test;
public class HashMapStressTest {
//@Test
public static void stress() {
println("ReversePurgeLongHashMap Stress Test");
printf("%12s%15s%n", "Capacity", "TimePerAdjust");
for (int capacity = 2 << 5; capacity < (2 << 24); capacity *= 2) {
int n = 10000000;
long[] keys = new long[n];
long[] values = new long[n];
for (int i = 0; i < n; i++) {
keys[i] = murmur(i);
values[i] = (i < (capacity / 2)) ? n : 1;
}
ReversePurgeLongHashMap hashmap = new ReversePurgeLongHashMap(capacity);
long timePerAdjust = timeOneHashMap(hashmap, keys, values, (int) (.75 * capacity));
printf("%12d%15d%n", capacity, timePerAdjust);
}
}
private static long timeOneHashMap(ReversePurgeLongHashMap hashMap, long[] keys, long[] values,
int sizeToShift) {
final long startTime = System.nanoTime();
int n = keys.length;
assert (n == values.length);
for (int i = 0; i < n; i++) {
hashMap.adjustOrPutValue(keys[i], values[i]);
if (hashMap.getNumActive() == sizeToShift) {
hashMap.adjustAllValuesBy(-1);
hashMap.keepOnlyPositiveCounts();
}
}
final long endTime = System.nanoTime();
return (endTime - startTime) / n;
}
private static long murmur(long key) {
long[] keyArr = { key };
return MurmurHash3.hash(keyArr, 0)[0];
}
private static void println(Object obj) { System.out.println(obj.toString()); }
private static void printf(String fmt, Object ... args) { System.out.printf(fmt, args); }
} | 2,358 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/frequencies/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.frequencies;
import static org.apache.datasketches.frequencies.PreambleUtil.FAMILY_BYTE;
import static org.apache.datasketches.frequencies.PreambleUtil.FLAGS_BYTE;
import static org.apache.datasketches.frequencies.PreambleUtil.PREAMBLE_LONGS_BYTE;
import static org.apache.datasketches.frequencies.PreambleUtil.SER_VER_BYTE;
import static org.apache.datasketches.frequencies.Util.LG_MIN_MAP_SIZE;
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;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.ArrayOfUtf16StringsSerDe;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.frequencies.ItemsSketch.Row;
public class ItemsSketchTest {
@Test
public void empty() {
ItemsSketch<String> sketch = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
Assert.assertTrue(sketch.isEmpty());
Assert.assertEquals(sketch.getNumActiveItems(), 0);
Assert.assertEquals(sketch.getStreamLength(), 0);
Assert.assertEquals(sketch.getLowerBound("a"), 0);
Assert.assertEquals(sketch.getUpperBound("a"), 0);
}
@Test
public void nullInput() {
ItemsSketch<String> sketch = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sketch.update(null);
Assert.assertTrue(sketch.isEmpty());
Assert.assertEquals(sketch.getNumActiveItems(), 0);
Assert.assertEquals(sketch.getStreamLength(), 0);
Assert.assertEquals(sketch.getLowerBound(null), 0);
Assert.assertEquals(sketch.getUpperBound(null), 0);
}
@Test
public void oneItem() {
ItemsSketch<String> sketch = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sketch.update("a");
Assert.assertFalse(sketch.isEmpty());
Assert.assertEquals(sketch.getNumActiveItems(), 1);
Assert.assertEquals(sketch.getStreamLength(), 1);
Assert.assertEquals(sketch.getEstimate("a"), 1);
Assert.assertEquals(sketch.getLowerBound("a"), 1);
}
@Test
public void severalItems() {
ItemsSketch<String> sketch = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sketch.update("a");
sketch.update("b");
sketch.update("c");
sketch.update("d");
sketch.update("b");
sketch.update("c");
sketch.update("b");
Assert.assertFalse(sketch.isEmpty());
Assert.assertEquals(sketch.getNumActiveItems(), 4);
Assert.assertEquals(sketch.getStreamLength(), 7);
Assert.assertEquals(sketch.getEstimate("a"), 1);
Assert.assertEquals(sketch.getEstimate("b"), 3);
Assert.assertEquals(sketch.getEstimate("c"), 2);
Assert.assertEquals(sketch.getEstimate("d"), 1);
ItemsSketch.Row<String>[] items = sketch.getFrequentItems(ErrorType.NO_FALSE_POSITIVES);
Assert.assertEquals(items.length, 4);
items = sketch.getFrequentItems(3, ErrorType.NO_FALSE_POSITIVES);
Assert.assertEquals(items.length, 1);
Assert.assertEquals(items[0].getItem(), "b");
sketch.reset();
Assert.assertTrue(sketch.isEmpty());
Assert.assertEquals(sketch.getNumActiveItems(), 0);
Assert.assertEquals(sketch.getStreamLength(), 0);
}
@Test
public void estimationMode() {
ItemsSketch<Integer> sketch = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sketch.update(1, 10);
sketch.update(2);
sketch.update(3);
sketch.update(4);
sketch.update(5);
sketch.update(6);
sketch.update(7, 15);
sketch.update(8);
sketch.update(9);
sketch.update(10);
sketch.update(11);
sketch.update(12);
Assert.assertFalse(sketch.isEmpty());
Assert.assertEquals(sketch.getStreamLength(), 35);
{
ItemsSketch.Row<Integer>[] items =
sketch.getFrequentItems(ErrorType.NO_FALSE_POSITIVES);
Assert.assertEquals(items.length, 2);
// only 2 items (1 and 7) should have counts more than 1
int count = 0;
for (ItemsSketch.Row<Integer> item: items) {
if (item.getLowerBound() > 1) {
count++;
}
}
Assert.assertEquals(count, 2);
}
{
ItemsSketch.Row<Integer>[] items =
sketch.getFrequentItems(ErrorType.NO_FALSE_NEGATIVES);
Assert.assertTrue(items.length >= 2);
// only 2 items (1 and 7) should have counts more than 1
int count = 0;
for (ItemsSketch.Row<Integer> item: items) {
if (item.getLowerBound() > 5) {
count++;
}
}
Assert.assertEquals(count, 2);
}
}
@Test
public void serializeStringDeserializeEmpty() {
ItemsSketch<String> sketch1 = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
byte[] bytes = sketch1.toByteArray(new ArrayOfStringsSerDe());
ItemsSketch<String> sketch2 =
ItemsSketch.getInstance(Memory.wrap(bytes), new ArrayOfStringsSerDe());
Assert.assertTrue(sketch2.isEmpty());
Assert.assertEquals(sketch2.getNumActiveItems(), 0);
Assert.assertEquals(sketch2.getStreamLength(), 0);
}
@Test
public void serializeDeserializeUft8Strings() {
ItemsSketch<String> sketch1 = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sketch1.update("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
sketch1.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
sketch1.update("ccccccccccccccccccccccccccccc");
sketch1.update("ddddddddddddddddddddddddddddd");
byte[] bytes = sketch1.toByteArray(new ArrayOfStringsSerDe());
ItemsSketch<String> sketch2 =
ItemsSketch.getInstance(Memory.wrap(bytes), new ArrayOfStringsSerDe());
sketch2.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
sketch2.update("ccccccccccccccccccccccccccccc");
sketch2.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
Assert.assertFalse(sketch2.isEmpty());
Assert.assertEquals(sketch2.getNumActiveItems(), 4);
Assert.assertEquals(sketch2.getStreamLength(), 7);
Assert.assertEquals(sketch2.getEstimate("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), 1);
Assert.assertEquals(sketch2.getEstimate("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), 3);
Assert.assertEquals(sketch2.getEstimate("ccccccccccccccccccccccccccccc"), 2);
Assert.assertEquals(sketch2.getEstimate("ddddddddddddddddddddddddddddd"), 1);
}
@Test
public void serializeDeserializeUtf16Strings() {
ItemsSketch<String> sketch1 = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sketch1.update("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
sketch1.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
sketch1.update("ccccccccccccccccccccccccccccc");
sketch1.update("ddddddddddddddddddddddddddddd");
byte[] bytes = sketch1.toByteArray(new ArrayOfUtf16StringsSerDe());
ItemsSketch<String> sketch2 =
ItemsSketch.getInstance(Memory.wrap(bytes), new ArrayOfUtf16StringsSerDe());
sketch2.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
sketch2.update("ccccccccccccccccccccccccccccc");
sketch2.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
Assert.assertFalse(sketch2.isEmpty());
Assert.assertEquals(sketch2.getNumActiveItems(), 4);
Assert.assertEquals(sketch2.getStreamLength(), 7);
Assert.assertEquals(sketch2.getEstimate("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), 1);
Assert.assertEquals(sketch2.getEstimate("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), 3);
Assert.assertEquals(sketch2.getEstimate("ccccccccccccccccccccccccccccc"), 2);
Assert.assertEquals(sketch2.getEstimate("ddddddddddddddddddddddddddddd"), 1);
}
@Test
public void forceResize() {
ItemsSketch<String> sketch1 = new ItemsSketch<>(2 << LG_MIN_MAP_SIZE);
for (int i=0; i<32; i++) {
sketch1.update(Integer.toString(i), i*i);
}
}
@Test
public void getRowHeader() {
String header = ItemsSketch.Row.getRowHeader();
Assert.assertNotNull(header);
Assert.assertTrue(header.length() > 0);
}
@Test
public void serializeLongDeserialize() {
ItemsSketch<Long> sketch1 = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sketch1.update(1L);
sketch1.update(2L);
sketch1.update(3L);
sketch1.update(4L);
String s = sketch1.toString();
println(s);
byte[] bytes = sketch1.toByteArray(new ArrayOfLongsSerDe());
ItemsSketch<Long> sketch2 =
ItemsSketch.getInstance(Memory.wrap(bytes), new ArrayOfLongsSerDe());
sketch2.update(2L);
sketch2.update(3L);
sketch2.update(2L);
Assert.assertFalse(sketch2.isEmpty());
Assert.assertEquals(sketch2.getNumActiveItems(), 4);
Assert.assertEquals(sketch2.getStreamLength(), 7);
Assert.assertEquals(sketch2.getEstimate(1L), 1);
Assert.assertEquals(sketch2.getEstimate(2L), 3);
Assert.assertEquals(sketch2.getEstimate(3L), 2);
Assert.assertEquals(sketch2.getEstimate(4L), 1);
}
@Test
public void mergeExact() {
ItemsSketch<String> sketch1 = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sketch1.update("a");
sketch1.update("b");
sketch1.update("c");
sketch1.update("d");
ItemsSketch<String> sketch2 = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sketch2.update("b");
sketch2.update("c");
sketch2.update("b");
sketch1.merge(sketch2);
Assert.assertFalse(sketch1.isEmpty());
Assert.assertEquals(sketch1.getNumActiveItems(), 4);
Assert.assertEquals(sketch1.getStreamLength(), 7);
Assert.assertEquals(sketch1.getEstimate("a"), 1);
Assert.assertEquals(sketch1.getEstimate("b"), 3);
Assert.assertEquals(sketch1.getEstimate("c"), 2);
Assert.assertEquals(sketch1.getEstimate("d"), 1);
}
@Test
public void checkNullMapReturns() {
ReversePurgeItemHashMap<Long> map = new ReversePurgeItemHashMap<>(1 << LG_MIN_MAP_SIZE);
Assert.assertNull(map.getActiveKeys());
Assert.assertNull(map.getActiveValues());
}
@SuppressWarnings("unlikely-arg-type")
@Test
public void checkMisc() {
ItemsSketch<Long> sk1 = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
Assert.assertEquals(sk1.getCurrentMapCapacity(), 6);
Assert.assertEquals(sk1.getEstimate(Long.valueOf(1)), 0);
ItemsSketch<Long> sk2 = new ItemsSketch<>(8);
Assert.assertEquals(sk1.merge(sk2), sk1 );
Assert.assertEquals(sk1.merge(null), sk1);
sk1.update(Long.valueOf(1));
ItemsSketch.Row<Long>[] rows = sk1.getFrequentItems(ErrorType.NO_FALSE_NEGATIVES);
ItemsSketch.Row<Long> row = rows[0];
Assert.assertTrue(row.hashCode() != 0);
Assert.assertTrue(row.equals(row));
Assert.assertFalse(row.equals(sk1));
Assert.assertEquals((long)row.getItem(), 1L);
Assert.assertEquals(row.getEstimate(), 1);
Assert.assertEquals(row.getUpperBound(), 1);
String s = row.toString();
println(s);
ItemsSketch.Row<Long> nullRow = null; //check equals(null)
Assert.assertFalse(row.equals(nullRow));
}
@Test
public void checkToString() {
ItemsSketch<Long> sk = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sk.update(Long.valueOf(1));
println(ItemsSketch.toString(sk.toByteArray(new ArrayOfLongsSerDe())));
}
@Test
public void checkGetFrequentItems1() {
ItemsSketch<Long> fis = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
fis.update(1L);
Row<Long>[] rowArr = fis.getFrequentItems(ErrorType.NO_FALSE_POSITIVES);
Row<Long> row = rowArr[0];
assertNotNull(row);
assertEquals(row.est, 1L);
assertEquals(row.item, Long.valueOf(1L));
assertEquals(row.lb, 1L);
assertEquals(row.ub, 1L);
Row<Long> newRow = new Row<>(row.item, row.est+1, row.ub, row.lb);
assertFalse(row.equals(newRow));
newRow = new Row<>(row.item, row.est, row.ub, row.lb);
assertTrue(row.equals(newRow));
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkUpdateException() {
ItemsSketch<Long> sk1 = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sk1.update(Long.valueOf(1), -1);
}
@Test
public void checkMemExceptions() {
ItemsSketch<Long> sk1 = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sk1.update(Long.valueOf(1), 1);
ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
byte[] byteArr = sk1.toByteArray(serDe);
WritableMemory mem = WritableMemory.writableWrap(byteArr);
//FrequentItemsSketch<Long> sk2 = FrequentItemsSketch.getInstance(mem, serDe);
//println(sk2.toString());
long pre0 = mem.getLong(0); //The correct first 8 bytes.
//Now start corrupting
tryBadMem(mem, PREAMBLE_LONGS_BYTE, 2); //Corrupt
mem.putLong(0, pre0); //restore
tryBadMem(mem, SER_VER_BYTE, 2); //Corrupt
mem.putLong(0, pre0); //restore
tryBadMem(mem, FAMILY_BYTE, 2); //Corrupt
mem.putLong(0, pre0); //restore
tryBadMem(mem, FLAGS_BYTE, 4); //Corrupt to true
mem.putLong(0, pre0); //restore
}
@Test
public void oneItemUtf8() {
ItemsSketch<String> sketch1 = new ItemsSketch<>(1 << LG_MIN_MAP_SIZE);
sketch1.update("\u5fb5");
Assert.assertFalse(sketch1.isEmpty());
Assert.assertEquals(sketch1.getNumActiveItems(), 1);
Assert.assertEquals(sketch1.getStreamLength(), 1);
Assert.assertEquals(sketch1.getEstimate("\u5fb5"), 1);
byte[] bytes = sketch1.toByteArray(new ArrayOfStringsSerDe());
ItemsSketch<String> sketch2 =
ItemsSketch.getInstance(Memory.wrap(bytes), new ArrayOfStringsSerDe());
Assert.assertFalse(sketch2.isEmpty());
Assert.assertEquals(sketch2.getNumActiveItems(), 1);
Assert.assertEquals(sketch2.getStreamLength(), 1);
Assert.assertEquals(sketch2.getEstimate("\u5fb5"), 1);
}
@Test
public void checkGetEpsilon() {
assertEquals(ItemsSketch.getEpsilon(1024), 3.5 / 1024, 0.0);
try {
ItemsSketch.getEpsilon(1000);
} catch (SketchesArgumentException e) { }
}
@Test
public void checkGetAprioriError() {
double eps = 3.5 / 1024;
assertEquals(ItemsSketch.getAprioriError(1024, 10_000), eps * 10_000);
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
//Restricted methods
private static void tryBadMem(WritableMemory mem, int byteOffset, int byteValue) {
ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
try {
mem.putByte(byteOffset, (byte) byteValue); //Corrupt
ItemsSketch.getInstance(mem, serDe);
fail();
} catch (SketchesArgumentException e) {
//expected
}
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| 2,359 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/frequencies/DistTest.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.frequencies;
import org.testng.Assert;
//import org.testng.annotations.Test;
public class DistTest {
/**
* @param prob the probability of success for the geometric distribution.
* @return a random number generated from the geometric distribution.
*/
public static long randomGeometricDist(double prob) {
assert ((prob > 0.0) && (prob < 1.0));
return 1 + (long) (Math.log(Math.random()) / Math.log(1.0 - prob));
}
public static double zeta(long n, double theta) {
// the zeta function, used by the below zipf function
// (this is not often called from outside this library)
// ... but have made it public now to speed things up
long i;
double ans = 0.0;
for (i = 1; i <= n; i++) {
ans += Math.pow(1.0 / i, theta);
}
return (ans);
}
// This draws values from the zipf distribution
// n is range, theta is skewness parameter
// theta = 0 gives uniform distribution,
// theta > 1 gives highly skewed distribution.
public static long zipf(double theta, long n, double zetan) {
double alpha;
double eta;
double u;
double uz;
double val;
// randinit must be called before entering this procedure for
// the first time since it uses the random generators
alpha = 1. / (1. - theta);
eta = (1. - Math.pow(2. / n, 1. - theta)) / (1. - (zeta(2, theta) / zetan));
u = 0.0;
while (u == 0.0) {
u = Math.random();
}
uz = u * zetan;
if (uz < 1.) {
val = 1;
} else if (uz < (1. + Math.pow(0.5, theta))) {
val = 2;
} else {
val = 1 + (n * Math.pow(((eta * u) - eta) + 1., alpha));
}
return (long) val;
}
//@Test
public static void testRandomGeometricDist() {
long maxItem = 0L;
double prob = .1;
for (int i = 0; i < 100; i++) {
long item = randomGeometricDist(prob);
if (item > maxItem) {
maxItem = item;
}
// If you succeed with probability p the probability
// of failing 20/p times is smaller than 1/2^20.
Assert.assertTrue(maxItem < (20.0 / prob));
}
}
}
| 2,360 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/frequencies/ReversePurgeLongHashMapTest.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.frequencies;
import static org.testng.Assert.assertNull;
import org.apache.datasketches.common.SketchesArgumentException;
import org.testng.annotations.Test;
public class ReversePurgeLongHashMapTest {
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkgetInstanceString() {
ReversePurgeLongHashMap.getInstance("");
}
@Test
public void checkActiveNull() {
ReversePurgeLongHashMap map = new ReversePurgeLongHashMap(4);
assertNull(map.getActiveKeys());
assertNull(map.getActiveValues());
}
}
| 2,361 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/frequencies/FrequentItemsSketchCrossLanguageTest.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.frequencies;
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.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 FrequentItemsSketchCrossLanguageTest {
@Test(groups = {GENERATE_JAVA_FILES})
public void generateBinariesForCompatibilityTestingLongsSketch() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000};
for (int n: nArr) {
LongsSketch sk = new LongsSketch(64);
for (int i = 1; i <= n; i++) sk.update(i);
assertTrue(n == 0 ? sk.isEmpty() : !sk.isEmpty());
if (n > 10) { assertTrue(sk.getMaximumError() > 0); }
else { assertEquals(sk.getMaximumError(), 0); }
Files.newOutputStream(javaPath.resolve("frequent_long_n" + n + "_java.sk")).write(sk.toByteArray());
}
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateBinariesForCompatibilityTestingStringsSketch() 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 = new ItemsSketch<>(64);
for (int i = 1; i <= n; i++) sk.update(Integer.toString(i));
assertTrue(n == 0 ? sk.isEmpty() : !sk.isEmpty());
if (n > 10) { assertTrue(sk.getMaximumError() > 0); }
else { assertEquals(sk.getMaximumError(), 0); }
Files.newOutputStream(javaPath.resolve("frequent_string_n" + n + "_java.sk"))
.write(sk.toByteArray(new ArrayOfStringsSerDe()));
}
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateBinariesForCompatibilityTestingStringsSketchAscii() throws IOException {
final ItemsSketch<String> sk = new ItemsSketch<>(64);
sk.update("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 1);
sk.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 2);
sk.update("ccccccccccccccccccccccccccccc", 3);
sk.update("ddddddddddddddddddddddddddddd", 4);
Files.newOutputStream(javaPath.resolve("frequent_string_ascii_java.sk"))
.write(sk.toByteArray(new ArrayOfStringsSerDe()));
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateBinariesForCompatibilityTestingStringsSketchUtf8() throws IOException {
final ItemsSketch<String> sk = new ItemsSketch<>(64);
sk.update("абвгд", 1);
sk.update("еёжзи", 2);
sk.update("йклмн", 3);
sk.update("опрст", 4);
sk.update("уфхцч", 5);
sk.update("шщъыь", 6);
sk.update("эюя", 7);
Files.newOutputStream(javaPath.resolve("frequent_string_utf8_java.sk"))
.write(sk.toByteArray(new ArrayOfStringsSerDe()));
}
@Test(groups = {CHECK_CPP_FILES})
public void longs() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("frequent_long_n" + n + "_cpp.sk"));
final LongsSketch sketch = LongsSketch.getInstance(Memory.wrap(bytes));
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
if (n > 10) {
assertTrue(sketch.getMaximumError() > 0);
} else {
assertEquals(sketch.getMaximumError(), 0);
}
assertEquals(sketch.getStreamLength(), n);
}
}
@Test(groups = {CHECK_CPP_FILES})
public void strings() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("frequent_string_n" + n + "_cpp.sk"));
final ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes), new ArrayOfStringsSerDe());
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
if (n > 10) {
assertTrue(sketch.getMaximumError() > 0);
} else {
assertEquals(sketch.getMaximumError(), 0);
}
assertEquals(sketch.getStreamLength(), n);
}
}
@Test(groups = {CHECK_CPP_FILES})
public void stringsAscii() throws IOException {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("frequent_string_ascii_cpp.sk"));
final ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes), new ArrayOfStringsSerDe());
assertFalse(sketch.isEmpty());
assertEquals(sketch.getMaximumError(), 0);
assertEquals(sketch.getStreamLength(), 10);
assertEquals(sketch.getEstimate("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), 1);
assertEquals(sketch.getEstimate("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), 2);
assertEquals(sketch.getEstimate("ccccccccccccccccccccccccccccc"), 3);
assertEquals(sketch.getEstimate("ddddddddddddddddddddddddddddd"), 4);
}
@Test(groups = {CHECK_CPP_FILES})
public void stringsUtf8() throws IOException {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("frequent_string_utf8_cpp.sk"));
final ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes), new ArrayOfStringsSerDe());
assertFalse(sketch.isEmpty());
assertEquals(sketch.getMaximumError(), 0);
assertEquals(sketch.getStreamLength(), 28);
assertEquals(sketch.getEstimate("абвгд"), 1);
assertEquals(sketch.getEstimate("еёжзи"), 2);
assertEquals(sketch.getEstimate("йклмн"), 3);
assertEquals(sketch.getEstimate("опрст"), 4);
assertEquals(sketch.getEstimate("уфхцч"), 5);
assertEquals(sketch.getEstimate("шщъыь"), 6);
assertEquals(sketch.getEstimate("эюя"), 7);
}
}
| 2,362 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/frequencies/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.frequencies;
import org.apache.datasketches.common.ArrayOfItemsSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SerDeCompatibilityTest {
static final ArrayOfItemsSerDe<Long> serDe = new ArrayOfLongsSerDe();
@Test
public void itemsToLongs() {
final ItemsSketch<Long> sketch1 = new ItemsSketch<>(8);
sketch1.update(1L);
sketch1.update(2L);
sketch1.update(3L);
sketch1.update(4L);
final byte[] bytes = sketch1.toByteArray(serDe);
final LongsSketch sketch2 = LongsSketch.getInstance(WritableMemory.writableWrap(bytes));
sketch2.update(2L);
sketch2.update(3L);
sketch2.update(2L);
Assert.assertFalse(sketch2.isEmpty());
Assert.assertEquals(sketch2.getNumActiveItems(), 4);
Assert.assertEquals(sketch2.getStreamLength(), 7);
Assert.assertEquals(sketch2.getEstimate(1L), 1);
Assert.assertEquals(sketch2.getEstimate(2L), 3);
Assert.assertEquals(sketch2.getEstimate(3L), 2);
Assert.assertEquals(sketch2.getEstimate(4L), 1);
}
@Test
public void longsToItems() {
final LongsSketch sketch1 = new LongsSketch(8);
sketch1.update(1L);
sketch1.update(2L);
sketch1.update(3L);
sketch1.update(4L);
final byte[] bytes = sketch1.toByteArray();
final ItemsSketch<Long> sketch2 = ItemsSketch.getInstance(WritableMemory.writableWrap(bytes), serDe);
sketch2.update(2L);
sketch2.update(3L);
sketch2.update(2L);
Assert.assertFalse(sketch2.isEmpty());
Assert.assertEquals(sketch2.getNumActiveItems(), 4);
Assert.assertEquals(sketch2.getStreamLength(), 7);
Assert.assertEquals(sketch2.getEstimate(1L), 1);
Assert.assertEquals(sketch2.getEstimate(2L), 3);
Assert.assertEquals(sketch2.getEstimate(3L), 2);
Assert.assertEquals(sketch2.getEstimate(4L), 1);
}
}
| 2,363 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/fdt/GroupTest.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.fdt;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class GroupTest {
private static final String LS = System.getProperty("line.separator");
@Test
public void checkToString() { //check visually
Group gp = new Group();
gp.init("AAAAAAAA,BBBBBBBBBB", 100_000_000, 1E8, 1.2E8, 8E7, 0.1, 0.01);
assertEquals(gp.getPrimaryKey(), "AAAAAAAA,BBBBBBBBBB");
assertEquals(gp.getCount(), 100_000_000);
assertEquals(gp.getEstimate(), 1E8);
assertEquals(gp.getUpperBound(), 1.2E8);
assertEquals(gp.getLowerBound(), 8E7);
assertEquals(gp.getFraction(), 0.1);
assertEquals(gp.getRse(), 0.01);
println(gp.getHeader());
println(gp.toString());
}
@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.out.print(s); //disable here
}
}
| 2,364 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/fdt/FdtSketchTest.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.fdt;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.List;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.tuple.TupleSketchIterator;
import org.apache.datasketches.tuple.strings.ArrayOfStringsSummary;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class FdtSketchTest {
private static final String LS = System.getProperty("line.separator");
private static final char sep = '|'; //string separator
@SuppressWarnings("deprecation")
@Test
public void checkFdtSketch() {
final int lgK = 14;
final FdtSketch sketch = new FdtSketch(lgK);
final String[] nodesArr = {"abc", "def" };
sketch.update(nodesArr);
final TupleSketchIterator<ArrayOfStringsSummary> it = sketch.iterator();
int count = 0;
while (it.next()) {
final String[] nodesArr2 = it.getSummary().getValue();
assertEquals(nodesArr2, nodesArr);
count++;
}
assertEquals(count, 1);
//serialize
final byte[] byteArr = sketch.toByteArray();
//deserialize
Memory mem = Memory.wrap(byteArr);
FdtSketch sketch2 = new FdtSketch(mem);
//check output
final TupleSketchIterator<ArrayOfStringsSummary> it2 = sketch2.iterator();
int count2 = 0;
while (it2.next()) {
final String[] nodesArr2 = it2.getSummary().getValue();
assertEquals(nodesArr2, nodesArr);
count2++;
}
assertEquals(count, count2);
assertEquals(sketch2.getEstimate(), sketch.getEstimate());
assertEquals(sketch2.getLowerBound(2), sketch.getLowerBound(2));
assertEquals(sketch2.getUpperBound(2), sketch.getUpperBound(2));
}
@Test
public void checkAlternateLgK() {
int lgK = FdtSketch.computeLgK(.01, .01);
assertEquals(lgK, 20);
lgK = FdtSketch.computeLgK(.02, .05);
assertEquals(lgK, 15);
try {
lgK = FdtSketch.computeLgK(.01, .001);
fail();
} catch (SketchesArgumentException e) {
//ok
}
}
@Test
public void checkFdtSketchWithThreshold() {
FdtSketch sk = new FdtSketch(.02, .05); //thresh, RSE
assertEquals(sk.getLgK(), 15);
println("LgK: " + sk.getLgK());
}
@Test
public void simpleCheckPostProcessing() {
FdtSketch sk = new FdtSketch(8);
int[] priKeyIndices = {0,2};
String[] arr1 = {"a", "1", "c"};
String[] arr2 = {"a", "2", "c"};
String[] arr3 = {"a", "3", "c"};
String[] arr4 = {"a", "4", "c"};
String[] arr5 = {"a", "1", "d"};
String[] arr6 = {"a", "2", "d"};
sk.update(arr1);
sk.update(arr2);
sk.update(arr3);
sk.update(arr4);
sk.update(arr5);
sk.update(arr6);
//get results from PostProcessor directly
Group gp = new Group(); //uninitialized
PostProcessor post = new PostProcessor(sk, gp, sep);
post = sk.getPostProcessor(gp, sep);
post = sk.getPostProcessor(); //equivalent
List<Group> list = post.getGroupList(priKeyIndices, 2, 0);
assertEquals(list.size(), 2);
assertEquals(post.getGroupCount(), 2);
println(gp.getHeader());
for (int i = 0; i < list.size(); i++) {
println(list.get(i).toString());
}
list = post.getGroupList(priKeyIndices, 2, 1);
assertEquals(list.size(), 1);
//get results from sketch directly
list = sk.getResult(priKeyIndices, 0, 2, sep);
assertEquals(list.size(), 2);
}
@Test
public void checkEstimatingPostProcessing() {
FdtSketch sk = new FdtSketch(4);
int[] priKeyIndices = {0};
for (int i = 0; i < 32; i++) {
String[] arr = {"a", Integer.toHexString(i)};
sk.update(arr);
}
assertTrue(sk.isEstimationMode());
List<Group> list = sk.getResult(priKeyIndices, 0, 2, sep);
assertEquals(list.size(), 1);
println(new Group().getHeader());
for (int i = 0; i < list.size(); i++) {
println(list.get(i).toString());
}
}
@Test
public void checkCopyCtor() {
final int lgK = 14;
final FdtSketch sk = new FdtSketch(lgK);
final String[] nodesArr = {"abc", "def" };
sk.update(nodesArr);
assertEquals(sk.getRetainedEntries(), 1);
final FdtSketch sk2 = sk.copy();
assertEquals(sk2.getRetainedEntries(), 1);
}
@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.out.print(s); //disable here
}
}
| 2,365 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDirectCompactDoublesSketchTest.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.kll;
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.kll.KllDirectDoublesSketch.KllDirectCompactDoublesSketch;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
public class KllDirectCompactDoublesSketchTest {
private static final DefaultMemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void checkRODirectUpdatable_ROandWritable() {
int k = 20;
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
byte[] byteArr = KllHelper.toByteArray(sk, true); //request updatable
Memory srcMem = Memory.wrap(byteArr); //cast to Memory -> read only
KllDoublesSketch sk2 = KllDoublesSketch.wrap(srcMem);
assertTrue(sk2 instanceof KllDirectDoublesSketch);
assertTrue(sk2.isMemoryUpdatableFormat());
assertTrue(sk2.isReadOnly());
assertEquals(sk2.getMinItem(), 1.0);
assertEquals(sk2.getMaxItem(), 21.0);
WritableMemory srcWmem = WritableMemory.writableWrap(byteArr);
KllDoublesSketch sk3 = KllDoublesSketch.writableWrap(srcWmem, memReqSvr);
assertTrue(sk3 instanceof KllDirectDoublesSketch);
println(sk3.toString(true, false));
assertFalse(sk3.isReadOnly());
sk3.update(22.0);
assertEquals(sk3.getMinItem(), 1.0);
assertEquals(sk3.getMaxItem(), 22.0);
}
@Test
public void checkRODirectCompact() {
int k = 20;
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
Memory srcMem = Memory.wrap(sk.toByteArray()); //compact RO fmt
KllDoublesSketch sk2 = KllDoublesSketch.wrap(srcMem);
assertTrue(sk2 instanceof KllDirectCompactDoublesSketch);
//println(sk2.toString(true, false));
assertFalse(sk2.isMemoryUpdatableFormat());
assertTrue(sk2.isReadOnly());
assertEquals(sk2.getMinItem(), 1.0);
assertEquals(sk2.getMaxItem(), 21.0);
Memory srcMem2 = Memory.wrap(sk2.toByteArray());
KllDoublesSketch sk3 = KllDoublesSketch.writableWrap((WritableMemory)srcMem2, memReqSvr);
assertTrue(sk3 instanceof KllDirectCompactDoublesSketch);
assertFalse(sk2.isMemoryUpdatableFormat());
//println(sk3.toString(true, false));
assertTrue(sk3.isReadOnly());
assertEquals(sk3.getMinItem(), 1.0);
assertEquals(sk3.getMaxItem(), 21.0);
}
@Test
public void checkDirectCompactSingleItem() {
int k = 20;
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k);
sk.update(1);
KllDoublesSketch sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
assertTrue(sk2 instanceof KllDirectCompactDoublesSketch);
//println(sk2.toString(true, false));
assertTrue(sk2.isReadOnly());
assertEquals(sk2.getDoubleSingleItem(), 1.0);
sk.update(2);
sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
assertEquals(sk2.getN(), 2);
try {
sk2.getDoubleSingleItem();
fail();
} catch (SketchesArgumentException e) { }
}
@Test
public void checkDirectCompactGetDoubleItemsArray() {
int k = 20;
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k);
KllDoublesSketch sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
double[] itemsArr = sk2.getDoubleItemsArray();
for (int i = 0; i < 20; i++) { assertEquals(itemsArr[i], 0F); }
sk.update(1);
sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
itemsArr = sk2.getDoubleItemsArray();
for (int i = 0; i < 19; i++) { assertEquals(itemsArr[i], 0F); }
assertEquals(itemsArr[19], 1F);
for (int i = 2; i <= 21; i++) { sk.update(i); }
sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
itemsArr = sk2.getDoubleItemsArray();
assertEquals(itemsArr.length, 33);
assertEquals(itemsArr[22], 21);
}
@Test
public void checkHeapAndDirectCompactGetRetainedItemsArray() {
int k = 20;
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k);
double[] retArr = sk.getDoubleRetainedItemsArray();
assertEquals(retArr.length, 0);
KllDoublesSketch sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
retArr = sk2.getDoubleRetainedItemsArray();
assertEquals(retArr.length, sk.getNumRetained());
assertEquals(retArr.length, 0);
sk.update(1.0);
retArr = sk.getDoubleRetainedItemsArray();
assertEquals(retArr.length, sk.getNumRetained());
assertEquals(retArr.length, 1);
assertEquals(retArr[0], 1.0);
sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
retArr = sk2.getDoubleRetainedItemsArray();
assertEquals(retArr.length, sk.getNumRetained());
assertEquals(retArr.length, 1);
assertEquals(retArr[0], 1.0);
for (int i = 2; i <= 21; i++) { sk.update(i); }
retArr = sk.getDoubleRetainedItemsArray();
assertEquals(retArr.length, sk.getNumRetained());
assertEquals(retArr.length, 11);
sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
assertEquals(retArr.length, sk2.getNumRetained());
assertEquals(retArr.length, 11);
}
@Test
public void checkMinAndMax() {
int k = 20;
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k);
KllDoublesSketch sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
try { sk2.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sk2.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
sk.update(1);
sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
assertEquals(sk2.getMaxItem(),1.0F);
assertEquals(sk2.getMinItem(),1.0F);
for (int i = 2; i <= 21; i++) { sk.update(i); }
sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
assertEquals(sk2.getMaxItem(),21.0F);
assertEquals(sk2.getMinItem(),1.0F);
}
@Test
public void checkQuantile() {
KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance();
for (int i = 1; i <= 1000; i++) { sk1.update(i); }
KllDoublesSketch sk2 = KllDoublesSketch.wrap(Memory.wrap(sk1.toByteArray()));
double med2 = sk2.getQuantile(0.5);
double med1 = sk1.getQuantile(0.5);
assertEquals(med1, med2);
println("Med1: " + med1);
println("Med2: " + med2);
}
@Test
public void checkCompactSingleItemMerge() {
int k = 20;
KllDoublesSketch skH1 = KllDoublesSketch.newHeapInstance(k); //Heap with 1 (single)
skH1.update(21);
KllDoublesSketch skDC1 = KllDoublesSketch.wrap(Memory.wrap(skH1.toByteArray())); //Direct Compact with 1 (single)
KllDoublesSketch skH20 = KllDoublesSketch.newHeapInstance(k); //Heap with 20
for (int i = 1; i <= 20; i++) { skH20.update(i); }
skH20.merge(skDC1);
assertEquals(skH20.getN(), 21);
WritableMemory wmem = WritableMemory.allocate(1000);
KllDoublesSketch skDU20 = KllDoublesSketch.newDirectInstance(k, wmem, memReqSvr);//Direct Updatable with 21
for (int i = 1; i <= 20; i++) { skDU20.update(i); }
skDU20.merge(skDC1);
assertEquals(skDU20.getN(), 21);
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
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,366 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDoublesSketchIteratorTest.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.kll;
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.DoublesSortedViewIterator;
import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIterator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class KllDoublesSketchIteratorTest {
@Test
public void emptySketch() {
KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
QuantilesDoublesSketchIterator it = sketch.iterator();
Assert.assertFalse(it.next());
}
@Test
public void oneItemSketch() {
KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
sketch.update(1);
QuantilesDoublesSketchIterator it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getQuantile(), 1.0);
Assert.assertEquals(it.getWeight(), 1);
Assert.assertFalse(it.next());
}
@Test
public void twoItemSketchForIterator() {
KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
sketch.update(1);
sketch.update(2);
QuantilesDoublesSketchIterator itr = sketch.iterator();
assertTrue(itr.next());
assertEquals(itr.getQuantile(), 2.0);
assertEquals(itr.getWeight(), 1);
assertTrue(itr.next());
assertEquals(itr.getQuantile(), 1.0);
assertEquals(itr.getWeight(), 1);
}
@Test
public void twoItemSketchForSortedViewIterator() {
KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
sketch.update(1);
sketch.update(2);
DoublesSortedViewIterator itr = sketch.getSortedView().iterator();
assertTrue(itr.next());
assertEquals(itr.getQuantile(), 1.0);
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(), 2.0);
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
public void bigSketches() {
for (int n = 1000; n < 100000; n += 2000) {
KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
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,367 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllFloatsValidationTest.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.kll;
import static org.apache.datasketches.common.Util.isOdd;
import org.testng.Assert;
import org.testng.annotations.Test;
/* A test record contains:
0. testIndex
1. K
2. N
3. stride (for generating the input)
4. numLevels
5. numSamples
6. hash of the retained samples
*/
// These results are for the version that delays the roll up until the next value comes in.
// The @Test annotations have to be enabled to use this class and a section in KllFloatsHelper also
// needs to be enabled.
@SuppressWarnings("unused")
public class KllFloatsValidationTest {
//Used only with manual running of checkTestResults(..)
private static final long[] correctResultsWithReset = {
0, 200, 180, 3246533, 1, 180, 1098352976109474698L,
1, 200, 198, 8349603, 1, 198, 686681527497651888L,
2, 200, 217, 676491, 2, 117, 495856134049157644L,
3, 200, 238, 3204507, 2, 138, 44453438498725402L,
4, 200, 261, 2459373, 2, 161, 719830627391926938L,
5, 200, 287, 5902143, 2, 187, 389303173170515580L,
6, 200, 315, 5188793, 2, 215, 985218890825795000L,
7, 200, 346, 801923, 2, 246, 589362992166904413L,
8, 200, 380, 2466269, 2, 280, 1081848693781775853L,
9, 200, 418, 5968041, 2, 318, 533825689515788397L,
10, 200, 459, 3230027, 2, 243, 937332670315558786L,
11, 200, 504, 5125875, 2, 288, 1019197831515566845L,
12, 200, 554, 4195571, 3, 230, 797351479150148224L,
13, 200, 609, 2221181, 3, 285, 451246040374318529L,
14, 200, 669, 5865503, 3, 345, 253851269470815909L,
15, 200, 735, 831703, 3, 411, 491974970526372303L,
16, 200, 808, 4830785, 3, 327, 1032107507126916277L,
17, 200, 888, 1356257, 3, 407, 215225420986342944L,
18, 200, 976, 952071, 3, 417, 600280049738270697L,
19, 200, 1073, 6729833, 3, 397, 341758522977365969L,
20, 200, 1180, 6017925, 3, 406, 1080227312339182949L,
21, 200, 1298, 4229891, 3, 401, 1092460534756675086L,
22, 200, 1427, 7264889, 4, 320, 884533400696890024L,
23, 200, 1569, 5836327, 4, 462, 660575800011134382L,
24, 200, 1725, 5950087, 4, 416, 669373957401387528L,
25, 200, 1897, 2692555, 4, 406, 607308667566496888L,
26, 200, 2086, 1512443, 4, 459, 744260340112029032L,
27, 200, 2294, 2681171, 4, 434, 199120609113802485L,
28, 200, 2523, 3726521, 4, 450, 570993497599288304L,
29, 200, 2775, 2695247, 4, 442, 306717093329516310L,
30, 200, 3052, 5751175, 5, 400, 256024589545754217L,
31, 200, 3357, 1148897, 5, 514, 507276662329207479L,
32, 200, 3692, 484127, 5, 457, 1082660223488175122L,
33, 200, 4061, 6414559, 5, 451, 620820308918522117L,
34, 200, 4467, 5587461, 5, 466, 121975084804459305L,
35, 200, 4913, 1615017, 5, 483, 152986529342916376L,
36, 200, 5404, 6508535, 5, 492, 858526451332425960L,
37, 200, 5944, 2991657, 5, 492, 624906434274621995L,
38, 200, 6538, 6736565, 6, 511, 589153542019036049L,
39, 200, 7191, 1579893, 6, 507, 10255312374117907L,
40, 200, 7910, 412509, 6, 538, 570863587164194186L,
41, 200, 8701, 1112089, 6, 477, 553100668286355347L,
42, 200, 9571, 1258813, 6, 526, 344845406406036297L,
43, 200, 10528, 1980049, 6, 508, 411846569527905064L,
44, 200, 11580, 2167127, 6, 520, 966876726203675488L,
45, 200, 12738, 1975435, 7, 561, 724125506920592732L,
46, 200, 14011, 4289627, 7, 560, 753686005174215572L,
47, 200, 15412, 5384001, 7, 494, 551637841878573955L,
48, 200, 16953, 2902685, 7, 560, 94602851752354802L,
49, 200, 18648, 4806445, 7, 562, 597672400688514221L,
50, 200, 20512, 2085, 7, 529, 417280161591969960L,
51, 200, 22563, 6375939, 7, 558, 11300453985206678L,
52, 200, 24819, 7837057, 7, 559, 283668599967437754L,
53, 200, 27300, 6607975, 8, 561, 122183647493325363L,
54, 200, 30030, 1519191, 8, 550, 1145227891427321202L,
55, 200, 33033, 808061, 8, 568, 71070843834364939L,
56, 200, 36336, 2653529, 8, 570, 450311772805359006L,
57, 200, 39969, 2188957, 8, 561, 269670427054904115L,
58, 200, 43965, 5885655, 8, 539, 1039064186324091890L,
59, 200, 48361, 6185889, 8, 574, 178055275082387938L,
60, 200, 53197, 208767, 9, 579, 139766040442973048L,
61, 200, 58516, 2551345, 9, 569, 322655279254252950L,
62, 200, 64367, 1950873, 9, 569, 101542216315768285L,
63, 200, 70803, 2950429, 9, 582, 72294008568551853L,
64, 200, 77883, 3993977, 9, 572, 299014330559512530L,
65, 200, 85671, 428871, 9, 585, 491351721800568188L,
66, 200, 94238, 6740849, 9, 577, 656204268858348899L,
67, 200, 103661, 2315497, 9, 562, 829926273188300764L,
68, 200, 114027, 5212835, 10, 581, 542222554617639557L,
69, 200, 125429, 4213475, 10, 593, 713339189579860773L,
70, 200, 137971, 2411583, 10, 592, 649651658985845357L,
71, 200, 151768, 5243307, 10, 567, 1017459402785275179L,
72, 200, 166944, 2468367, 10, 593, 115034451827634398L,
73, 200, 183638, 2210923, 10, 583, 365735165000548572L,
74, 200, 202001, 321257, 10, 591, 928479940794929153L,
75, 200, 222201, 8185105, 11, 600, 780163958693677795L,
76, 200, 244421, 6205349, 11, 598, 132454307780236135L,
77, 200, 268863, 3165901, 11, 600, 369824066179493948L,
78, 200, 295749, 2831723, 11, 595, 80968411797441666L,
79, 200, 325323, 464193, 11, 594, 125773061716381917L,
80, 200, 357855, 7499035, 11, 576, 994150328579932916L,
81, 200, 393640, 1514479, 11, 596, 111092193875842594L,
82, 200, 433004, 668493, 12, 607, 497338041653302784L,
83, 200, 476304, 3174931, 12, 606, 845986926165673887L,
84, 200, 523934, 914611, 12, 605, 354993119685278556L,
85, 200, 576327, 7270385, 12, 602, 937679531753465428L,
86, 200, 633959, 1956979, 12, 598, 659413123921208266L,
87, 200, 697354, 3137635, 12, 606, 874228711599628459L,
88, 200, 767089, 214923, 12, 608, 1077644643342432307L,
89, 200, 843797, 3084545, 13, 612, 79317113064339979L,
90, 200, 928176, 7800899, 13, 612, 357414065779796772L,
91, 200, 1020993, 6717253, 13, 615, 532723577905833296L,
92, 200, 1123092, 5543015, 13, 614, 508695073250223746L,
93, 200, 1235401, 298785, 13, 616, 34344606952783179L,
94, 200, 1358941, 4530313, 13, 607, 169924026179364121L,
95, 200, 1494835, 4406457, 13, 612, 1026773494313671061L,
96, 200, 1644318, 1540983, 13, 614, 423454640036650614L,
97, 200, 1808749, 7999631, 14, 624, 466122870338520329L,
98, 200, 1989623, 4295537, 14, 621, 609309853701283445L,
99, 200, 2188585, 7379971, 14, 622, 141739898871015642L,
100, 200, 2407443, 6188931, 14, 621, 22515080776738923L,
101, 200, 2648187, 6701239, 14, 619, 257441864177795548L,
102, 200, 2913005, 2238709, 14, 623, 867028825821064773L,
103, 200, 3204305, 5371075, 14, 625, 1110615471273395112L,
104, 200, 3524735, 7017341, 15, 631, 619518037415974467L,
105, 200, 3877208, 323337, 15, 633, 513230912593541122L,
106, 200, 4264928, 6172471, 15, 628, 885861662583325072L,
107, 200, 4691420, 5653803, 15, 633, 754052473303005204L,
108, 200, 5160562, 1385265, 15, 630, 294993765757975100L,
109, 200, 5676618, 4350899, 15, 617, 1073144684944932303L,
110, 200, 6244279, 1272235, 15, 630, 308982934296855020L,
111, 200, 6868706, 1763939, 16, 638, 356231694823272867L,
112, 200, 7555576, 3703411, 16, 636, 20043268926300101L,
113, 200, 8311133, 6554171, 16, 637, 121111429906734123L,
};
private static int[] makeInputArray(int n, int stride) {
assert isOdd(stride);
int mask = (1 << 23) - 1; // because library items are single-precision floats
int cur = 0;
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
cur += stride;
cur &= mask;
arr[i] = cur;
}
return arr;
}
//@Test //only enabled to test the above makeInputArray(..)
public void testMakeInputArray() {
final int[] array = { 3654721, 7309442, 2575555, 6230276, 1496389, 5151110 };
Assert.assertEquals(makeInputArray(6, 3654721), array);
}
private static long simpleHashOfSubArray(final float[] arr, final int start, final int subLength) {
final long multiplier = 738219921; // an arbitrary odd 30-bit number
final long mask60 = (1L << 60) - 1;
long accum = 0;
for (int i = start; i < (start + subLength); i++) {
accum += (long) arr[i];
accum *= multiplier;
accum &= mask60;
accum ^= accum >> 30;
}
return accum;
}
//@Test //only enabled to test the above simpleHashOfSubArray(..)
public void testHash() {
float[] array = { 907500, 944104, 807020, 219921, 678370, 955217, 426885 };
Assert.assertEquals(simpleHashOfSubArray(array, 1, 5), 1141543353991880193L);
}
/*
* Please note that this test should be run with a modified version of KllFloatsHelper
* that chooses directions alternately instead of randomly.
* See the instructions at the bottom of that class.
*/
//@Test //NEED TO ENABLE HERE AND BELOW FOR VALIDATION
public void checkTestResults() {
int numTests = correctResultsWithReset.length / 7;
for (int testI = 0; testI < numTests; testI++) {
//KllFloatsHelper.nextOffset = 0; //NEED TO ENABLE
assert (int) correctResultsWithReset[7 * testI] == testI;
int k = (int) correctResultsWithReset[(7 * testI) + 1];
int n = (int) correctResultsWithReset[(7 * testI) + 2];
int stride = (int) correctResultsWithReset[(7 * testI) + 3];
int[] inputArray = makeInputArray(n, stride);
KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(k);
for (int i = 0; i < n; i++) {
sketch.update(inputArray[i]);
}
int numLevels = sketch.getNumLevels();
int numSamples = sketch.getNumRetained();
int[] levels = sketch.getLevelsArray(sketch.sketchStructure);
long hashedSamples = simpleHashOfSubArray(sketch.getFloatItemsArray(), levels[0], numSamples);
System.out.print(testI);
assert correctResultsWithReset[(7 * testI) + 4] == numLevels;
assert correctResultsWithReset[(7 * testI) + 5] == numSamples;
assert correctResultsWithReset[7 * testI + 6] == hashedSamples;
if (correctResultsWithReset[(7 * testI) + 6] == hashedSamples) {
System.out.println(" pass");
} else {
System.out.print(" " + correctResultsWithReset[(7 * testI) + 6] + " != " + hashedSamples);
System.out.println(" fail");
System.out.println(sketch.toString(true, true));
break;
}
}
}
}
| 2,368 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDoublesSketchTest.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.kll;
import static org.apache.datasketches.kll.KllSketch.SketchType.DOUBLES_SKETCH;
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 org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.quantilescommon.DoublesSortedView;
import org.apache.datasketches.quantilescommon.DoublesSortedViewIterator;
import org.testng.annotations.Test;
public class KllDoublesSketchTest {
private static final double PMF_EPS_FOR_K_8 = 0.35; // PMF rank error (epsilon) for k=8
private static final double PMF_EPS_FOR_K_128 = 0.025; // PMF rank error (epsilon) for k=128
private static final double PMF_EPS_FOR_K_256 = 0.013; // PMF rank error (epsilon) for k=256
private static final double NUMERIC_NOISE_TOLERANCE = 1E-6;
private static final DefaultMemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void empty() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
sketch.update(Double.NaN); // this must not change anything
assertTrue(sketch.isEmpty());
assertEquals(sketch.getN(), 0);
assertEquals(sketch.getNumRetained(), 0);
try { sketch.getRank(0); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getQuantile(0.5); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getQuantiles(new double[] {0}); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getPMF(new double[] {0}); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getCDF(new double[] {0}); fail(); } catch (SketchesArgumentException e) {}
assertNotNull(sketch.toString(true, true));
assertNotNull(sketch.toString());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void getQuantileInvalidArg() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
sketch.update(1);
sketch.getQuantile(-1.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void getQuantilesInvalidArg() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
sketch.update(1);
sketch.getQuantiles(new double[] {2.0});
}
@Test
public void oneValue() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
sketch.update(1);
assertFalse(sketch.isEmpty());
assertEquals(sketch.getN(), 1);
assertEquals(sketch.getNumRetained(), 1);
assertEquals(sketch.getRank(0.0, EXCLUSIVE), 0.0);
assertEquals(sketch.getRank(1.0, EXCLUSIVE), 0.0);
assertEquals(sketch.getRank(2.0, EXCLUSIVE), 1.0);
assertEquals(sketch.getRank(0.0, INCLUSIVE), 0.0);
assertEquals(sketch.getRank(1.0, INCLUSIVE), 1.0);
assertEquals(sketch.getRank(2.0, INCLUSIVE), 1.0);
assertEquals(sketch.getMinItem(), 1.0);
assertEquals(sketch.getMaxItem(), 1.0);
assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 1.0);
assertEquals(sketch.getQuantile(0.5, INCLUSIVE), 1.0);
}
@Test
public void tenValues() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(20);
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, INCLUSIVE), i / 10.0);
}
final double[] 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);
}
for (int i = 0; i >= 10; i++) {
double rank = i/10.0;
double q = rank == 1.0 ? i : i + 1;
assertEquals(sketch.getQuantile(rank, EXCLUSIVE), q);
q = rank == 0 ? i + 1.0 : i;
assertEquals(sketch.getQuantile(rank, INCLUSIVE), q);
}
{
// getQuantile() and getQuantiles() equivalence EXCLUSIVE
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.0}, EXCLUSIVE);
for (int i = 0; i <= 10; i++) {
assertEquals(sketch.getQuantile(i / 10.0, EXCLUSIVE), quantiles[i]);
}
}
{
// getQuantile() and getQuantiles() equivalence INCLUSIVE
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.0}, INCLUSIVE);
for (int i = 0; i <= 10; i++) {
assertEquals(sketch.getQuantile(i / 10.0, INCLUSIVE), quantiles[i]);
}
}
}
@Test
public void manyValuesEstimationMode() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
final int n = 1_000_000;
for (int i = 0; i < n; i++) {
sketch.update(i);
}
assertEquals(sketch.getN(), n);
// test getRank
for (int i = 0; i < n; i++) {
final double trueRank = (double) i / n;
assertEquals(sketch.getRank(i), trueRank, PMF_EPS_FOR_K_256, "for value " + i);
}
// test getPMF
final double[] pmf = sketch.getPMF(new double[] {n / 2.0}); // split at median
assertEquals(pmf.length, 2);
assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256);
assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256);
assertEquals(sketch.getMinItem(), 0f); // min value is exact
assertEquals(sketch.getMaxItem(), n - 1f); // max value is exact
// check at every 0.1 percentage point
final double[] fractions = new double[1001];
final double[] reverseFractions = new double[1001]; // check that ordering doesn't matter
for (int i = 0; i <= 1000; i++) {
fractions[i] = (double) i / 1000;
reverseFractions[1000 - i] = fractions[i];
}
final double[] quantiles = sketch.getQuantiles(fractions);
final double[] reverseQuantiles = sketch.getQuantiles(reverseFractions);
double previousQuantile = 0;
for (int i = 0; i <= 1000; i++) {
final double quantile = sketch.getQuantile(fractions[i]);
assertEquals(quantile, quantiles[i]);
assertEquals(quantile, reverseQuantiles[1000 - i]);
assertTrue(previousQuantile <= quantile);
previousQuantile = quantile;
}
}
@Test
public void getRankGetCdfGetPmfConsistency() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
final int n = 1000;
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);
final double[] pmf = sketch.getPMF(values);
double sumPmf = 0;
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i]), NUMERIC_NOISE_TOLERANCE,
"rank vs CDF for value " + i);
sumPmf += pmf[i];
assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i);
}
sumPmf += pmf[n];
assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE);
assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE);
}
{ // inclusive = true
final double[] ranks = sketch.getCDF(values, INCLUSIVE);
final double[] pmf = sketch.getPMF(values, INCLUSIVE);
double sumPmf = 0;
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i], INCLUSIVE), NUMERIC_NOISE_TOLERANCE,
"rank vs CDF for value " + i);
sumPmf += pmf[i];
assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i);
}
sumPmf += pmf[n];
assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE);
assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE);
}
}
@Test
public void merge() {
final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance();
final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance();
final int n = 10000;
for (int i = 0; i < n; i++) {
sketch1.update(i * 1.0);
sketch2.update((2 * n - i - 1) * 1.0);
}
assertEquals(sketch1.getMinItem(), 0.0);
assertEquals(sketch1.getMaxItem(), (n - 1) * 1.0);
assertEquals(sketch2.getMinItem(), n * 1.0);
assertEquals(sketch2.getMaxItem(), (2 * n - 1) * 1.0);
sketch1.merge(sketch2);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), 2L * n);
assertEquals(sketch1.getMinItem(), 0.0);
assertEquals(sketch1.getMaxItem(), (2 * n - 1) * 1.0);
assertEquals(sketch1.getQuantile(0.5), n * 1.0, 2 * n * PMF_EPS_FOR_K_256);
}
@Test
public void mergeLowerK() {
final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance(256);
final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance(128);
final int n = 10000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
sketch2.update(2 * n - i - 1);
}
assertEquals(sketch1.getMinItem(), 0.0f);
assertEquals(sketch1.getMaxItem(), n - 1f);
assertEquals(sketch2.getMinItem(), n);
assertEquals(sketch2.getMaxItem(), 2f * n - 1.0);
assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false));
assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true));
sketch1.merge(sketch2);
// sketch1 must get "contaminated" by the lower K in sketch2
assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false));
assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true));
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), 2 * n);
assertEquals(sketch1.getMinItem(), 0.0);
assertEquals(sketch1.getMaxItem(), 2.0 * n - 1.0);
assertEquals(sketch1.getQuantile(0.5), n, 2 * n * PMF_EPS_FOR_K_128);
}
@Test
public void mergeEmptyLowerK() {
final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance(256);
final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance(128);
final int n = 10_000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
}
// rank error should not be affected by a merge with an empty sketch with lower K
final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true);
sketch1.merge(sketch2);
assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), n);
assertEquals(sketch1.getMinItem(), 0.0);
assertEquals(sketch1.getMaxItem(), n - 1.0);
assertEquals(sketch1.getQuantile(0.5), n / 2.0, n * PMF_EPS_FOR_K_256);
//merge the other way
sketch2.merge(sketch1);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), n);
assertEquals(sketch1.getMinItem(), 0f);
assertEquals(sketch1.getMaxItem(), n - 1.0);
assertEquals(sketch1.getQuantile(0.5), n / 2.0, n * PMF_EPS_FOR_K_256);
}
@Test
public void mergeExactModeLowerK() {
final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance(256);
final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance(128);
final int n = 10000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
}
sketch2.update(1);
// rank error should not be affected by a merge with a sketch in exact mode with lower K
final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true);
sketch1.merge(sketch2);
assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge);
}
@Test
public void mergeMinMinValueFromOther() {
final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance();
final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance();
sketch1.update(1);
sketch2.update(2);
sketch2.merge(sketch1);
assertEquals(sketch2.getMinItem(), 1.0);
}
@Test
public void mergeMinAndMaxFromOther() {
final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance();
for (int i = 1; i <= 1_000_000; i++) {
sketch1.update(i);
}
final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance(10);
sketch2.merge(sketch1);
assertEquals(sketch2.getMinItem(), 1.0);
assertEquals(sketch2.getMaxItem(), 1_000_000.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void kTooSmall() {
KllDoublesSketch.newHeapInstance(KllSketch.DEFAULT_M - 1);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void kTooLarge() {
KllDoublesSketch.newHeapInstance(KllSketch.MAX_K + 1);
}
@Test
public void minK() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(KllSketch.DEFAULT_M);
for (int i = 0; i < 1000; i++) {
sketch.update(i);
}
assertEquals(sketch.getK(), KllSketch.DEFAULT_M);
assertEquals(sketch.getQuantile(0.5), 500.0, 1000 * PMF_EPS_FOR_K_8);
}
@Test
public void maxK() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(KllSketch.MAX_K);
for (int i = 0; i < 1000; i++) {
sketch.update(i);
}
assertEquals(sketch.getK(), KllSketch.MAX_K);
assertEquals(sketch.getQuantile(0.5), 500, 1000 * PMF_EPS_FOR_K_256);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void outOfOrderSplitPoints() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
sketch.update(0);
sketch.getCDF(new double[] {1.0, 0.0});
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void nanSplitPoint() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
sketch.update(0);
sketch.getCDF(new double[] {Double.NaN});
}
@Test
public void getQuantiles() {
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
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 checkReset() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= 100; i++) { sk.update(i); }
long n1 = sk.getN();
double min1 = sk.getMinItem();
double max1 = sk.getMaxItem();
sk.reset();
for (int i = 1; i <= 100; i++) { sk.update(i); }
long n2 = sk.getN();
double min2 = sk.getMinItem();
double max2 = sk.getMaxItem();
assertEquals(n2, n1);
assertEquals(min2, min1);
assertEquals(max2, max1);
}
@Test
public void checkReadOnlyUpdate() {
KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(20);
Memory mem = Memory.wrap(sk1.toByteArray());
KllDoublesSketch sk2 = KllDoublesSketch.wrap(mem);
try { sk2.update(1); fail(); } catch (SketchesArgumentException e) { }
}
@Test
public void checkNewDirectInstanceAndSize() {
WritableMemory wmem = WritableMemory.allocate(3000);
KllDoublesSketch.newDirectInstance(wmem, memReqSvr);
try { KllDoublesSketch.newDirectInstance(null, memReqSvr); fail(); }
catch (NullPointerException e) { }
try { KllFloatsSketch.newDirectInstance(wmem, null); fail(); }
catch (NullPointerException e) { }
int updateSize = KllSketch.getMaxSerializedSizeBytes(200, 0, DOUBLES_SKETCH, true);
int compactSize = KllSketch.getMaxSerializedSizeBytes(200, 0, DOUBLES_SKETCH, false);
assertTrue(compactSize < updateSize);
}
@Test
public void sortedView() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance();
sk.update(3);
sk.update(1);
sk.update(2);
DoublesSortedView view = sk.getSortedView();
DoublesSortedViewIterator itr = view.iterator();
assertEquals(itr.next(), true);
assertEquals(itr.getQuantile(), 1);
assertEquals(itr.getWeight(), 1);
assertEquals(itr.getCumulativeWeight(EXCLUSIVE), 0);
assertEquals(itr.getCumulativeWeight(INCLUSIVE), 1);
assertEquals(itr.next(), true);
assertEquals(itr.getQuantile(), 2);
assertEquals(itr.getWeight(), 1);
assertEquals(itr.getCumulativeWeight(EXCLUSIVE), 1);
assertEquals(itr.getCumulativeWeight(INCLUSIVE), 2);
assertEquals(itr.next(), true);
assertEquals(itr.getQuantile(), 3);
assertEquals(itr.getWeight(), 1);
assertEquals(itr.getCumulativeWeight(EXCLUSIVE), 2);
assertEquals(itr.getCumulativeWeight(INCLUSIVE), 3);
assertEquals(itr.next(), false);
}
@Test //also visual
public void checkCDF_PDF() {
final double[] cdfI = {.25, .50, .75, 1.0, 1.0 };
final double[] cdfE = {0.0, .25, .50, .75, 1.0 };
final double[] pmfI = {.25, .25, .25, .25, 0.0 };
final double[] pmfE = {0.0, .25, .25, .25, .25 };
final double toll = 1E-10;
final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance();
final double[] doublesIn = {10, 20, 30, 40};
for (int i = 0; i < doublesIn.length; i++) { sketch.update(doublesIn[i]); }
double[] sp = new double[] { 10, 20, 30, 40 };
println("SplitPoints:");
for (int i = 0; i < sp.length; i++) {
printf("%10.2f", sp[i]);
}
println("");
println("INCLUSIVE:");
double[] cdf = sketch.getCDF(sp, INCLUSIVE);
double[] pmf = sketch.getPMF(sp, INCLUSIVE);
printf("%10s%10s\n", "CDF", "PMF");
for (int i = 0; i < cdf.length; i++) {
printf("%10.2f%10.2f\n", cdf[i], pmf[i]);
assertEquals(cdf[i], cdfI[i], toll);
assertEquals(pmf[i], pmfI[i], toll);
}
println("EXCLUSIVE");
cdf = sketch.getCDF(sp, EXCLUSIVE);
pmf = sketch.getPMF(sp, EXCLUSIVE);
printf("%10s%10s\n", "CDF", "PMF");
for (int i = 0; i < cdf.length; i++) {
printf("%10.2f%10.2f\n", cdf[i], pmf[i]);
assertEquals(cdf[i], cdfE[i], toll);
assertEquals(pmf[i], pmfE[i], toll);
}
}
@Test
public void checkWrapCase1Doubles() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
Memory mem = Memory.wrap(sk.toByteArray());
KllDoublesSketch sk2 = KllDoublesSketch.wrap(mem);
assertTrue(mem.isReadOnly());
assertTrue(sk2.isReadOnly());
assertFalse(sk2.isDirect());
}
@Test
public void checkWritableWrapCase6And2Doubles() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
WritableMemory wmem = WritableMemory.writableWrap(KllHelper.toByteArray(sk, true));
KllDoublesSketch sk2 = KllDoublesSketch.writableWrap(wmem, memReqSvr);
assertFalse(wmem.isReadOnly());
assertFalse(sk2.isReadOnly());
assertFalse(sk2.isDirect());
}
@Test
public void checkKllSketchCase5Doubles() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
KllDoublesSketch sk2 = KllDoublesSketch.writableWrap(wmem, memReqSvr);
assertFalse(wmem.isReadOnly());
assertTrue(sk2.isReadOnly());
assertFalse(sk2.isDirect());
}
@Test
public void checkKllSketchCase3Doubles() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
Memory mem = Memory.wrap(KllHelper.toByteArray(sk, true));
WritableMemory wmem = (WritableMemory) mem;
KllDoublesSketch sk2 = KllDoublesSketch.writableWrap(wmem, memReqSvr);
assertTrue(wmem.isReadOnly());
assertTrue(sk2.isReadOnly());
assertFalse(sk2.isDirect());
}
@Test
public void checkKllSketchCase7Doubles() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
Memory mem = Memory.wrap(KllHelper.toByteArray(sk, true));
WritableMemory wmem = (WritableMemory) mem;
KllDoublesSketch sk2 = KllDoublesSketch.writableWrap(wmem, memReqSvr);
assertTrue(wmem.isReadOnly());
assertTrue(sk2.isReadOnly());
assertFalse(sk2.isDirect());
}
@Test
public void checkReadOnlyExceptions() {
int[] intArr = new int[0];
int intV = 2;
int idx = 1;
KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(20);
Memory mem = Memory.wrap(sk1.toByteArray());
KllDoublesSketch sk2 = KllDoublesSketch.wrap(mem);
try { sk2.setLevelsArray(intArr); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setLevelsArrayAt(idx,intV); fail(); } catch (SketchesArgumentException e) { }
}
@Test
public void checkIsSameResource() {
int cap = 128;
WritableMemory wmem = WritableMemory.allocate(cap);
WritableMemory reg1 = wmem.writableRegion(0, 64);
WritableMemory reg2 = wmem.writableRegion(64, 64);
assertFalse(reg1 == reg2);
assertFalse(reg1.isSameResource(reg2));
WritableMemory reg3 = wmem.writableRegion(0, 64);
assertFalse(reg1 == reg3);
assertTrue(reg1.isSameResource(reg3));
byte[] byteArr1 = KllDoublesSketch.newHeapInstance(20).toByteArray();
reg1.putByteArray(0, byteArr1, 0, byteArr1.length);
KllDoublesSketch sk1 = KllDoublesSketch.wrap(reg1);
byte[] byteArr2 = KllDoublesSketch.newHeapInstance(20).toByteArray();
reg2.putByteArray(0, byteArr2, 0, byteArr2.length);
assertFalse(sk1.isSameResource(reg2));
byte[] byteArr3 = KllDoublesSketch.newHeapInstance(20).toByteArray();
reg3.putByteArray(0, byteArr3, 0, byteArr3.length);
assertTrue(sk1.isSameResource(reg3));
}
@Test
public void checkSortedViewAfterReset() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20);
sk.update(1.0);
DoublesSortedView sv = sk.getSortedView();
double dsv = sv.getQuantile(1.0, INCLUSIVE);
assertEquals(dsv, 1.0);
sk.reset();
try { sk.getSortedView(); fail(); } catch (SketchesArgumentException e) { }
}
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,369 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllMiscFloatsTest.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.kll;
import static org.apache.datasketches.kll.KllSketch.SketchType.FLOATS_SKETCH;
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.kll.KllDirectFloatsSketch.KllDirectCompactFloatsSketch;
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.quantilescommon.FloatsSortedView;
import org.apache.datasketches.quantilescommon.FloatsSortedViewIterator;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class KllMiscFloatsTest {
static final String LS = System.getProperty("line.separator");
private final MemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void checkSortedViewConstruction() {
final KllFloatsSketch kll = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= 20; i++) { kll.update(i); }
FloatsSortedView fsv = kll.getSortedView();
long[] cumWeights = fsv.getCumulativeWeights();
float[] values = fsv.getQuantiles();
assertEquals(cumWeights.length, 20);
assertEquals(values.length, 20);
for (int i = 0; i < 20; i++) {
assertEquals(cumWeights[i], i + 1);
assertEquals(values[i], i + 1);
}
}
@Test
public void checkBounds() {
final KllFloatsSketch kll = KllFloatsSketch.newHeapInstance(); //default k = 200
for (int i = 0; i < 1000; i++) {
kll.update(i);
}
final double eps = kll.getNormalizedRankError(false);
final float est = kll.getQuantile(0.5);
final float ub = kll.getQuantileUpperBound(0.5);
final float lb = kll.getQuantileLowerBound(0.5);
assertEquals(ub, kll.getQuantile(.5 + eps));
assertEquals(lb, kll.getQuantile(0.5 - eps));
println("Ext : " + est);
println("UB : " + ub);
println("LB : " + lb);
final double rest = kll.getRank(est);
final double restUB = kll.getRankUpperBound(rest);
final double restLB = kll.getRankLowerBound(rest);
assertTrue(restUB - rest < (2 * eps));
assertTrue(rest - restLB < (2 * eps));
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions1() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(6, (byte) 3); //corrupt with odd M
KllFloatsSketch.heapify(wmem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions2() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(0, (byte) 1); //corrupt preamble ints, should be 2
KllFloatsSketch.heapify(wmem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions3() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
sk.update(1.0f);
sk.update(2.0f);
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(0, (byte) 1); //corrupt preamble ints, should be 5
KllFloatsSketch.heapify(wmem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions4() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(1, (byte) 0); //corrupt SerVer, should be 1 or 2
KllFloatsSketch.heapify(wmem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions5() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(2, (byte) 0); //corrupt FamilyID, should be 15
KllFloatsSketch.heapify(wmem);
}
@Test //set static enablePrinting = true for visual checking
public void checkMisc() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(8);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) {} //empty
println(sk.toString(true, true));
for (int i = 0; i < 20; i++) { sk.update(i); }
println(sk.toString(true, true));
sk.toByteArray();
final float[] items = sk.getFloatItemsArray();
assertEquals(items.length, 16);
final int[] levels = sk.getLevelsArray(sk.sketchStructure);
assertEquals(levels.length, 3);
assertEquals(sk.getNumLevels(), 2);
}
@Test //set static enablePrinting = true for visual checking
public void visualCheckToString() {
final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20);
int n = 21;
for (int i = 1; i <= n; i++) { sk.update(i); }
println(sk.toString(true, true));
assertEquals(sk.getNumLevels(), 2);
assertEquals(sk.getMinItem(), 1);
assertEquals(sk.getMaxItem(), 21);
assertEquals(sk.getNumRetained(), 11);
final KllFloatsSketch sk2 = KllFloatsSketch.newHeapInstance(20);
n = 400;
for (int i = 101; i <= n + 100; i++) { sk2.update(i); }
println("\n" + sk2.toString(true, true));
assertEquals(sk2.getNumLevels(), 5);
assertEquals(sk2.getMinItem(), 101);
assertEquals(sk2.getMaxItem(), 500);
assertEquals(sk2.getNumRetained(), 52);
sk2.merge(sk);
println(LS + sk2.toString(true, true));
assertEquals(sk2.getNumLevels(), 5);
assertEquals(sk2.getMinItem(), 1);
assertEquals(sk2.getMaxItem(), 500);
assertEquals(sk2.getNumRetained(), 56);
}
@Test //set static enablePrinting = true for visual checking
public void viewHeapCompactions() {
int k = 20;
int n = 108;
int compaction = 0;
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= n; i++) {
sk.update(i);
if (sk.levelsArr[0] == 0) {
println(LS + "#<<< BEFORE COMPACTION # " + (++compaction) + " >>>");
println(sk.toString(true, true));
sk.update(++i);
println(LS + "#<<< AFTER COMPACTION # " + (compaction) + " >>>");
println(sk.toString(true, true));
assertEquals(sk.getFloatItemsArray()[sk.levelsArr[0]], i);
}
}
}
@Test //set static enablePrinting = true for visual checking
public void viewDirectCompactions() {
int k = 20;
int n = 108;
int sizeBytes = KllSketch.getMaxSerializedSizeBytes(k, n, FLOATS_SKETCH, true);
WritableMemory wmem = WritableMemory.allocate(sizeBytes);
KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(k, wmem, memReqSvr);
for (int i = 1; i <= n; i++) {
sk.update(i);
if (sk.levelsArr[0] == 0) {
println(sk.toString(true, true));
sk.update(++i);
println(sk.toString(true, true));
assertEquals(sk.getFloatItemsArray()[sk.levelsArr[0]], i);
}
}
}
@Test //set static enablePrinting = true for visual checking
public void viewCompactionAndSortedView() {
int n = 43;
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= n; i++) { sk.update(i); }
println(sk.toString(true, true));
FloatsSortedView sv = sk.getSortedView();
FloatsSortedViewIterator itr = sv.iterator();
println("### SORTED VIEW");
printf("%12s%12s\n", "Value", "CumWeight");
while (itr.next()) {
float v = itr.getQuantile();
long wt = itr.getWeight();
printf("%12.1f%12d\n", v, wt);
}
}
@Test
public void checkGrowLevels() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
assertEquals(sk.getNumLevels(), 2);
assertEquals(sk.getFloatItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure)[2], 33);
}
@Test //set static enablePrinting = true for visual checking
public void checkSketchInitializeFloatHeap() {
int k = 20; //don't change this
KllFloatsSketch sk;
println("#### CASE: FLOAT FULL HEAP");
sk = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0F);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT HEAP EMPTY");
sk = KllFloatsSketch.newHeapInstance(k);
println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT HEAP SINGLE");
sk = KllFloatsSketch.newHeapInstance(k);
sk.update(1);
println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0F);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test //set static enablePrinting = true for visual checking
public void checkSketchInitializeFloatHeapifyCompactMem() {
int k = 20; //don't change this
KllFloatsSketch sk;
KllFloatsSketch sk2;
byte[] compBytes;
WritableMemory wmem;
println("#### CASE: FLOAT FULL HEAPIFIED FROM COMPACT");
sk2 = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk2.update(i); }
//println(sk2.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
println(KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true));
sk = KllFloatsSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0F);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT EMPTY HEAPIFIED FROM COMPACT");
sk2 = KllFloatsSketch.newHeapInstance(k);
//println(sk.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true));
sk = KllFloatsSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT SINGLE HEAPIFIED FROM COMPACT");
sk2 = KllFloatsSketch.newHeapInstance(k);
sk2.update(1);
//println(sk2.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true));
sk = KllFloatsSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0F);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test //set static enablePrinting = true for visual checking
public void checkSketchInitializeFloatHeapifyUpdatableMem() {
int k = 20; //don't change this
KllFloatsSketch sk;
KllFloatsSketch sk2;
byte[] compBytes;
WritableMemory wmem;
println("#### CASE: FLOAT FULL HEAPIFIED FROM UPDATABLE");
sk2 = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk2.update(i); }
//println(sk2.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
println(KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true));
sk = KllHeapFloatsSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0F);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT EMPTY HEAPIFIED FROM UPDATABLE");
sk2 = KllFloatsSketch.newHeapInstance(k);
//println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true));
sk = KllHeapFloatsSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT SINGLE HEAPIFIED FROM UPDATABLE");
sk2 = KllFloatsSketch.newHeapInstance(k);
sk2.update(1);
//println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true));
sk = KllHeapFloatsSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0F);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test //set static enablePrinting = true for visual checking
public void checkMemoryToStringFloatCompact() {
int k = 20; //don't change this
KllFloatsSketch sk;
KllFloatsSketch sk2;
byte[] compBytes;
byte[] compBytes2;
WritableMemory wmem;
String s;
println("#### CASE: FLOAT FULL COMPACT");
sk = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
compBytes = sk.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllFloatsSketch.heapify(wmem);
compBytes2 = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes2);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(compBytes, compBytes2);
println("#### CASE: FLOAT EMPTY COMPACT");
sk = KllFloatsSketch.newHeapInstance(k);
compBytes = sk.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllFloatsSketch.heapify(wmem);
compBytes2 = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes2);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(compBytes, compBytes2);
println("#### CASE: FLOAT SINGLE COMPACT");
sk = KllFloatsSketch.newHeapInstance(k);
sk.update(1);
compBytes = sk.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllFloatsSketch.heapify(wmem);
compBytes2 = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes2);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(compBytes, compBytes2);
}
@Test //set static enablePrinting = true for visual checking
public void checkMemoryToStringFloatUpdatable() {
int k = 20; //don't change this
KllFloatsSketch sk;
KllFloatsSketch sk2;
byte[] upBytes;
byte[] upBytes2;
WritableMemory wmem;
String s;
println("#### CASE: FLOAT FULL UPDATABLE");
sk = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllHeapFloatsSketch.heapifyImpl(wmem);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s); //note: heapify does not copy garbage, while toUpdatableByteArray does
assertEquals(sk.getN(), sk2.getN());
assertEquals(sk.getMinItem(), sk2.getMinItem());
assertEquals(sk.getMaxItem(), sk2.getMaxItem());
assertEquals(sk.getNumRetained(), sk2.getNumRetained());
println("#### CASE: FLOAT EMPTY UPDATABLE");
sk = KllFloatsSketch.newHeapInstance(k);
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllHeapFloatsSketch.heapifyImpl(wmem);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(upBytes, upBytes2);
println("#### CASE: FLOAT SINGLE UPDATABLE");
sk = KllFloatsSketch.newHeapInstance(k);
sk.update(1);
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllHeapFloatsSketch.heapifyImpl(wmem);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(upBytes, upBytes2);
}
@Test
public void checkSimpleMerge() {
int k = 20;
int m = 8;
int n1 = 21;
int n2 = 43;
WritableMemory wmem = WritableMemory.allocate(3000);
WritableMemory wmem2 = WritableMemory.allocate(3000);
KllFloatsSketch sk1 = KllDirectFloatsSketch.newDirectUpdatableInstance(k, m, wmem, memReqSvr);
KllFloatsSketch sk2 = KllDirectFloatsSketch.newDirectUpdatableInstance(k, m, wmem2, memReqSvr);
for (int i = 1; i <= n1; i++) {
sk1.update(i);
}
for (int i = 1; i <= n2; i++) {
sk2.update(i + 100);
}
sk1.merge(sk2);
assertEquals(sk1.getMinItem(), 1.0);
assertEquals(sk1.getMaxItem(), 143.0);
}
@Test
public void checkGetSingleItem() {
int k = 20;
KllFloatsSketch skHeap = KllFloatsSketch.newHeapInstance(k);
skHeap.update(1);
assertTrue(skHeap instanceof KllHeapFloatsSketch);
assertEquals(skHeap.getFloatSingleItem(), 1.0F);
WritableMemory srcMem = WritableMemory.writableWrap(KllHelper.toByteArray(skHeap, true));
KllFloatsSketch skDirect = KllFloatsSketch.writableWrap(srcMem, memReqSvr);
assertTrue(skDirect instanceof KllDirectFloatsSketch);
assertEquals(skDirect.getFloatSingleItem(), 1.0F);
Memory srcMem2 = Memory.wrap(skHeap.toByteArray());
KllFloatsSketch skCompact = KllFloatsSketch.wrap(srcMem2);
assertTrue(skCompact instanceof KllDirectCompactFloatsSketch);
assertEquals(skCompact.getFloatSingleItem(), 1.0F);
}
@Test
public void printlnTest() {
String s = "PRINTING: printf in " + this.getClass().getName();
println(s);
printf("%s\n", s);
}
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,370 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDirectCompactFloatsSketchTest.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.kll;
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.kll.KllDirectFloatsSketch.KllDirectCompactFloatsSketch;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
public class KllDirectCompactFloatsSketchTest {
private static final DefaultMemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void checkRODirectUpdatable_ROandWritable() {
int k = 20;
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
byte[] byteArr = KllHelper.toByteArray(sk, true); //request updatable
Memory srcMem = Memory.wrap(byteArr); //cast to Memory -> read only
KllFloatsSketch sk2 = KllFloatsSketch.wrap(srcMem);
assertTrue(sk2 instanceof KllDirectFloatsSketch);
assertTrue(sk2.isMemoryUpdatableFormat());
assertTrue(sk2.isReadOnly());
assertEquals(sk2.getMinItem(), 1.0F);
assertEquals(sk2.getMaxItem(), 21.0F);
WritableMemory srcWmem = WritableMemory.writableWrap(byteArr);
KllFloatsSketch sk3 = KllFloatsSketch.writableWrap(srcWmem, memReqSvr);
assertTrue(sk3 instanceof KllDirectFloatsSketch);
println(sk3.toString(true, false));
assertFalse(sk3.isReadOnly());
sk3.update(22.0F);
assertEquals(sk2.getMinItem(), 1.0F);
assertEquals(sk2.getMaxItem(), 22.0F);
}
@Test
public void checkRODirectCompact() {
int k = 20;
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
Memory srcMem = Memory.wrap(sk.toByteArray()); //compact RO fmt
KllFloatsSketch sk2 = KllFloatsSketch.wrap(srcMem);
assertTrue(sk2 instanceof KllDirectCompactFloatsSketch);
//println(sk2.toString(true, false));
assertFalse(sk2.isMemoryUpdatableFormat());
assertTrue(sk2.isReadOnly());
assertEquals(sk2.getMinItem(), 1.0F);
assertEquals(sk2.getMaxItem(), 21.0F);
Memory srcMem2 = Memory.wrap(sk2.toByteArray());
KllFloatsSketch sk3 = KllFloatsSketch.writableWrap((WritableMemory)srcMem2, memReqSvr);
assertTrue(sk3 instanceof KllDirectCompactFloatsSketch);
assertFalse(sk2.isMemoryUpdatableFormat());
//println(sk3.toString(true, false));
assertTrue(sk3.isReadOnly());
assertEquals(sk3.getMinItem(), 1.0F);
assertEquals(sk3.getMaxItem(), 21.0F);
}
@Test
public void checkDirectCompactSingleItem() {
int k = 20;
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k);
sk.update(1);
KllFloatsSketch sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
assertTrue(sk2 instanceof KllDirectCompactFloatsSketch);
//println(sk2.toString(true, false));
assertTrue(sk2.isReadOnly());
assertEquals(sk2.getFloatSingleItem(), 1.0F);
sk.update(2);
sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
assertEquals(sk2.getN(), 2);
try {
sk2.getFloatSingleItem();
fail();
} catch (SketchesArgumentException e) { }
}
@Test
public void checkDirectCompactGetFloatItemsArray() {
int k = 20;
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k);
KllFloatsSketch sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
float[] itemsArr = sk2.getFloatItemsArray();
for (int i = 0; i < 20; i++) { assertEquals(itemsArr[i], 0F); }
sk.update(1);
sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
itemsArr = sk2.getFloatItemsArray();
for (int i = 0; i < 19; i++) { assertEquals(itemsArr[i], 0F); }
assertEquals(itemsArr[19], 1F);
for (int i = 2; i <= 21; i++) { sk.update(i); }
sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
itemsArr = sk2.getFloatItemsArray();
assertEquals(itemsArr.length, 33);
assertEquals(itemsArr[22], 21);
}
@Test
public void checkHeapAndDirectCompactGetRetainedItemsArray() {
int k = 20;
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k);
float[] retArr = sk.getFloatRetainedItemsArray();
assertEquals(retArr.length, 0);
KllFloatsSketch sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
retArr = sk2.getFloatRetainedItemsArray();
assertEquals(retArr.length, sk.getNumRetained());
assertEquals(retArr.length, 0);
sk.update(1f);
retArr = sk.getFloatRetainedItemsArray();
assertEquals(retArr.length, sk.getNumRetained());
assertEquals(retArr.length, 1);
assertEquals(retArr[0], 1f);
sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
retArr = sk2.getFloatRetainedItemsArray();
assertEquals(retArr.length, sk.getNumRetained());
assertEquals(retArr.length, 1);
assertEquals(retArr[0], 1f);
for (int i = 2; i <= 21; i++) { sk.update(i); }
retArr = sk.getFloatRetainedItemsArray();
assertEquals(retArr.length, sk.getNumRetained());
assertEquals(retArr.length, 11);
sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
assertEquals(retArr.length, sk2.getNumRetained());
assertEquals(retArr.length, 11);
}
@Test
public void checkMinAndMax() {
int k = 20;
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k);
KllFloatsSketch sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
try { sk2.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sk2.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
sk.update(1);
sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
assertEquals(sk2.getMaxItem(),1.0F);
assertEquals(sk2.getMinItem(),1.0F);
for (int i = 2; i <= 21; i++) { sk.update(i); }
sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
assertEquals(sk2.getMaxItem(),21.0F);
assertEquals(sk2.getMinItem(),1.0F);
}
@Test
public void checkQuantile() {
KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance();
for (int i = 1; i <= 1000; i++) { sk1.update(i); }
KllFloatsSketch sk2 = KllFloatsSketch.wrap(Memory.wrap(sk1.toByteArray()));
double med2 = sk2.getQuantile(0.5);
double med1 = sk1.getQuantile(0.5);
assertEquals(med1, med2);
println("Med1: " + med1);
println("Med2: " + med2);
}
@Test
public void checkCompactSingleItemMerge() {
int k = 20;
KllFloatsSketch skH1 = KllFloatsSketch.newHeapInstance(k); //Heap with 1 (single)
skH1.update(21);
KllFloatsSketch skDC1 = KllFloatsSketch.wrap(Memory.wrap(skH1.toByteArray())); //Direct Compact with 1 (single)
KllFloatsSketch skH20 = KllFloatsSketch.newHeapInstance(k); //Heap with 20
for (int i = 1; i <= 20; i++) { skH20.update(i); }
skH20.merge(skDC1);
assertEquals(skH20.getN(), 21);
WritableMemory wmem = WritableMemory.allocate(1000);
KllFloatsSketch skDU20 = KllFloatsSketch.newDirectInstance(k, wmem, memReqSvr);//Direct Updatable with 21
for (int i = 1; i <= 20; i++) { skDU20.update(i); }
skDU20.merge(skDC1);
assertEquals(skDU20.getN(), 21);
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
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,371 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllCrossLanguageTest.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.kll;
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.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 java.util.Comparator;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.TestUtil;
import org.apache.datasketches.common.Util;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIterator;
import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator;
import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIterator;
import org.testng.annotations.Test;
/**
* Methods for cross language integration testing
*/
public class KllCrossLanguageTest {
private ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
@Test(groups = {GENERATE_JAVA_FILES})
public void generateKllDoublesSketchBinaries() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000};
for (int n: nArr) {
final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance();
for (int i = 1; i <= n; i++) { sk.update(i); }
Files.newOutputStream(javaPath.resolve("kll_double_n" + n + "_java.sk")).write(sk.toByteArray());
}
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateKllFloatsSketchBinaries() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000};
for (int n: nArr) {
final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
for (int i = 1; i <= n; i++) { sk.update(i); }
Files.newOutputStream(javaPath.resolve("kll_float_n" + n + "_java.sk")).write(sk.toByteArray());
}
}
@Test(groups = {GENERATE_JAVA_FILES})
public void generateKllItemsSketchBinaries() throws IOException {
final int[] nArr = {0, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000};
for (int n: nArr) {
final int digits = Util.numDigits(n);
final KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
for (int i = 1; i <= n; i++) { sk.update(Util.intToFixedLengthString(i, digits)); }
Files.newOutputStream(javaPath.resolve("kll_string_n" + n + "_java.sk")).write(sk.toByteArray());
}
}
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
public void checkCppKllDoublesSketchOneItemVersion1() {
final byte[] byteArr = TestUtil.getResourceBytes("kll_sketch_double_one_item_v1.sk");
final KllDoublesSketch sk = KllDoublesSketch.heapify(Memory.wrap(byteArr));
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getMaxItem(), 1.0);
}
@Test(groups = {CHECK_CPP_HISTORICAL_FILES})
public void checkCppKllFloatsSketchOneItemVersion1() {
final byte[] byteArr = TestUtil.getResourceBytes("kll_sketch_float_one_item_v1.sk");
final KllFloatsSketch sk = KllFloatsSketch.heapify(Memory.wrap(byteArr));
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getMaxItem(), 1.0F);
}
@Test(groups = {CHECK_CPP_FILES})
public void kllFloat() throws IOException {
final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("kll_float_n" + n + "_cpp.sk"));
final KllFloatsSketch sketch = KllFloatsSketch.heapify(Memory.wrap(bytes));
assertEquals(sketch.getK(), 200);
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
assertTrue(n > 100 ? sketch.isEstimationMode() : !sketch.isEstimationMode());
assertEquals(sketch.getN(), n);
if (n > 0) {
assertEquals(sketch.getMinItem(), 1);
assertEquals(sketch.getMaxItem(), n);
long weight = 0;
QuantilesFloatsSketchIterator it = sketch.iterator();
while (it.next()) {
assertTrue(it.getQuantile() >= sketch.getMinItem());
assertTrue(it.getQuantile() <= sketch.getMaxItem());
weight += it.getWeight();
}
assertEquals(weight, n);
}
}
}
@Test(groups = {CHECK_CPP_FILES})
public void kllDouble() throws IOException {
final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("kll_double_n" + n + "_cpp.sk"));
final KllDoublesSketch sketch = KllDoublesSketch.heapify(Memory.wrap(bytes));
assertEquals(sketch.getK(), 200);
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
assertTrue(n > 100 ? sketch.isEstimationMode() : !sketch.isEstimationMode());
assertEquals(sketch.getN(), n);
if (n > 0) {
assertEquals(sketch.getMinItem(), 1);
assertEquals(sketch.getMaxItem(), n);
long weight = 0;
QuantilesDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
assertTrue(it.getQuantile() >= sketch.getMinItem());
assertTrue(it.getQuantile() <= sketch.getMaxItem());
weight += it.getWeight();
}
assertEquals(weight, n);
}
}
}
@Test(groups = {CHECK_CPP_FILES})
public void kllString() 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, 10, 100, 1000, 10000, 100000, 1000000};
for (int n: nArr) {
final byte[] bytes = Files.readAllBytes(cppPath.resolve("kll_string_n" + n + "_cpp.sk"));
final KllHeapItemsSketch<String> sketch = new KllHeapItemsSketch<>(
Memory.wrap(bytes),
numericOrder,
new ArrayOfStringsSerDe()
);
assertEquals(sketch.getK(), 200);
assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty());
assertTrue(n > 100 ? sketch.isEstimationMode() : !sketch.isEstimationMode());
assertEquals(sketch.getN(), n);
if (n > 0) {
assertEquals(sketch.getMinItem(), Integer.toString(1));
assertEquals(sketch.getMaxItem(), Integer.toString(n));
long weight = 0;
QuantilesGenericSketchIterator<String> it = sketch.iterator();
while (it.next()) {
assertTrue(numericOrder.compare(it.getQuantile(), sketch.getMinItem()) >= 0);
assertTrue(numericOrder.compare(it.getQuantile(), sketch.getMaxItem()) <= 0);
weight += it.getWeight();
}
assertEquals(weight, n);
}
}
}
}
| 2,372 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllSketchTest.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.kll;
import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY;
import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL;
import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE;
import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE;
import static org.apache.datasketches.kll.KllSketch.SketchStructure.getSketchStructure;
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 KllSketchTest {
@Test
public void checkSketchStructureEnum() {
assertEquals(getSketchStructure(2,1), COMPACT_EMPTY);
assertEquals(getSketchStructure(2,2), COMPACT_SINGLE);
assertEquals(getSketchStructure(5,1), COMPACT_FULL);
assertEquals(getSketchStructure(5,3), UPDATABLE);
try { getSketchStructure(5,2); fail(); } catch (SketchesArgumentException e) { }
try { getSketchStructure(2,3); fail(); } catch (SketchesArgumentException e) { }
}
private final static boolean enablePrinting = false;
/**
* @param o the Object to println
*/
static final void println(final Object o) {
if (enablePrinting) { System.out.println(o.toString()); }
}
}
| 2,373 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllFloatsSketchSerDeTest.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.kll;
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.memory.Memory;
import org.testng.annotations.Test;
public class KllFloatsSketchSerDeTest {
@Test
public void serializeDeserializeEmpty() {
final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance();
//from heap -> byte[] -> heap
final byte[] bytes = sk1.toByteArray();
final KllFloatsSketch sk2 = KllFloatsSketch.heapify(Memory.wrap(bytes));
assertEquals(bytes.length, sk1.getSerializedSizeBytes());
assertTrue(sk2.isEmpty());
assertEquals(sk2.getNumRetained(), sk1.getNumRetained());
assertEquals(sk2.getN(), sk1.getN());
assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
try { sk2.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sk2.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap
final KllFloatsSketch sk3 = KllFloatsSketch.wrap(Memory.wrap(bytes));
assertTrue(sk3.isEmpty());
assertEquals(sk3.getNumRetained(), sk1.getNumRetained());
assertEquals(sk3.getN(), sk1.getN());
assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
try { sk3.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sk3.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap -> byte[] -> compare byte[]
final byte[] bytes2 = sk3.toByteArray();
assertEquals(bytes, bytes2);
}
@Test
public void serializeDeserializeOneValue() {
final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance();
sk1.update(1);
//from heap -> byte[] -> heap
final byte[] bytes = sk1.toByteArray();
final KllFloatsSketch sk2 = KllFloatsSketch.heapify(Memory.wrap(bytes));
assertEquals(bytes.length, sk1.getSerializedSizeBytes());
assertFalse(sk2.isEmpty());
assertEquals(sk2.getNumRetained(), 1);
assertEquals(sk2.getN(), 1);
assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk2.getMinItem(), 1.0F);
assertEquals(sk2.getMaxItem(), 1.0F);
assertEquals(sk2.getSerializedSizeBytes(), Long.BYTES + Float.BYTES);
//from heap -> byte[] -> off heap
final KllFloatsSketch sk3 = KllFloatsSketch.wrap(Memory.wrap(bytes));
assertFalse(sk3.isEmpty());
assertEquals(sk3.getNumRetained(), 1);
assertEquals(sk3.getN(), 1);
assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk3.getMinItem(), 1.0f);
assertEquals(sk3.getMaxItem(), 1.0f);
assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap -> byte[] -> compare byte[]
final byte[] bytes2 = sk3.toByteArray();
assertEquals(bytes, bytes2);
}
@Test
public void serializeDeserializeMultipleValues() {
final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance();
final int n = 1000;
for (int i = 0; i < n; i++) {
sk1.update(i);
}
assertEquals(sk1.getMinItem(), 0.0f);
assertEquals(sk1.getMaxItem(), 999.0f);
//from heap -> byte[] -> heap
final byte[] bytes = sk1.toByteArray();
final KllFloatsSketch sk2 = KllFloatsSketch.heapify(Memory.wrap(bytes));
assertEquals(bytes.length, sk1.getSerializedSizeBytes());
assertFalse(sk2.isEmpty());
assertEquals(sk2.getNumRetained(), sk1.getNumRetained());
assertEquals(sk2.getN(), sk1.getN());
assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk2.getMinItem(), sk1.getMinItem());
assertEquals(sk2.getMaxItem(), sk1.getMaxItem());
assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap
final KllFloatsSketch sk3 = KllFloatsSketch.wrap(Memory.wrap(bytes));
assertFalse(sk3.isEmpty());
assertEquals(sk3.getNumRetained(), sk1.getNumRetained());
assertEquals(sk3.getN(), sk1.getN());
assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk3.getMinItem(), sk1.getMinItem());
assertEquals(sk3.getMaxItem(), sk1.getMaxItem());
assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap -> byte[] -> compare byte[]
final byte[] bytes2 = sk3.toByteArray();
assertEquals(bytes, bytes2);
}
}
| 2,374 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllMiscDirectDoublesTest.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.kll;
import static org.apache.datasketches.kll.KllSketch.SketchType.DOUBLES_SKETCH;
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.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.quantilescommon.DoublesSortedView;
import org.apache.datasketches.quantilescommon.DoublesSortedViewIterator;
import org.testng.annotations.Test;
public class KllMiscDirectDoublesTest {
static final String LS = System.getProperty("line.separator");
private static final DefaultMemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void checkBounds() {
final KllDoublesSketch kll = getDirectDoublesSketch(200, 0);
for (int i = 0; i < 1000; i++) {
kll.update(i);
}
final double eps = kll.getNormalizedRankError(false);
final double est = kll.getQuantile(0.5);
final double ub = kll.getQuantileUpperBound(0.5);
final double lb = kll.getQuantileLowerBound(0.5);
assertEquals(ub, kll.getQuantile(.5 + eps));
assertEquals(lb, kll.getQuantile(0.5 - eps));
println("Ext : " + est);
println("UB : " + ub);
println("LB : " + lb);
final double rest = kll.getRank(est);
final double restUB = kll.getRankUpperBound(rest);
final double restLB = kll.getRankLowerBound(rest);
assertTrue(restUB - rest < (2 * eps));
assertTrue(rest - restLB < (2 * eps));
}
@Test
public void checkMisc() {
final int k = 8;
final KllDoublesSketch sk = getDirectDoublesSketch(k, 0);
try { sk.getPartitionBoundaries(10); fail(); } catch (SketchesArgumentException e) {}
for (int i = 0; i < 20; i++) { sk.update(i); }
final double[] items = sk.getDoubleItemsArray();
assertEquals(items.length, 16);
final int[] levels = sk.getLevelsArray(sk.sketchStructure);
assertEquals(levels.length, 3);
assertEquals(sk.getNumLevels(), 2);
}
//@Test //enable static println(..) for visual checking
public void visualCheckToString() {
final int k = 20;
final KllDoublesSketch sk = getDirectDoublesSketch(k, 0);
for (int i = 0; i < 10; i++) { sk.update(i + 1); }
println(sk.toString(true, true));
final KllDoublesSketch sk2 = getDirectDoublesSketch(k, 0);
for (int i = 0; i < 400; i++) { sk2.update(i + 1); }
println("\n" + sk2.toString(true, true));
sk2.merge(sk);
final String s2 = sk2.toString(true, true);
println(LS + s2);
}
@Test
public void viewDirectCompactions() {
int k = 20;
int u = 108;
KllDoublesSketch sk = getDirectDoublesSketch(k, 0);
for (int i = 1; i <= u; i++) {
sk.update(i);
if (sk.levelsArr[0] == 0) {
println(sk.toString(true, true));
sk.update(++i);
println(sk.toString(true, true));
assertEquals(sk.getDoubleItemsArray()[sk.levelsArr[0]], i);
}
}
}
@Test
public void viewCompactionAndSortedView() {
int k = 20;
KllDoublesSketch sk = getDirectDoublesSketch(k, 0);
show(sk, 20);
DoublesSortedView sv = sk.getSortedView();
DoublesSortedViewIterator itr = sv.iterator();
printf("%12s%12s\n", "Value", "CumWeight");
while (itr.next()) {
double v = itr.getQuantile();
long wt = itr.getWeight();
printf("%12.1f%12d\n", v, wt);
}
}
private static void show(final KllDoublesSketch sk, int limit) {
int i = (int) sk.getN();
for ( ; i < limit; i++) { sk.update(i + 1); }
println(sk.toString(true, true));
}
@Test
public void checkSketchInitializeDoubleHeap() {
int k = 20; //don't change this
KllDoublesSketch sk;
//println("#### CASE: DOUBLE FULL HEAP");
sk = getDirectDoublesSketch(k, 0);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
//println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
//println("#### CASE: DOUBLE HEAP EMPTY");
sk = getDirectDoublesSketch(k, 0);
//println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
//println("#### CASE: DOUBLE HEAP SINGLE");
sk = getDirectDoublesSketch(k, 0);
sk.update(1);
//println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test
public void checkSketchInitializeDoubleHeapifyCompactMem() {
int k = 20; //don't change this
KllDoublesSketch sk;
KllDoublesSketch sk2;
byte[] compBytes;
WritableMemory wmem;
//println("#### CASE: DOUBLE FULL HEAPIFIED FROM COMPACT");
sk2 = getDirectDoublesSketch(k, 0);
for (int i = 1; i <= k + 1; i++) { sk2.update(i); }
//println(sk.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem));
sk = KllDoublesSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
//println("#### CASE: DOUBLE EMPTY HEAPIFIED FROM COMPACT");
sk2 = getDirectDoublesSketch(k, 0);
//println(sk.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem));
sk = KllDoublesSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
//println("#### CASE: DOUBLE SINGLE HEAPIFIED FROM COMPACT");
sk2 = getDirectDoublesSketch(k, 0);
sk2.update(1);
//println(sk2.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem));
sk = KllDoublesSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test
public void checkSketchInitializeDoubleHeapifyUpdatableMem() {
int k = 20; //don't change this
KllDoublesSketch sk;
KllDoublesSketch sk2;
byte[] compBytes;
WritableMemory wmem;
//println("#### CASE: DOUBLE FULL HEAPIFIED FROM UPDATABLE");
sk2 = getDirectDoublesSketch(k, 0);
for (int i = 1; i <= k + 1; i++) { sk2.update(i); }
//println(sk2.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
sk = KllHeapDoublesSketch.heapifyImpl(wmem);
//println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
// println("#### CASE: DOUBLE EMPTY HEAPIFIED FROM UPDATABLE");
sk2 = getDirectDoublesSketch(k, 0);
//println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem));
sk = KllHeapDoublesSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
//println("#### CASE: DOUBLE SINGLE HEAPIFIED FROM UPDATABLE");
sk2 = getDirectDoublesSketch(k, 0);
sk2.update(1);
//println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.memoryToString(wmem, true));
sk = KllHeapDoublesSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test
public void checkMemoryToStringDoubleUpdatable() {
int k = 20; //don't change this
KllDoublesSketch sk;
KllDoublesSketch sk2;
byte[] upBytes;
byte[] upBytes2;
WritableMemory wmem;
String s;
println("#### CASE: DOUBLE FULL UPDATABLE");
sk = getDirectDoublesSketch(k, 0);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllDoublesSketch.writableWrap(wmem, memReqSvr);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(upBytes, upBytes2);
println("#### CASE: DOUBLE EMPTY UPDATABLE");
sk = getDirectDoublesSketch(k, 0);
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllDoublesSketch.writableWrap(wmem, memReqSvr);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(upBytes, upBytes2);
println("#### CASE: DOUBLE SINGLE UPDATABL");
sk = getDirectDoublesSketch(k, 0);
sk.update(1);
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllDoublesSketch.writableWrap(wmem, memReqSvr);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(upBytes, upBytes2);
}
@Test
public void checkSimpleMerge() {
int k = 20;
int n1 = 21;
int n2 = 21;
KllDoublesSketch sk1 = getDirectDoublesSketch(k, 0);
KllDoublesSketch sk2 = getDirectDoublesSketch(k, 0);
for (int i = 1; i <= n1; i++) {
sk1.update(i);
}
for (int i = 1; i <= n2; i++) {
sk2.update(i + 100);
}
println(sk1.toString(true, true));
println(sk2.toString(true, true));
sk1.merge(sk2);
println(sk1.toString(true, true));
assertEquals(sk1.getMaxItem(), 121.0);
assertEquals(sk1.getMinItem(), 1.0);
}
@Test
public void checkSizes() {
KllDoublesSketch sk = getDirectDoublesSketch(20, 0);
for (int i = 1; i <= 21; i++) { sk.update(i); }
//println(sk.toString(true, true));
byte[] byteArr1 = KllHelper.toByteArray(sk, true);
int size1 = sk.currentSerializedSizeBytes(true);
assertEquals(size1, byteArr1.length);
byte[] byteArr2 = sk.toByteArray();
int size2 = sk.currentSerializedSizeBytes(false);
assertEquals(size2, byteArr2.length);
}
@Test
public void checkNewInstance() {
int k = 200;
WritableMemory dstMem = WritableMemory.allocate(6000);
KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(k, dstMem, memReqSvr);
for (int i = 1; i <= 10_000; i++) {sk.update(i); }
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getMaxItem(), 10000.0);
//println(sk.toString(true, true));
}
@Test
public void checkDifferentM() {
int k = 20;
int m = 4;
WritableMemory dstMem = WritableMemory.allocate(1000);
KllDoublesSketch sk = KllDirectDoublesSketch.newDirectUpdatableInstance(k, m, dstMem, memReqSvr);
for (int i = 1; i <= 200; i++) {sk.update(i); }
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getMaxItem(), 200.0);
}
private static KllDoublesSketch getDirectDoublesSketch(final int k, final int n) {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= n; i++) { sk.update(i); }
byte[] byteArr = KllHelper.toByteArray(sk, true);
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
KllDoublesSketch ddsk = KllDoublesSketch.writableWrap(wmem, memReqSvr);
return ddsk;
}
@Test
public void printlnTest() {
String s = "PRINTING: printf in " + this.getClass().getName();
println(s);
printf("%s\n", s);
}
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,375 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDirectDoublesSketchIteratorTest.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.kll;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIterator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class KllDirectDoublesSketchIteratorTest {
private static final DefaultMemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void emptySketch() {
final KllDoublesSketch sketch = getDDSketch(200, 0);
QuantilesDoublesSketchIterator it = sketch.iterator();
Assert.assertFalse(it.next());
}
@Test
public void oneItemSketch() {
final KllDoublesSketch sketch = getDDSketch(200, 0);
sketch.update(0);
QuantilesDoublesSketchIterator it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getQuantile(), 0f);
Assert.assertEquals(it.getWeight(), 1);
Assert.assertFalse(it.next());
}
@Test
public void bigSketches() {
for (int n = 1000; n < 100000; n += 2000) {
final KllDoublesSketch sketch = getDDSketch(200, 0);
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);
}
}
private static KllDoublesSketch getDDSketch(final int k, final int n) {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= n; i++) { sk.update(i); }
byte[] byteArr = KllHelper.toByteArray(sk, true);
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
KllDoublesSketch ddsk = KllDoublesSketch.writableWrap(wmem, memReqSvr);
return ddsk;
}
}
| 2,376 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllMiscDoublesTest.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.kll;
import static org.apache.datasketches.kll.KllSketch.SketchType.DOUBLES_SKETCH;
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.kll.KllDirectDoublesSketch.KllDirectCompactDoublesSketch;
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.quantilescommon.DoublesSortedView;
import org.apache.datasketches.quantilescommon.DoublesSortedViewIterator;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
public class KllMiscDoublesTest {
static final String LS = System.getProperty("line.separator");
private final MemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void checkSortedViewConstruction() {
final KllDoublesSketch kll = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= 20; i++) { kll.update(i); }
DoublesSortedView fsv = kll.getSortedView();
long[] cumWeights = fsv.getCumulativeWeights();
double[] values = fsv.getQuantiles();
assertEquals(cumWeights.length, 20);
assertEquals(values.length, 20);
for (int i = 0; i < 20; i++) {
assertEquals(cumWeights[i], i + 1);
assertEquals(values[i], i + 1);
}
}
@Test
public void checkBounds() {
final KllDoublesSketch kll = KllDoublesSketch.newHeapInstance(); // default k = 200
for (int i = 0; i < 1000; i++) {
kll.update(i);
}
final double eps = kll.getNormalizedRankError(false);
final double est = kll.getQuantile(0.5);
final double ub = kll.getQuantileUpperBound(0.5);
final double lb = kll.getQuantileLowerBound(0.5);
assertEquals(ub, kll.getQuantile(.5 + eps));
assertEquals(lb, kll.getQuantile(0.5 - eps));
println("Ext : " + est);
println("UB : " + ub);
println("LB : " + lb);
final double rest = kll.getRank(est);
final double restUB = kll.getRankUpperBound(rest);
final double restLB = kll.getRankLowerBound(rest);
assertTrue(restUB - rest < (2 * eps));
assertTrue(rest - restLB < (2 * eps));
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions1() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance();
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(6, (byte) 3); //corrupt with odd M
KllDoublesSketch.heapify(wmem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions2() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance();
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(0, (byte) 1); //corrupt preamble ints, should be 2
KllDoublesSketch.heapify(wmem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions3() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance();
sk.update(1.0f);
sk.update(2.0f);
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(0, (byte) 1); //corrupt preamble ints, should be 5
KllDoublesSketch.heapify(wmem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions4() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance();
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(1, (byte) 0); //corrupt SerVer, should be 1 or 2
KllDoublesSketch.heapify(wmem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions5() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance();
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(2, (byte) 0); //corrupt FamilyID, should be 15
KllDoublesSketch.heapify(wmem);
}
@Test //set static enablePrinting = true for visual checking
public void checkMisc() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(8);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) {} //empty
println(sk.toString(true, true));
for (int i = 0; i < 20; i++) { sk.update(i); }
println(sk.toString(true, true));
sk.toByteArray();
final double[] items = sk.getDoubleItemsArray();
assertEquals(items.length, 16);
final int[] levels = sk.getLevelsArray(sk.sketchStructure);
assertEquals(levels.length, 3);
assertEquals(sk.getNumLevels(), 2);
}
@Test //set static enablePrinting = true for visual checking
public void visualCheckToString() {
final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20);
int n = 21;
for (int i = 1; i <= n; i++) { sk.update(i); }
println(sk.toString(true, true));
assertEquals(sk.getNumLevels(), 2);
assertEquals(sk.getMinItem(), 1);
assertEquals(sk.getMaxItem(), 21);
assertEquals(sk.getNumRetained(), 11);
final KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(20);
n = 400;
for (int i = 101; i <= n + 100; i++) { sk2.update(i); }
println("\n" + sk2.toString(true, true));
assertEquals(sk2.getNumLevels(), 5);
assertEquals(sk2.getMinItem(), 101);
assertEquals(sk2.getMaxItem(), 500);
assertEquals(sk2.getNumRetained(), 52);
sk2.merge(sk);
println(LS + sk2.toString(true, true));
assertEquals(sk2.getNumLevels(), 5);
assertEquals(sk2.getMinItem(), 1);
assertEquals(sk2.getMaxItem(), 500);
assertEquals(sk2.getNumRetained(), 56);
}
@Test //set static enablePrinting = true for visual checking
public void viewHeapCompactions() {
int k = 20;
int n = 108;
int compaction = 0;
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= n; i++) {
sk.update(i);
if (sk.levelsArr[0] == 0) {
println(LS + "#<<< BEFORE COMPACTION # " + (++compaction) + " >>>");
println(sk.toString(true, true));
sk.update(++i);
println(LS + "#<<< AFTER COMPACTION # " + (compaction) + " >>>");
println(sk.toString(true, true));
assertEquals(sk.getDoubleItemsArray()[sk.levelsArr[0]], i);
}
}
}
@Test //set static enablePrinting = true for visual checking
public void viewDirectCompactions() {
int k = 20;
int n = 108;
int sizeBytes = KllSketch.getMaxSerializedSizeBytes(k, n, DOUBLES_SKETCH, true);
WritableMemory wmem = WritableMemory.allocate(sizeBytes);
KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(k, wmem, memReqSvr);
for (int i = 1; i <= n; i++) {
sk.update(i);
if (sk.levelsArr[0] == 0) {
println(sk.toString(true, true));
sk.update(++i);
println(sk.toString(true, true));
assertEquals(sk.getDoubleItemsArray()[sk.levelsArr[0]], i);
}
}
}
@Test //set static enablePrinting = true for visual checking
public void viewCompactionAndSortedView() {
int n = 43;
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= n; i++) { sk.update(i); }
println(sk.toString(true, true));
DoublesSortedView sv = sk.getSortedView();
DoublesSortedViewIterator itr = sv.iterator();
println("### SORTED VIEW");
printf("%12s%12s\n", "Value", "CumWeight");
while (itr.next()) {
double v = itr.getQuantile();
long wt = itr.getWeight();
printf("%12.1f%12d\n", v, wt);
}
}
@Test
public void checkGrowLevels() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
assertEquals(sk.getNumLevels(), 2);
assertEquals(sk.getDoubleItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure)[2], 33);
}
@Test //set static enablePrinting = true for visual checking
public void checkSketchInitializeDoubleHeap() {
int k = 20; //don't change this
KllDoublesSketch sk;
println("#### CASE: DOUBLE FULL HEAP");
sk = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: DOUBLE HEAP EMPTY");
sk = KllDoublesSketch.newHeapInstance(k);
println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: DOUBLE HEAP SINGLE");
sk = KllDoublesSketch.newHeapInstance(k);
sk.update(1);
println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test // set static enablePrinting = true for visual checking
public void checkSketchInitializeDoubleHeapifyCompactMem() {
int k = 20; // don't change this
KllDoublesSketch sk;
KllDoublesSketch sk2;
byte[] compBytes;
WritableMemory wmem;
println("#### CASE: DOUBLE FULL HEAPIFIED FROM COMPACT");
sk2 = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk2.update(i); }
// println(sk2.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
println(KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true));
sk = KllDoublesSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: DOUBLE EMPTY HEAPIFIED FROM COMPACT");
sk2 = KllDoublesSketch.newHeapInstance(k);
// println(sk.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true));
sk = KllDoublesSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: DOUBLE SINGLE HEAPIFIED FROM COMPACT");
sk2 = KllDoublesSketch.newHeapInstance(k);
sk2.update(1);
//println(sk2.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true));
sk = KllDoublesSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test // set static enablePrinting = true for visual checking
public void checkSketchInitializeDoubleHeapifyUpdatableMem() {
int k = 20; // don't change this
KllDoublesSketch sk;
KllDoublesSketch sk2;
byte[] compBytes;
WritableMemory wmem;
println("#### CASE: DOUBLE FULL HEAPIFIED FROM UPDATABLE");
sk2 = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk2.update(i); }
//println(sk2.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
println(KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true));
sk = KllHeapDoublesSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: DOUBLE EMPTY HEAPIFIED FROM UPDATABLE");
sk2 = KllDoublesSketch.newHeapInstance(k);
// println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true));
sk = KllHeapDoublesSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: DOUBLE SINGLE HEAPIFIED FROM UPDATABLE");
sk2 = KllDoublesSketch.newHeapInstance(k);
sk2.update(1);
//println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true));
sk = KllHeapDoublesSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test //set static enablePrinting = true for visual checking
public void checkMemoryToStringDoubleCompact() {
int k = 20; //don't change this
KllDoublesSketch sk;
KllDoublesSketch sk2;
byte[] compBytes;
byte[] compBytes2;
WritableMemory wmem;
String s;
println("#### CASE: DOUBLE FULL COMPACT");
sk = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
compBytes = sk.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllDoublesSketch.heapify(wmem);
compBytes2 = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes2);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(compBytes, compBytes2);
println("#### CASE: DOUBLE EMPTY COMPACT");
sk = KllDoublesSketch.newHeapInstance(20);
compBytes = sk.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllDoublesSketch.heapify(wmem);
compBytes2 = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes2);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(compBytes, compBytes2);
println("#### CASE: DOUBLE SINGLE COMPACT");
sk = KllDoublesSketch.newHeapInstance(20);
sk.update(1);
compBytes = sk.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllDoublesSketch.heapify(wmem);
compBytes2 = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes2);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(compBytes, compBytes2);
}
@Test //set static enablePrinting = true for visual checking
public void checkMemoryToStringDoubleUpdatable() {
int k = 20; //don't change this
KllDoublesSketch sk;
KllDoublesSketch sk2;
byte[] upBytes;
byte[] upBytes2;
WritableMemory wmem;
String s;
println("#### CASE: DOUBLE FULL UPDATABLE");
sk = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllHeapDoublesSketch.heapifyImpl(wmem);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s); //note: heapify does not copy garbage, while toUpdatableByteArray does
assertEquals(sk.getN(), sk2.getN());
assertEquals(sk.getMinItem(), sk2.getMinItem());
assertEquals(sk.getMaxItem(), sk2.getMaxItem());
assertEquals(sk.getNumRetained(), sk2.getNumRetained());
println("#### CASE: DOUBLE EMPTY UPDATABLE");
sk = KllDoublesSketch.newHeapInstance(k);
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllHeapDoublesSketch.heapifyImpl(wmem);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(upBytes, upBytes2);
println("#### CASE: DOUBLE SINGLE UPDATABL");
sk = KllDoublesSketch.newHeapInstance(k);
sk.update(1);
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllHeapDoublesSketch.heapifyImpl(wmem);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, DOUBLES_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(upBytes, upBytes2);
}
@Test
public void checkSimpleMerge() {
int k = 20;
int m = 8;
int n1 = 21;
int n2 = 43;
WritableMemory wmem = WritableMemory.allocate(3000);
WritableMemory wmem2 = WritableMemory.allocate(3000);
KllDoublesSketch sk1 = KllDirectDoublesSketch.newDirectUpdatableInstance(k, m, wmem, memReqSvr);
KllDoublesSketch sk2 = KllDirectDoublesSketch.newDirectUpdatableInstance(k, m, wmem2, memReqSvr);
for (int i = 1; i <= n1; i++) {
sk1.update(i);
}
for (int i = 1; i <= n2; i++) {
sk2.update(i + 100);
}
sk1.merge(sk2);
assertEquals(sk1.getMinItem(), 1.0);
assertEquals(sk1.getMaxItem(), 143.0);
}
@Test
public void checkGetSingleItem() {
int k = 20;
KllDoublesSketch skHeap = KllDoublesSketch.newHeapInstance(k);
skHeap.update(1);
assertTrue(skHeap instanceof KllHeapDoublesSketch);
assertEquals(skHeap.getDoubleSingleItem(), 1.0);
WritableMemory srcMem = WritableMemory.writableWrap(KllHelper.toByteArray(skHeap, true));
KllDoublesSketch skDirect = KllDoublesSketch.writableWrap(srcMem, memReqSvr);
assertTrue(skDirect instanceof KllDirectDoublesSketch);
assertEquals(skDirect.getDoubleSingleItem(), 1.0);
Memory srcMem2 = Memory.wrap(skHeap.toByteArray());
KllDoublesSketch skCompact = KllDoublesSketch.wrap(srcMem2);
assertTrue(skCompact instanceof KllDirectCompactDoublesSketch);
assertEquals(skCompact.getDoubleSingleItem(), 1.0);
}
@Test
public void printlnTest() {
String s = "PRINTING: printf in " + this.getClass().getName();
println(s);
printf("%s\n", s);
}
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,377 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllItemsSketchTest.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.kll;
import static java.lang.Math.ceil;
import static org.apache.datasketches.kll.KllSketch.SketchStructure.*;
import static org.apache.datasketches.kll.KllSketch.SketchType.*;
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.Comparator;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.Util;
import org.apache.datasketches.kll.KllSketch.SketchType;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.quantilescommon.DoublesSortedView;
import org.apache.datasketches.quantilescommon.GenericSortedView;
import org.apache.datasketches.quantilescommon.GenericSortedViewIterator;
import org.testng.annotations.Test;
@SuppressWarnings("unused")
public class KllItemsSketchTest {
private static final double PMF_EPS_FOR_K_8 = 0.35; // PMF rank error (epsilon) for k=8
private static final double PMF_EPS_FOR_K_128 = 0.025; // PMF rank error (epsilon) for k=128
private static final double PMF_EPS_FOR_K_256 = 0.013; // PMF rank error (epsilon) for k=256
private static final double NUMERIC_NOISE_TOLERANCE = 1E-6;
private ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
@Test
public void empty() {
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sketch.update(null); // this must not change anything
assertTrue(sketch.isEmpty());
assertEquals(sketch.getN(), 0);
assertEquals(sketch.getNumRetained(), 0);
try { sketch.getRank("", INCLUSIVE); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getQuantile(0.5); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getQuantiles(new double[] {0}); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getPMF(new String[] {""}); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getCDF(new String[] {""}); fail(); } catch (SketchesArgumentException e) {}
assertNotNull(sketch.toString(true, true));
assertNotNull(sketch.toString());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void getQuantileInvalidArg() {
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sketch.update("A");
sketch.getQuantile(-1.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void getQuantilesInvalidArg() {
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sketch.update("A");
sketch.getQuantiles(new double[] {2.0});
}
@Test
public void oneValue() {
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sketch.update("A");
assertFalse(sketch.isEmpty());
assertEquals(sketch.getN(), 1);
assertEquals(sketch.getNumRetained(), 1);
assertEquals(sketch.getRank("A", EXCLUSIVE), 0.0);
assertEquals(sketch.getRank("B", EXCLUSIVE), 1.0);
assertEquals(sketch.getRank("A", EXCLUSIVE), 0.0);
assertEquals(sketch.getRank("B", EXCLUSIVE), 1.0);
assertEquals(sketch.getRank("@", INCLUSIVE), 0.0);
assertEquals(sketch.getRank("A", INCLUSIVE), 1.0);
assertEquals(sketch.getMinItem(),"A");
assertEquals(sketch.getMaxItem(), "A");
assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), "A");
assertEquals(sketch.getQuantile(0.5, INCLUSIVE), "A");
}
@Test
public void tenValues() {
final String[] tenStr = {"A","B","C","D","E","F","G","H","I","J"};
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
for (int i = 1; i <= 10; i++) { sketch.update(tenStr[i - 1]); }
assertFalse(sketch.isEmpty());
assertEquals(sketch.getN(), 10);
assertEquals(sketch.getNumRetained(), 10);
for (int i = 1; i <= 10; i++) {
assertEquals(sketch.getRank(tenStr[i - 1], EXCLUSIVE), (i - 1) / 10.0);
assertEquals(sketch.getRank(tenStr[i - 1], INCLUSIVE), i / 10.0);
}
final String[] qArr = tenStr;
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);
}
for (int i = 0; i <= 10; i++) {
double rank = i/10.0;
String q = rank == 1.0 ? tenStr[i-1] : tenStr[i];
assertEquals(sketch.getQuantile(rank, EXCLUSIVE), q);
q = rank == 0 ? tenStr[i] : tenStr[i - 1];
assertEquals(sketch.getQuantile(rank, INCLUSIVE), q);
}
{
// getQuantile() and getQuantiles() equivalence EXCLUSIVE
final String[] 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.0}, EXCLUSIVE);
for (int i = 0; i <= 10; i++) {
assertEquals(sketch.getQuantile(i / 10.0, EXCLUSIVE), quantiles[i]);
}
}
{
// getQuantile() and getQuantiles() equivalence INCLUSIVE
final String[] 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 manyValuesEstimationMode() {
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
final int n = 1_000_000;
final int digits = Util.numDigits(n);
for (int i = 1; i <= n; i++) {
sketch.update(Util.intToFixedLengthString(i, digits));
assertEquals(sketch.getN(), i);
}
// test getRank
for (int i = 1; i <= n; i++) {
final double trueRank = (double) i / n;
String s = Util.intToFixedLengthString(i, digits);
double r = sketch.getRank(s);
assertEquals(r, trueRank, PMF_EPS_FOR_K_256, "for value " + s);
}
// test getPMF
String s = Util.intToFixedLengthString(n/2, digits);
final double[] pmf = sketch.getPMF(new String[] {s}); // split at median
assertEquals(pmf.length, 2);
assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256);
assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256);
assertEquals(sketch.getMinItem(), Util.intToFixedLengthString(1, digits));
assertEquals(sketch.getMaxItem(), Util.intToFixedLengthString(n, digits));
// check at every 0.1 percentage point
final double[] fractions = new double[1001];
final double[] reverseFractions = new double[1001]; // check that ordering doesn't matter
for (int i = 0; i <= 1000; i++) {
fractions[i] = (double) i / 1000;
reverseFractions[1000 - i] = fractions[i];
}
final String[] quantiles = sketch.getQuantiles(fractions);
final String[] reverseQuantiles = sketch.getQuantiles(reverseFractions);
String previousQuantile = "";
for (int i = 0; i <= 1000; i++) {
final String quantile = sketch.getQuantile(fractions[i]);
assertEquals(quantile, quantiles[i]);
assertEquals(quantile, reverseQuantiles[1000 - i]);
assertTrue(Util.le(previousQuantile, quantile, Comparator.naturalOrder()));
previousQuantile = quantile;
}
}
@Test
public void getRankGetCdfGetPmfConsistency() {
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
final int n = 1000;
final int digits = Util.numDigits(n);
final String[] quantiles = new String[n];
for (int i = 0; i < n; i++) {
final String str = Util.intToFixedLengthString(i, digits);
sketch.update(str);
quantiles[i] = str;
}
{ //EXCLUSIVE
final double[] ranks = sketch.getCDF(quantiles, EXCLUSIVE);
final double[] pmf = sketch.getPMF(quantiles, EXCLUSIVE);
double sumPmf = 0;
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(quantiles[i], EXCLUSIVE), NUMERIC_NOISE_TOLERANCE, "rank vs CDF for value " + i);
sumPmf += pmf[i];
assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i);
}
sumPmf += pmf[n];
assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE);
assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE);
}
{ // INCLUSIVE (default)
final double[] ranks = sketch.getCDF(quantiles, INCLUSIVE);
final double[] pmf = sketch.getPMF(quantiles, INCLUSIVE);
double sumPmf = 0;
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(quantiles[i], INCLUSIVE), NUMERIC_NOISE_TOLERANCE,
"rank vs CDF for value " + i);
sumPmf += pmf[i];
assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i);
}
sumPmf += pmf[n];
assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE);
assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE);
}
}
@Test
public void merge() {
final KllItemsSketch<String> sketch1 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
final KllItemsSketch<String> sketch2 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
final int n = 10000;
final int digits = Util.numDigits(2 * n);
for (int i = 0; i < n; i++) {
sketch1.update(Util.intToFixedLengthString(i, digits));
sketch2.update(Util.intToFixedLengthString(2 * n - i - 1, digits));
}
assertEquals(sketch1.getMinItem(), Util.intToFixedLengthString(0, digits));
assertEquals(sketch1.getMaxItem(), Util.intToFixedLengthString(n - 1, digits));
assertEquals(sketch2.getMinItem(), Util.intToFixedLengthString(n, digits));
assertEquals(sketch2.getMaxItem(), Util.intToFixedLengthString(2 * n - 1, digits));
sketch1.merge(sketch2);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), 2L * n);
assertEquals(sketch1.getMinItem(), Util.intToFixedLengthString(0, digits));
assertEquals(sketch1.getMaxItem(), Util.intToFixedLengthString(2 * n - 1, digits));
String upperBound = Util.intToFixedLengthString(n + (int)ceil(n * PMF_EPS_FOR_K_256), digits);
String lowerBound = Util.intToFixedLengthString(n - (int)ceil(n * PMF_EPS_FOR_K_256), digits);
String median = sketch1.getQuantile(0.5);
assertTrue(Util.le(median, upperBound, Comparator.naturalOrder()));
assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder()));
}
@Test
public void mergeLowerK() {
final KllItemsSketch<String> sketch1 = KllItemsSketch.newHeapInstance(256, Comparator.naturalOrder(), serDe);
final KllItemsSketch<String> sketch2 = KllItemsSketch.newHeapInstance(128, Comparator.naturalOrder(), serDe);
final int n = 10000;
final int digits = Util.numDigits(2 * n);
for (int i = 0; i < n; i++) {
sketch1.update(Util.intToFixedLengthString(i, digits));
sketch2.update(Util.intToFixedLengthString(2 * n - i - 1, digits));
}
assertEquals(sketch1.getMinItem(), Util.intToFixedLengthString(0, digits));
assertEquals(sketch1.getMaxItem(), Util.intToFixedLengthString(n - 1, digits));
assertEquals(sketch2.getMinItem(), Util.intToFixedLengthString(n, digits));
assertEquals(sketch2.getMaxItem(), Util.intToFixedLengthString(2 * n - 1, digits));
assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false));
assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true));
sketch1.merge(sketch2);
// sketch1 must get "contaminated" by the lower K in sketch2
assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false));
assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true));
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), 2 * n);
assertEquals(sketch1.getMinItem(), Util.intToFixedLengthString(0, digits));
assertEquals(sketch1.getMaxItem(), Util.intToFixedLengthString(2 * n - 1, digits));
String upperBound = Util.intToFixedLengthString(n + (int)ceil(2 * n * PMF_EPS_FOR_K_128), digits);
String lowerBound = Util.intToFixedLengthString(n - (int)ceil(2 * n * PMF_EPS_FOR_K_128), digits);
String median = sketch1.getQuantile(0.5);
assertTrue(Util.le(median, upperBound, Comparator.naturalOrder()));
assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder()));
}
@Test
public void mergeEmptyLowerK() {
final KllItemsSketch<String> sketch1 = KllItemsSketch.newHeapInstance(256, Comparator.naturalOrder(), serDe);
final KllItemsSketch<String> sketch2 = KllItemsSketch.newHeapInstance(128, Comparator.naturalOrder(), serDe);
final int n = 10000;
final int digits = Util.numDigits(n);
for (int i = 0; i < n; i++) {
sketch1.update(Util.intToFixedLengthString(i, digits)); //sketch2 is empty
}
// rank error should not be affected by a merge with an empty sketch with lower K
final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true);
sketch1.merge(sketch2);
assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge);
{
assertFalse(sketch1.isEmpty());
assertTrue(sketch2.isEmpty());
assertEquals(sketch1.getN(), n);
assertEquals(sketch1.getMinItem(), Util.intToFixedLengthString(0, digits));
assertEquals(sketch1.getMaxItem(), Util.intToFixedLengthString(n - 1, digits));
String upperBound = Util.intToFixedLengthString(n / 2 + (int)ceil(n * PMF_EPS_FOR_K_256), digits);
String lowerBound = Util.intToFixedLengthString(n / 2 - (int)ceil(n * PMF_EPS_FOR_K_256), digits);
String median = sketch1.getQuantile(0.5);
assertTrue(Util.le(median, upperBound, Comparator.naturalOrder()));
assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder()));
}
{
//merge the other way
sketch2.merge(sketch1);
assertFalse(sketch1.isEmpty());
assertFalse(sketch2.isEmpty());
assertEquals(sketch1.getN(), n);
assertEquals(sketch2.getN(), n);
assertEquals(sketch1.getMinItem(), Util.intToFixedLengthString(0, digits));
assertEquals(sketch1.getMaxItem(), Util.intToFixedLengthString(n - 1, digits));
assertEquals(sketch2.getMinItem(), Util.intToFixedLengthString(0, digits));
assertEquals(sketch2.getMaxItem(), Util.intToFixedLengthString(n - 1, digits));
String upperBound = Util.intToFixedLengthString(n / 2 + (int)ceil(n * PMF_EPS_FOR_K_128), digits);
String lowerBound = Util.intToFixedLengthString(n / 2 - (int)ceil(n * PMF_EPS_FOR_K_128), digits);
String median = sketch2.getQuantile(0.5);
assertTrue(Util.le(median, upperBound, Comparator.naturalOrder()));
assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder()));
}
}
@Test
public void mergeExactModeLowerK() {
final KllItemsSketch<String> sketch1 = KllItemsSketch.newHeapInstance(256, Comparator.naturalOrder(), serDe);
final KllItemsSketch<String> sketch2 = KllItemsSketch.newHeapInstance(128, Comparator.naturalOrder(), serDe);
final int n = 10000;
final int digits = Util.numDigits(n);
for (int i = 0; i < n; i++) {
sketch1.update(Util.intToFixedLengthString(i, digits));
}
sketch2.update(Util.intToFixedLengthString(1, digits));
// rank error should not be affected by a merge with a sketch in exact mode with lower K
final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true);
sketch1.merge(sketch2);
assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge);
}
@Test
public void mergeMinMinValueFromOther() {
final KllItemsSketch<String> sketch1 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
final KllItemsSketch<String> sketch2 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sketch1.update(Util.intToFixedLengthString(1, 1));
sketch2.update(Util.intToFixedLengthString(2, 1));
sketch2.merge(sketch1);
assertEquals(sketch2.getMinItem(), Util.intToFixedLengthString(1, 1));
}
@Test
public void mergeMinAndMaxFromOther() {
final KllItemsSketch<String> sketch1 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
final KllItemsSketch<String> sketch2 = KllItemsSketch.newHeapInstance(10, Comparator.naturalOrder(), serDe);
final int n = 1_000_000;
final int digits = Util.numDigits(n);
for (int i = 1; i <= 1_000_000; i++) {
sketch1.update(Util.intToFixedLengthString(i, digits)); //sketch2 is empty
}
sketch2.merge(sketch1);
assertEquals(sketch2.getMinItem(), Util.intToFixedLengthString(1, digits));
assertEquals(sketch2.getMaxItem(), Util.intToFixedLengthString(n, digits));
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void kTooSmall() {
KllItemsSketch.newHeapInstance(KllSketch.DEFAULT_M - 1, Comparator.naturalOrder(), serDe);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void kTooLarge() {
KllItemsSketch.newHeapInstance(KllSketch.MAX_K + 1, Comparator.naturalOrder(), serDe);
}
@Test
public void minK() {
final KllItemsSketch<String> sketch =
KllItemsSketch.newHeapInstance(KllSketch.DEFAULT_M,Comparator.naturalOrder(), serDe);
final int n = 1000;
final int digits = Util.numDigits(n);
for (int i = 0; i < n; i++) {
sketch.update(Util.intToFixedLengthString(i, digits));
}
assertEquals(sketch.getK(), KllSketch.DEFAULT_M);
String upperBound = Util.intToFixedLengthString(n / 2 + (int)ceil(n * PMF_EPS_FOR_K_8), digits);
String lowerBound = Util.intToFixedLengthString(n / 2 - (int)ceil(n * PMF_EPS_FOR_K_8), digits);
String median = sketch.getQuantile(0.5);
assertTrue(Util.le(median, upperBound, Comparator.naturalOrder()));
assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder()));
}
@Test
public void maxK() {
final KllItemsSketch<String> sketch =
KllItemsSketch.newHeapInstance(KllSketch.MAX_K,Comparator.naturalOrder(), serDe);
final int n = 1000;
final int digits = Util.numDigits(n);
for (int i = 0; i < n; i++) {
sketch.update(Util.intToFixedLengthString(i, digits));
}
assertEquals(sketch.getK(), KllSketch.MAX_K);
String upperBound = Util.intToFixedLengthString(n / 2 + (int)ceil(n * PMF_EPS_FOR_K_256), digits);
String lowerBound = Util.intToFixedLengthString(n / 2 - (int)ceil(n * PMF_EPS_FOR_K_256), digits);
String median = sketch.getQuantile(0.5);
assertTrue(Util.le(median, upperBound, Comparator.naturalOrder()));
assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder()));
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void outOfOrderSplitPoints() {
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
final String s0 = Util.intToFixedLengthString(0, 1);
final String s1 = Util.intToFixedLengthString(1, 1);
sketch.update(s0);
sketch.getCDF(new String[] {s1, s0});
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void nullSplitPoint() {
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sketch.update(Util.intToFixedLengthString(0, 1));
sketch.getCDF(new String[] {null});
}
@Test
public void getQuantiles() {
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sketch.update("A");
sketch.update("B");
sketch.update("C");
sketch.update("D");
String[] quantiles1 = sketch.getQuantiles(new double[] {0.0, 0.5, 1.0}, EXCLUSIVE);
String[] 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 checkReset() {
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
final int n = 100;
final int digits = Util.numDigits(n);
for (int i = 1; i <= n; i++) { sketch.update(Util.intToFixedLengthString(i, digits)); }
long n1 = sketch.getN();
String min1 = sketch.getMinItem();
String max1 = sketch.getMaxItem();
sketch.reset();
for (int i = 1; i <= 100; i++) { sketch.update(Util.intToFixedLengthString(i, digits)); }
long n2 = sketch.getN();
String min2 = sketch.getMinItem();
String max2 = sketch.getMaxItem();
assertEquals(n2, n1);
assertEquals(min2, min1);
assertEquals(max2, max1);
}
@Test
public void checkReadOnlyUpdate() {
KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
Memory mem = Memory.wrap(sk1.toByteArray());
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(mem, Comparator.naturalOrder(), serDe);
try { sk2.update("A"); fail(); } catch (SketchesArgumentException e) { }
}
@Test
public void checkNewDirectInstanceAndSmallSize() {
KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
Memory mem = Memory.wrap(sk1.toByteArray());
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(mem, Comparator.naturalOrder(), serDe);
int sizeBytes = sk2.currentSerializedSizeBytes(false);
assertEquals(sizeBytes, 8);
sk1.update("A");
mem = Memory.wrap(sk1.toByteArray());
sk2 = KllItemsSketch.wrap(mem, Comparator.naturalOrder(), serDe);
sizeBytes = sk2.currentSerializedSizeBytes(false);
assertEquals(sizeBytes, 8 + 5);
sk1.update("B");
mem = Memory.wrap(sk1.toByteArray());
sk2 = KllItemsSketch.wrap(mem, Comparator.naturalOrder(), serDe);
sizeBytes = sk2.currentSerializedSizeBytes(false);
assertEquals(sizeBytes, 20 + 4 + 2 * 5 + 2 * 5);
}
@Test
public void sortedView() {
final KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
sk.update("A");
sk.update("AB");
sk.update("ABC");
final GenericSortedView<String> view = sk.getSortedView();
final GenericSortedViewIterator<String> itr = view.iterator();
assertEquals(itr.next(), true);
assertEquals(itr.getQuantile(), "A");
assertEquals(itr.getWeight(), 1);
assertEquals(itr.getCumulativeWeight(EXCLUSIVE), 0);
assertEquals(itr.getCumulativeWeight(INCLUSIVE), 1);
assertEquals(itr.next(), true);
assertEquals(itr.getQuantile(), "AB");
assertEquals(itr.getWeight(), 1);
assertEquals(itr.getCumulativeWeight(EXCLUSIVE), 1);
assertEquals(itr.getCumulativeWeight(INCLUSIVE), 2);
assertEquals(itr.next(), true);
assertEquals(itr.getQuantile(), "ABC");
assertEquals(itr.getWeight(), 1);
assertEquals(itr.getCumulativeWeight(EXCLUSIVE), 2);
assertEquals(itr.getCumulativeWeight(INCLUSIVE), 3);
assertEquals(itr.next(), false);
}
@Test //also visual
public void checkCDF_PDF() {
final double[] cdfI = {.25, .50, .75, 1.0, 1.0 };
final double[] cdfE = {0.0, .25, .50, .75, 1.0 };
final double[] pmfI = {.25, .25, .25, .25, 0.0 };
final double[] pmfE = {0.0, .25, .25, .25, .25 };
final double toll = 1E-10;
final KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
final String[] strIn = {"A", "AB", "ABC", "ABCD"};
for (int i = 0; i < strIn.length; i++) { sketch.update(strIn[i]); }
String[] sp = new String[] {"A", "AB", "ABC", "ABCD"};
println("SplitPoints:");
for (int i = 0; i < sp.length; i++) {
printf("%10s", sp[i]);
}
println("");
println("INCLUSIVE:");
double[] cdf = sketch.getCDF(sp, INCLUSIVE);
double[] pmf = sketch.getPMF(sp, INCLUSIVE);
printf("%10s%10s\n", "CDF", "PMF");
for (int i = 0; i < cdf.length; i++) {
printf("%10.2f%10.2f\n", cdf[i], pmf[i]);
assertEquals(cdf[i], cdfI[i], toll);
assertEquals(pmf[i], pmfI[i], toll);
}
println("EXCLUSIVE");
cdf = sketch.getCDF(sp, EXCLUSIVE);
pmf = sketch.getPMF(sp, EXCLUSIVE);
printf("%10s%10s\n", "CDF", "PMF");
for (int i = 0; i < cdf.length; i++) {
printf("%10.2f%10.2f\n", cdf[i], pmf[i]);
assertEquals(cdf[i], cdfE[i], toll);
assertEquals(pmf[i], pmfE[i], toll);
}
}
@Test
public void checkWrapCase1Floats() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
final int n = 21;
final int digits = Util.numDigits(n);
for (int i = 1; i <= n; i++) { sk.update(Util.intToFixedLengthString(i, digits)); }
Memory mem = Memory.wrap(sk.toByteArray());
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(mem, Comparator.naturalOrder(), serDe);
assertTrue(mem.isReadOnly());
assertTrue(sk2.isReadOnly());
assertFalse(sk2.isDirect());
}
@Test
public void checkReadOnlyExceptions() {
int[] intArr = new int[0];
int intV = 2;
int idx = 1;
KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
Memory mem = Memory.wrap(sk1.toByteArray());
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(mem, Comparator.naturalOrder(), serDe);
try { sk2.setLevelsArray(intArr); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setLevelsArrayAt(idx,intV); fail(); } catch (SketchesArgumentException e) { }
}
@Test
public void checkIsSameResource() {
int cap = 128;
WritableMemory wmem = WritableMemory.allocate(cap);
WritableMemory reg1 = wmem.writableRegion(0, 64);
WritableMemory reg2 = wmem.writableRegion(64, 64);
assertFalse(reg1 == reg2);
assertFalse(reg1.isSameResource(reg2));
WritableMemory reg3 = wmem.writableRegion(0, 64);
assertFalse(reg1 == reg3);
assertTrue(reg1.isSameResource(reg3));
byte[] byteArr1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe).toByteArray();
reg1.putByteArray(0, byteArr1, 0, byteArr1.length);
KllItemsSketch<String> sk1 = KllItemsSketch.wrap(reg1, Comparator.naturalOrder(), serDe);
byte[] byteArr2 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe).toByteArray();
reg2.putByteArray(0, byteArr2, 0, byteArr2.length);
assertFalse(sk1.isSameResource(reg2));
byte[] byteArr3 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe).toByteArray();
reg3.putByteArray(0, byteArr3, 0, byteArr3.length);
assertTrue(sk1.isSameResource(reg3));
}
// New added tests specially for KllItemsSketch
@Test
public void checkHeapifyEmpty() {
final KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
Memory mem = Memory.wrap(sk1.toByteArray());
KllMemoryValidate memVal = new KllMemoryValidate(mem, SketchType.ITEMS_SKETCH, serDe);
assertEquals(memVal.sketchStructure, COMPACT_EMPTY);
assertEquals(mem.getCapacity(), 8);
final KllItemsSketch<String> sk2 = KllItemsSketch.heapify(mem, Comparator.naturalOrder(), serDe);
assertEquals(sk2.sketchStructure, UPDATABLE);
assertEquals(sk2.getN(), 0);
assertFalse(sk2.isReadOnly());
try { sk2.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk2.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
println(sk1.toString(true, true));
println("");
println(KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe));
}
@Test
public void checkHeapifySingleItem() {
final KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
sk1.update("A");
Memory mem = Memory.wrap(sk1.toByteArray());
KllMemoryValidate memVal = new KllMemoryValidate(mem, SketchType.ITEMS_SKETCH, serDe);
assertEquals(memVal.sketchStructure, COMPACT_SINGLE);
assertEquals(mem.getCapacity(), memVal.sketchBytes);
final KllItemsSketch<String> sk2 = KllItemsSketch.heapify(mem, Comparator.naturalOrder(), serDe);
assertEquals(sk2.sketchStructure, UPDATABLE);
assertEquals(sk2.getN(), 1);
assertFalse(sk2.isReadOnly());
assertEquals(sk2.getMinItem(), "A");
assertEquals(sk2.getMaxItem(), "A");
println(sk1.toString(true, true));
println("");
println(KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe));
}
@Test
public void checkHeapifyFewItems() {
final KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
sk1.update("A");
sk1.update("AB");
sk1.update("ABC");
Memory mem = Memory.wrap(sk1.toByteArray());
KllMemoryValidate memVal = new KllMemoryValidate(mem, SketchType.ITEMS_SKETCH, serDe);
assertEquals(memVal.sketchStructure, COMPACT_FULL);
assertEquals(mem.getCapacity(), memVal.sketchBytes);
println(sk1.toString(true, true));
println("");
println(KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe));
}
@Test
public void checkHeapifyManyItems() {
final KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
final int n = 109;
final int digits = Util.numDigits(n);
for (int i = 1; i <= n; i++) {
sk1.update(Util.intToFixedLengthString(i, digits));
}
Memory mem = Memory.wrap(sk1.toByteArray());
KllMemoryValidate memVal = new KllMemoryValidate(mem, SketchType.ITEMS_SKETCH, serDe);
assertEquals(memVal.sketchStructure, COMPACT_FULL);
assertEquals(mem.getCapacity(), memVal.sketchBytes);
println(sk1.toString(true, true));
println("");
println(KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe));
}
@Test
public void checkWrapCausingLevelsCompaction() {
final KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
final int n = 109;
final int digits = Util.numDigits(n);
for (int i = 1; i <= n; i++) {
sk1.update(Util.intToFixedLengthString(i, digits));
}
Memory mem = Memory.wrap(sk1.toByteArray());
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(mem, Comparator.naturalOrder(), serDe);
assertTrue(mem.isReadOnly());
assertTrue(sk2.isReadOnly());
assertFalse(sk2.isDirect()); //not off-heap
println(sk1.toString(true, true));
println("");
println(sk2.toString(true, true));
println("");
println(KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe));
}
@Test
public void checkExceptions() {
final KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
try { sk.getTotalItemsByteArr(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getTotalItemsNumBytes(); fail(); } catch (SketchesArgumentException e) { }
try { sk.setWritableMemory(null); fail(); } catch (SketchesArgumentException e) { }
byte[] byteArr = sk.toByteArray();
final KllItemsSketch<String> sk2 = KllItemsSketch.wrap(Memory.wrap(byteArr), Comparator.naturalOrder(), serDe);
try { sk2.incN(); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setItemsArray(null); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setItemsArrayAt(0, null); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setLevelZeroSorted(false); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setMaxItem(null); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setMinItem(null); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setMinK(0); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setN(0); fail(); } catch (SketchesArgumentException e) { }
}
@Test
public void checkSortedViewAfterReset() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
sk.update("1");
GenericSortedView<String> sv = sk.getSortedView();
String ssv = sv.getQuantile(1.0, INCLUSIVE);
assertEquals(ssv, "1");
sk.reset();
try { sk.getSortedView(); fail(); } catch (SketchesArgumentException e) { }
}
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,378 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllFloatsSketchIteratorTest.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.kll;
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.FloatsSortedViewIterator;
import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class KllFloatsSketchIteratorTest {
@Test
public void emptySketch() {
KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
QuantilesFloatsSketchIterator it = sketch.iterator();
Assert.assertFalse(it.next());
}
@Test
public void oneItemSketch() {
KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
sketch.update(1);
QuantilesFloatsSketchIterator it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getQuantile(), 1.0f);
Assert.assertEquals(it.getWeight(), 1);
Assert.assertFalse(it.next());
}
@Test
public void twoItemSketchForIterator() {
KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
sketch.update(1);
sketch.update(2);
QuantilesFloatsSketchIterator itr = sketch.iterator();
assertTrue(itr.next());
assertEquals(itr.getQuantile(), 2.0f);
assertEquals(itr.getWeight(), 1);
assertTrue(itr.next());
assertEquals(itr.getQuantile(), 1.0f);
assertEquals(itr.getWeight(), 1);
}
@Test
public void twoItemSketchForSortedViewIterator() {
KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
sketch.update(1);
sketch.update(2);
FloatsSortedViewIterator itr = sketch.getSortedView().iterator();
assertTrue(itr.next());
assertEquals(itr.getQuantile(), 1.0f);
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(), 2.0f);
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
public void bigSketches() {
for (int n = 1000; n < 100000; n += 2000) {
KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
for (int i = 0; i < n; i++) {
sketch.update(i);
}
QuantilesFloatsSketchIterator 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,379 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllMemoryValidateTest.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.kll;
import static org.apache.datasketches.kll.KllPreambleUtil.EMPTY_BIT_MASK;
import static org.apache.datasketches.kll.KllPreambleUtil.PREAMBLE_INTS_EMPTY_SINGLE;
import static org.apache.datasketches.kll.KllPreambleUtil.PREAMBLE_INTS_FULL;
import static org.apache.datasketches.kll.KllPreambleUtil.SERIAL_VERSION_EMPTY_FULL;
import static org.apache.datasketches.kll.KllPreambleUtil.SERIAL_VERSION_SINGLE;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryFamilyID;
import static org.apache.datasketches.kll.KllPreambleUtil.*;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryPreInts;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySerVer;
import static org.apache.datasketches.kll.KllSketch.SketchType.DOUBLES_SKETCH;
import static org.apache.datasketches.kll.KllSketch.SketchType.FLOATS_SKETCH;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
@SuppressWarnings("unused")
public class KllMemoryValidateTest {
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidFamily() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
byte[] byteArr = sk.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemoryFamilyID(wmem, Family.KLL.getID() - 1);
KllMemoryValidate memVal = new KllMemoryValidate(wmem, FLOATS_SKETCH);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidSerVer() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
byte[] byteArr = sk.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemorySerVer(wmem, SERIAL_VERSION_EMPTY_FULL - 1);
KllMemoryValidate memVal = new KllMemoryValidate(wmem, FLOATS_SKETCH);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidEmptyAndSingleFormat() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
sk.update(1);
byte[] byteArr = sk.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemoryEmptyFlag(wmem, true);
KllMemoryValidate memVal = new KllMemoryValidate(wmem, FLOATS_SKETCH);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidUpdatableAndSerVer() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
byte[] byteArr = sk.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemorySerVer(wmem, SERIAL_VERSION_SINGLE);
KllMemoryValidate memVal = new KllMemoryValidate(wmem, FLOATS_SKETCH);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidSingleAndPreInts() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
sk.update(1);
byte[] byteArr = sk.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemoryPreInts(wmem, PREAMBLE_INTS_FULL);
KllMemoryValidate memVal = new KllMemoryValidate(wmem, FLOATS_SKETCH);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidSingleAndSerVer() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
sk.update(1);
byte[] byteArr = sk.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemorySerVer(wmem, SERIAL_VERSION_EMPTY_FULL);
KllMemoryValidate memVal = new KllMemoryValidate(wmem, FLOATS_SKETCH);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidEmptyDoublesAndPreIntsFull() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance();
byte[] byteArr = sk.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemoryPreInts(wmem, PREAMBLE_INTS_FULL);
KllMemoryValidate memVal = new KllMemoryValidate(wmem, DOUBLES_SKETCH);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidSingleDoubleCompactAndSerVer() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance();
sk.update(1);
byte[] byteArr = sk.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemorySerVer(wmem, SERIAL_VERSION_EMPTY_FULL);
KllMemoryValidate memVal = new KllMemoryValidate(wmem, DOUBLES_SKETCH);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidDoubleUpdatableAndPreInts() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance();
byte[] byteArr = KllHelper.toByteArray(sk, true);
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemoryPreInts(wmem, PREAMBLE_INTS_EMPTY_SINGLE);
KllMemoryValidate memVal = new KllMemoryValidate(wmem, DOUBLES_SKETCH);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidFloatFullAndPreInts() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
sk.update(1); sk.update(2);
byte[] byteArr = sk.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemoryPreInts(wmem, PREAMBLE_INTS_EMPTY_SINGLE);
KllMemoryValidate memVal = new KllMemoryValidate(wmem, FLOATS_SKETCH);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidFloatUpdatableFullAndPreInts() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
sk.update(1); sk.update(2);
byte[] byteArr = KllHelper.toByteArray(sk, true);
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemoryPreInts(wmem, PREAMBLE_INTS_EMPTY_SINGLE);
KllMemoryValidate memVal = new KllMemoryValidate(wmem, FLOATS_SKETCH);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidDoubleCompactSingleAndPreInts() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance();
sk.update(1);
byte[] byteArr = sk.toByteArray();
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
setMemoryPreInts(wmem, PREAMBLE_INTS_FULL);//should be 2, single
KllMemoryValidate memVal = new KllMemoryValidate(wmem, DOUBLES_SKETCH);
}
}
| 2,380 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDirectFloatsSketchTest.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.kll;
import static org.apache.datasketches.kll.KllSketch.SketchType.FLOATS_SKETCH;
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 org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
public class KllDirectFloatsSketchTest {
private static final double PMF_EPS_FOR_K_8 = 0.35; // PMF rank error (epsilon) for k=8
private static final double PMF_EPS_FOR_K_128 = 0.025; // PMF rank error (epsilon) for k=128
private static final double PMF_EPS_FOR_K_256 = 0.013; // PMF rank error (epsilon) for k=256
private static final double NUMERIC_NOISE_TOLERANCE = 1E-6;
private static final DefaultMemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void empty() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0);
sketch.update(Float.NaN); // this must not change anything
assertTrue(sketch.isEmpty());
assertEquals(sketch.getN(), 0);
assertEquals(sketch.getNumRetained(), 0);
try { sketch.getRank(0.5f); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getQuantile(0.5); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getQuantiles(new double[] {0.0, 1.0}); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getPMF(new float[] {0}); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getCDF(new float[0]); fail(); } catch (SketchesArgumentException e) {}
assertNotNull(sketch.toString(true, true));
assertNotNull(sketch.toString());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void getQuantileInvalidArg() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0);
sketch.update(1);
sketch.getQuantile(-1.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void getQuantilesInvalidArg() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0);
sketch.update(1);
sketch.getQuantiles(new double[] {2.0});
}
@Test
public void oneValue() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0);
sketch.update(1);
assertFalse(sketch.isEmpty());
assertEquals(sketch.getN(), 1);
assertEquals(sketch.getNumRetained(), 1);
assertEquals(sketch.getRank(1, EXCLUSIVE), 0.0);
assertEquals(sketch.getRank(2, EXCLUSIVE), 1.0);
assertEquals(sketch.getMinItem(), 1f);
assertEquals(sketch.getMaxItem(), 1f);
assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 1f);
}
@Test
public void manyValuesEstimationMode() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0);
final int n = 1_000_000;
for (int i = 0; i < n; i++) {
sketch.update(i);
}
assertEquals(sketch.getN(), n);
// test getRank
for (int i = 0; i < n; i++) {
final double trueRank = (double) i / n;
assertEquals(sketch.getRank(i), trueRank, PMF_EPS_FOR_K_256, "for value " + i);
}
// test getPMF
final double[] pmf = sketch.getPMF(new float[] {n / 2.0f}); // split at median
assertEquals(pmf.length, 2);
assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256);
assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256);
assertEquals(sketch.getMinItem(), 0.0f); // min value is exact
assertEquals(sketch.getMaxItem(), n - 1.0f); // max value is exact
// check at every 0.1 percentage point
final double[] ranks = new double[1001];
final double[] reverseRanks = new double[1001]; // check that ordering doesn't matter
for (int i = 0; i <= 1000; i++) {
ranks[i] = (double) i / 1000;
reverseRanks[1000 - i] = ranks[i];
}
final float[] quantiles = sketch.getQuantiles(ranks);
final float[] reverseQuantiles = sketch.getQuantiles(reverseRanks);
float previousQuantile = 0.0f;
for (int i = 0; i <= 1000; i++) {
final float quantile = sketch.getQuantile(ranks[i]);
assertEquals(quantile, quantiles[i]);
assertEquals(quantile, reverseQuantiles[1000 - i]);
assertTrue(previousQuantile <= quantile);
previousQuantile = quantile;
}
}
@Test
public void getRankGetCdfGetPmfConsistency() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0);
final int n = 1000;
final float[] values = new float[n];
for (int i = 0; i < n; i++) {
sketch.update(i);
values[i] = i;
}
final double[] ranks = sketch.getCDF(values);
final double[] pmf = sketch.getPMF(values);
double sumPmf = 0;
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i]), NUMERIC_NOISE_TOLERANCE,
"rank vs CDF for value " + i);
sumPmf += pmf[i];
assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i);
}
sumPmf += pmf[n];
assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE);
assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE);
}
@Test
public void merge() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0);
final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(200, 0);
final int n = 10_000;
for (int i = 0; i < n; i++) {
sketch1.update(i * 1.0F);
sketch2.update((2 * n - i - 1) * 1.0F);
}
assertEquals(sketch1.getMinItem(), 0.0);
assertEquals(sketch1.getMaxItem(), (n - 1) * 1.0);
assertEquals(sketch2.getMinItem(), n * 1.0);
assertEquals(sketch2.getMaxItem(), (2 * n - 1) * 1.0);
sketch1.merge(sketch2);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), 2L * n);
assertEquals(sketch1.getMinItem(), 0.0);
assertEquals(sketch1.getMaxItem(), (2 * n - 1) * 1.0F);
assertEquals(sketch1.getQuantile(0.5), n * 1.0F, n * PMF_EPS_FOR_K_256);
}
@Test
public void mergeLowerK() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(256, 0);
final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(128, 0);
final int n = 10_000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
sketch2.update(2 * n - i - 1);
}
assertEquals(sketch1.getMinItem(), 0.0f);
assertEquals(sketch1.getMaxItem(), n - 1f);
assertEquals(sketch2.getMinItem(), n);
assertEquals(sketch2.getMaxItem(), 2f * n - 1f);
assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false));
assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true));
sketch1.merge(sketch2);
// sketch1 must get "contaminated" by the lower K in sketch2
assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false));
assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true));
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), 2 * n);
assertEquals(sketch1.getMinItem(), 0.0f);
assertEquals(sketch1.getMaxItem(), 2.0f * n - 1.0f);
assertEquals(sketch1.getQuantile(0.5), n, n * PMF_EPS_FOR_K_128);
}
@Test
public void mergeEmptyLowerK() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(256, 0);
final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(128, 0);
final int n = 10_000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
}
// rank error should not be affected by a merge with an empty sketch with lower K
final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true);
sketch1.merge(sketch2);
assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), n);
assertEquals(sketch1.getMinItem(), 0.0f);
assertEquals(sketch1.getMaxItem(), n - 1.0f);
assertEquals(sketch1.getQuantile(0.5), n / 2.0f, n / 2 * PMF_EPS_FOR_K_256);
//merge the other way
sketch2.merge(sketch1);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), n);
assertEquals(sketch1.getMinItem(), 0.0f);
assertEquals(sketch1.getMaxItem(), n - 1.0f);
assertEquals(sketch1.getQuantile(0.5), n / 2.0f, n / 2 * PMF_EPS_FOR_K_256);
}
@Test
public void mergeExactModeLowerK() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(256, 0);
final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(128, 0);
final int n = 10000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
}
sketch2.update(1);
// rank error should not be affected by a merge with a sketch in exact mode with lower K
final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true);
sketch1.merge(sketch2);
assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge);
}
@Test
public void mergeMinMinValueFromOther() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0);
final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(200, 0);
sketch1.update(1);
sketch2.update(2);
sketch2.merge(sketch1);
assertEquals(sketch2.getMinItem(), 1.0F);
}
@Test
public void mergeMinAndMaxFromOther() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0);
final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(200, 0);
for (int i = 1; i <= 1_000_000; i++) {
sketch1.update(i);
}
sketch2.merge(sketch1);
assertEquals(sketch2.getMinItem(), 1F);
assertEquals(sketch2.getMaxItem(), 1_000_000F);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void kTooSmall() {
getUpdatableDirectFloatSketch(KllSketch.DEFAULT_M - 1, 0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void kTooLarge() {
getUpdatableDirectFloatSketch(KllSketch.MAX_K + 1, 0);
}
@Test
public void minK() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(KllSketch.DEFAULT_M, 0);
for (int i = 0; i < 1000; i++) {
sketch.update(i);
}
assertEquals(sketch.getK(), KllSketch.DEFAULT_M);
assertEquals(sketch.getQuantile(0.5), 500, 500 * PMF_EPS_FOR_K_8);
}
@Test
public void maxK() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(KllSketch.MAX_K, 0);
for (int i = 0; i < 1000; i++) {
sketch.update(i);
}
assertEquals(sketch.getK(), KllSketch.MAX_K);
assertEquals(sketch.getQuantile(0.5), 500, 500 * PMF_EPS_FOR_K_256);
}
@Test
public void serializeDeserializeEmptyViaCompactHeapify() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0);
final byte[] bytes = sketch1.toByteArray(); //compact
final KllFloatsSketch sketch2 = KllFloatsSketch.heapify(Memory.wrap(bytes));
assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(false));
assertTrue(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained());
assertEquals(sketch2.getN(), sketch1.getN());
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
try { sketch2.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch2.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sketch2.currentSerializedSizeBytes(false),
sketch1.currentSerializedSizeBytes(false));
}
@Test
public void serializeDeserializeEmptyViaUpdatableWritableWrap() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0);
final byte[] bytes = KllHelper.toByteArray(sketch1, true); //updatable
final KllFloatsSketch sketch2 =
KllFloatsSketch.writableWrap(WritableMemory.writableWrap(bytes),memReqSvr);
assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true));
assertTrue(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained());
assertEquals(sketch2.getN(), sketch1.getN());
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
try { sketch2.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch2.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sketch2.currentSerializedSizeBytes(true),
sketch1.currentSerializedSizeBytes(true));
}
@Test
public void serializeDeserializeOneValueViaCompactHeapify() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0);
sketch1.update(1);
final byte[] bytes = sketch1.toByteArray(); //compact
final KllFloatsSketch sketch2 = KllFloatsSketch.heapify(Memory.wrap(bytes));
assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(false));
assertFalse(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), 1);
assertEquals(sketch2.getN(), 1);
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
assertTrue(Float.isFinite(sketch2.getMinItem()));
assertTrue(Float.isFinite(sketch2.getMaxItem()));
assertEquals(sketch2.currentSerializedSizeBytes(false), 8 + Float.BYTES);
}
@Test
public void serializeDeserializeOneValueViaUpdatableWritableWrap() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0);
sketch1.update(1);
final byte[] bytes = KllHelper.toByteArray(sketch1, true); //updatable
final KllFloatsSketch sketch2 =
KllFloatsSketch.writableWrap(WritableMemory.writableWrap(bytes),memReqSvr);
assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true));
assertFalse(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), 1);
assertEquals(sketch2.getN(), 1);
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
assertEquals(sketch2.getMinItem(), 1.0f);
assertEquals(sketch2.getMaxItem(), 1.0f);
assertEquals(sketch2.currentSerializedSizeBytes(false), 8 + Float.BYTES);
assertEquals(sketch2.currentSerializedSizeBytes(true), bytes.length);
}
@Test
public void serializeDeserializeFullViaCompactHeapify() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 1000);
final byte[] byteArr1 = sketch1.toByteArray(); //compact
final KllFloatsSketch sketch2 = KllFloatsSketch.heapify(Memory.wrap(byteArr1));
assertEquals(byteArr1.length, sketch1.currentSerializedSizeBytes(false));
assertFalse(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained());
assertEquals(sketch2.getN(), sketch1.getN());
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
assertEquals(sketch2.getMinItem(), sketch1.getMinItem());
assertEquals(sketch2.getMaxItem(), sketch1.getMaxItem());
assertEquals(sketch2.currentSerializedSizeBytes(false), sketch1.currentSerializedSizeBytes(false));
}
@Test
public void serializeDeserializeFullViaUpdatableWritableWrap() {
final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0);
final int n = 1000;
for (int i = 1; i <= n; i++) {
sketch1.update(i);
}
final byte[] bytes = KllHelper.toByteArray(sketch1, true); //updatable
final KllFloatsSketch sketch2 =
KllFloatsSketch.writableWrap(WritableMemory.writableWrap(bytes), memReqSvr);
assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true));
assertFalse(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained());
assertEquals(sketch2.getN(), sketch1.getN());
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
assertEquals(sketch2.getMinItem(), sketch1.getMinItem());
assertEquals(sketch2.getMaxItem(), sketch1.getMaxItem());
assertEquals(sketch2.currentSerializedSizeBytes(true), sketch1.currentSerializedSizeBytes(true));
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void outOfOrderSplitPoints() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0);
sketch.update(0);
sketch.getCDF(new float[] {1, 0});
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void nanSplitPoint() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0);
sketch.update(0);
sketch.getCDF(new float[] {Float.NaN});
}
@Test
public void getQuantiles() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0);
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 checkSimpleMergeDirect() { //used for troubleshooting
int k = 20;
int n1 = 21;
int n2 = 43;
KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(k);
KllFloatsSketch sk2 = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= n1; i++) {
sk1.update(i);
}
for (int i = 1; i <= n2; i++) {
sk2.update(i + 100);
}
println("SK1:");
println(sk1.toString(true, true));
println("SK2:");
println(sk2.toString(true, true));
WritableMemory wmem1 = WritableMemory.writableWrap(KllHelper.toByteArray(sk1, true));
WritableMemory wmem2 = WritableMemory.writableWrap(KllHelper.toByteArray(sk2, true));
KllFloatsSketch dsk1 = KllFloatsSketch.writableWrap(wmem1, memReqSvr);
KllFloatsSketch dsk2 = KllFloatsSketch.writableWrap(wmem2, memReqSvr);
println("BEFORE MERGE");
println(dsk1.toString(true, true));
dsk1.merge(dsk2);
println("AFTER MERGE");
println(dsk1.toString(true, true));
}
@Test
public void checkSketchInitializeDirectFloatUpdatableMem() {
int k = 20; //don't change this
KllFloatsSketch sk;
KllFloatsSketch sk2;
byte[] compBytes;
WritableMemory wmem;
println("#### CASE: FLOAT FULL DIRECT FROM UPDATABLE");
sk2 = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk2.update(i); }
//println(sk2.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
println(KllPreambleUtil.toString(compBytes, FLOATS_SKETCH, true));
sk = KllFloatsSketch.writableWrap(wmem, memReqSvr);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT EMPTY HEAPIFIED FROM UPDATABLE");
sk2 = KllFloatsSketch.newHeapInstance(k);
//println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
println(KllPreambleUtil.toString(compBytes, FLOATS_SKETCH, true));
sk = KllFloatsSketch.writableWrap(wmem, memReqSvr);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT SINGLE HEAPIFIED FROM UPDATABLE");
sk2 = KllFloatsSketch.newHeapInstance(k);
sk2.update(1);
//println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
println(KllPreambleUtil.toString(compBytes, FLOATS_SKETCH, true));
sk = KllFloatsSketch.writableWrap(wmem, memReqSvr);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test
public void checkGetWritableMemory() {
final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 200);
assertEquals(sketch.getK(), 200);
assertEquals(sketch.getN(), 200);
assertFalse(sketch.isEmpty());
assertTrue(sketch.isMemoryUpdatableFormat());
assertFalse(sketch.isEstimationMode());
assertTrue(sketch.isFloatsSketch());
assertFalse(sketch.isLevelZeroSorted());
assertFalse(sketch.isDoublesSketch());
final WritableMemory wmem = sketch.getWritableMemory();
final KllFloatsSketch sk = KllHeapFloatsSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), 200);
assertEquals(sk.getN(), 200);
assertFalse(sk.isEmpty());
assertFalse(sk.isMemoryUpdatableFormat());
assertFalse(sk.isEstimationMode());
assertTrue(sk.isFloatsSketch());
assertFalse(sk.isLevelZeroSorted());
assertFalse(sk.isDoublesSketch());
}
@Test
public void checkReset() {
WritableMemory dstMem = WritableMemory.allocate(3000);
KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(20, dstMem, memReqSvr);
for (int i = 1; i <= 100; i++) { sk.update(i); }
long n1 = sk.getN();
float min1 = sk.getMinItem();
float max1 = sk.getMaxItem();
sk.reset();
for (int i = 1; i <= 100; i++) { sk.update(i); }
long n2 = sk.getN();
float min2 = sk.getMinItem();
float max2 = sk.getMaxItem();
assertEquals(n2, n1);
assertEquals(min2, min1);
assertEquals(max2, max1);
}
@Test
public void checkHeapify() {
WritableMemory dstMem = WritableMemory.allocate(6000);
KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(20, dstMem, memReqSvr);
for (int i = 1; i <= 100; i++) { sk.update(i); }
KllFloatsSketch sk2 = KllHeapFloatsSketch.heapifyImpl(dstMem);
assertEquals(sk2.getMinItem(), 1.0);
assertEquals(sk2.getMaxItem(), 100.0);
}
@Test
public void checkMergeKllFloatsSketch() {
WritableMemory dstMem = WritableMemory.allocate(6000);
KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(20, dstMem, memReqSvr);
for (int i = 1; i <= 21; i++) { sk.update(i); }
KllFloatsSketch sk2 = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++ ) { sk2.update(i + 100); }
sk.merge(sk2);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getMaxItem(), 121.0);
}
@Test
public void checkReverseMergeKllFloatsSketch() {
WritableMemory dstMem = WritableMemory.allocate(6000);
KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(20, dstMem, memReqSvr);
for (int i = 1; i <= 21; i++) { sk.update(i); }
KllFloatsSketch sk2 = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++ ) { sk2.update(i + 100); }
sk2.merge(sk);
assertEquals(sk2.getMinItem(), 1.0);
assertEquals(sk2.getMaxItem(), 121.0);
}
@Test
public void checkWritableWrapOfCompactForm() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++ ) { sk.update(i); }
WritableMemory srcMem = WritableMemory.writableWrap(sk.toByteArray());
KllFloatsSketch sk2 = KllFloatsSketch.writableWrap(srcMem, memReqSvr);
assertEquals(sk2.getMinItem(), 1.0F);
assertEquals(sk2.getMaxItem(), 21.0F);
}
@Test
public void checkReadOnlyExceptions() {
int k = 20;
float[] fltArr = new float[0];
float fltV = 1.0f;
int idx = 1;
boolean bool = true;
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k);
KllFloatsSketch sk2 = KllFloatsSketch.wrap(Memory.wrap(sk.toByteArray()));
try { sk2.incN(); fail(); } catch (SketchesArgumentException e) { }
try { sk2.incNumLevels(); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setFloatItemsArray(fltArr); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setFloatItemsArrayAt(idx, fltV); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setLevelZeroSorted(bool); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setMaxItem(fltV); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setMinItem(fltV); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setMinK(idx); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setN(idx); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setNumLevels(idx); fail(); } catch (SketchesArgumentException e) { }
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMergeExceptions() {
KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(20);
WritableMemory srcMem1 = WritableMemory.writableWrap(sk1.toByteArray());
KllFloatsSketch sk2 = KllFloatsSketch.writableWrap(srcMem1, memReqSvr);
sk2.merge(sk1);
}
@Test
public void checkMergeExceptionsWrongType() {
KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(20);
KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(20);
try { sk1.merge(sk2); fail(); } catch (ClassCastException e) { }
try { sk2.merge(sk1); fail(); } catch (ClassCastException e) { }
}
private static KllFloatsSketch getUpdatableDirectFloatSketch(final int k, final int n) {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= n; i++) { sk.update(i); }
byte[] byteArr = KllHelper.toByteArray(sk, true);
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
KllFloatsSketch dfsk = KllFloatsSketch.writableWrap(wmem, memReqSvr);
return dfsk;
}
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,381 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllMiscDirectFloatsTest.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.kll;
import static org.apache.datasketches.kll.KllSketch.SketchType.FLOATS_SKETCH;
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.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.quantilescommon.FloatsSortedView;
import org.apache.datasketches.quantilescommon.FloatsSortedViewIterator;
import org.testng.annotations.Test;
public class KllMiscDirectFloatsTest {
static final String LS = System.getProperty("line.separator");
private static final DefaultMemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void checkBounds() {
final KllFloatsSketch kll = getDirectFloatsSketch(200, 0);
for (int i = 0; i < 1000; i++) {
kll.update(i);
}
final double eps = kll.getNormalizedRankError(false);
final float est = kll.getQuantile(0.5);
final float ub = kll.getQuantileUpperBound(0.5);
final float lb = kll.getQuantileLowerBound(0.5);
assertEquals(ub, kll.getQuantile(.5 + eps));
assertEquals(lb, kll.getQuantile(0.5 - eps));
println("Ext : " + est);
println("UB : " + ub);
println("LB : " + lb);
final double rest = kll.getRank(est);
final double restUB = kll.getRankUpperBound(rest);
final double restLB = kll.getRankLowerBound(rest);
assertTrue(restUB - rest < (2 * eps));
assertTrue(rest - restLB < (2 * eps));
}
@Test
public void checkMisc() {
final int k = 8;
final KllFloatsSketch sk = getDirectFloatsSketch(k, 0);
try { sk.getPartitionBoundaries(10); fail(); } catch (SketchesArgumentException e) {}
for (int i = 0; i < 20; i++) { sk.update(i); }
final float[] items = sk.getFloatItemsArray();
assertEquals(items.length, 16);
final int[] levels = sk.getLevelsArray(sk.sketchStructure);
assertEquals(levels.length, 3);
assertEquals(sk.getNumLevels(), 2);
}
//@Test //enable static println(..) for visual checking
public void visualCheckToString() {
final int k = 20;
final KllFloatsSketch sk = getDirectFloatsSketch(k, 0);
for (int i = 0; i < 10; i++) { sk.update(i + 1); }
println(sk.toString(true, true));
final KllFloatsSketch sk2 = getDirectFloatsSketch(k, 0);
for (int i = 0; i < 400; i++) { sk2.update(i + 1); }
println("\n" + sk2.toString(true, true));
sk2.merge(sk);
final String s2 = sk2.toString(true, true);
println(LS + s2);
}
@Test
public void viewDirectCompactions() {
int k = 20;
int u = 108;
KllFloatsSketch sk = getDirectFloatsSketch(k, 0);
for (int i = 1; i <= u; i++) {
sk.update(i);
if (sk.levelsArr[0] == 0) {
println(sk.toString(true, true));
sk.update(++i);
println(sk.toString(true, true));
assertEquals(sk.getFloatItemsArray()[sk.levelsArr[0]], i);
}
}
}
@Test
public void viewCompactionAndSortedView() {
int k = 20;
KllFloatsSketch sk = getDirectFloatsSketch(k, 0);
show(sk, 20);
FloatsSortedView sv = sk.getSortedView();
FloatsSortedViewIterator itr = sv.iterator();
printf("%12s%12s\n", "Value", "CumWeight");
while (itr.next()) {
float v = itr.getQuantile();
long wt = itr.getWeight();
printf("%12.1f%12d\n", v, wt);
}
}
private static void show(final KllFloatsSketch sk, int limit) {
int i = (int) sk.getN();
for ( ; i < limit; i++) { sk.update(i + 1); }
println(sk.toString(true, true));
}
@Test
public void checkSketchInitializeFloatHeap() {
int k = 20; //don't change this
KllFloatsSketch sk;
//println("#### CASE: FLOAT FULL HEAP");
sk = getDirectFloatsSketch(k, 0);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
//println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0F);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
//println("#### CASE: FLOAT HEAP EMPTY");
sk = getDirectFloatsSketch(k, 0);
//println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
//println("#### CASE: FLOAT HEAP SINGLE");
sk = getDirectFloatsSketch(k, 0);
sk.update(1);
//println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0F);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test
public void checkSketchInitializeFloatHeapifyCompactMem() {
int k = 20; //don't change this
KllFloatsSketch sk;
KllFloatsSketch sk2;
byte[] compBytes;
WritableMemory wmem;
//println("#### CASE: FLOAT FULL HEAPIFIED FROM COMPACT");
sk2 = getDirectFloatsSketch(k, 0);
for (int i = 1; i <= k + 1; i++) { sk2.update(i); }
//println(sk.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem));
sk = KllFloatsSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0F);
assertEquals(sk.getMinItem(), 1.0f);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
//println("#### CASE: FLOAT EMPTY HEAPIFIED FROM COMPACT");
sk2 = getDirectFloatsSketch(k, 0);
//println(sk.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem));
sk = KllFloatsSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
//println("#### CASE: FLOAT SINGLE HEAPIFIED FROM COMPACT");
sk2 = getDirectFloatsSketch(k, 0);
sk2.update(1);
//println(sk2.toString(true, true));
compBytes = sk2.toByteArray();
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem));
sk = KllFloatsSketch.heapify(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0F);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test
public void checkSketchInitializeFloatHeapifyUpdatableMem() {
int k = 20; //don't change this
KllFloatsSketch sk;
KllFloatsSketch sk2;
byte[] compBytes;
WritableMemory wmem;
//println("#### CASE: FLOAT FULL HEAPIFIED FROM UPDATABLE");
sk2 = getDirectFloatsSketch(k, 0);
for (int i = 1; i <= k + 1; i++) { sk2.update(i); }
//println(sk2.toString(true, true));
compBytes = KllHelper.toByteArray(sk2,true);
wmem = WritableMemory.writableWrap(compBytes);
sk = KllHeapFloatsSketch.heapifyImpl(wmem);
//println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), 21.0F);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
// println("#### CASE: FLOAT EMPTY HEAPIFIED FROM UPDATABLE");
sk2 = getDirectFloatsSketch(k, 0);
//println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem));
sk = KllHeapFloatsSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
//println("#### CASE: FLOAT SINGLE HEAPIFIED FROM UPDATABLE");
sk2 = getDirectFloatsSketch(k, 0);
sk2.update(1);
//println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2,true);
wmem = WritableMemory.writableWrap(compBytes);
//println(KllPreambleUtil.toString(wmem));
sk = KllHeapFloatsSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getFloatItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), 1.0F);
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test
public void checkMemoryToStringFloatUpdatable() {
int k = 20; //don't change this
KllFloatsSketch sk;
KllFloatsSketch sk2;
byte[] upBytes;
byte[] upBytes2;
WritableMemory wmem;
String s;
println("#### CASE: FLOAT FULL UPDATABLE");
sk = getDirectFloatsSketch(k, 0);
for (int i = 1; i <= k + 1; i++) { sk.update(i); }
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllFloatsSketch.writableWrap(wmem, memReqSvr);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(upBytes, upBytes2);
println("#### CASE: FLOAT EMPTY UPDATABLE");
sk = getDirectFloatsSketch(k, 0);
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllFloatsSketch.writableWrap(wmem, memReqSvr);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(upBytes, upBytes2);
println("#### CASE: FLOAT SINGLE UPDATABL");
sk = getDirectFloatsSketch(k, 0);
sk.update(1);
upBytes = KllHelper.toByteArray(sk, true);
wmem = WritableMemory.writableWrap(upBytes);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllFloatsSketch.writableWrap(wmem, memReqSvr);
upBytes2 = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(upBytes2);
s = KllPreambleUtil.toString(wmem, FLOATS_SKETCH, true);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(upBytes, upBytes2);
}
@Test
public void checkSimpleMerge() {
int k = 20;
int n1 = 21;
int n2 = 21;
KllFloatsSketch sk1 = getDirectFloatsSketch(k, 0);
KllFloatsSketch sk2 = getDirectFloatsSketch(k, 0);
for (int i = 1; i <= n1; i++) {
sk1.update(i);
}
for (int i = 1; i <= n2; i++) {
sk2.update(i + 100);
}
println(sk1.toString(true, true));
println(sk2.toString(true, true));
sk1.merge(sk2);
println(sk1.toString(true, true));
assertEquals(sk1.getMaxItem(), 121.0F);
assertEquals(sk1.getMinItem(), 1.0F);
}
@Test
public void checkSizes() {
KllFloatsSketch sk = getDirectFloatsSketch(20, 0);
for (int i = 1; i <= 21; i++) { sk.update(i); }
//println(sk.toString(true, true));
byte[] byteArr1 = KllHelper.toByteArray(sk, true);
int size1 = sk.currentSerializedSizeBytes(true);
assertEquals(size1, byteArr1.length);
byte[] byteArr2 = sk.toByteArray();
int size2 = sk.currentSerializedSizeBytes(false);
assertEquals(size2, byteArr2.length);
}
@Test
public void checkNewInstance() {
int k = 200;
WritableMemory dstMem = WritableMemory.allocate(3000);
KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(k, dstMem, memReqSvr);
for (int i = 1; i <= 10_000; i++) {sk.update(i); }
assertEquals(sk.getMinItem(), 1.0F);
assertEquals(sk.getMaxItem(), 10000.0F);
//println(sk.toString(true, true));
}
@Test
public void checkDifferentM() {
int k = 20;
int m = 4;
WritableMemory dstMem = WritableMemory.allocate(1000);
KllFloatsSketch sk = KllDirectFloatsSketch.newDirectUpdatableInstance(k, m, dstMem, memReqSvr);
for (int i = 1; i <= 200; i++) {sk.update(i); }
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getMaxItem(), 200.0);
}
private static KllFloatsSketch getDirectFloatsSketch(final int k, final int n) {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= n; i++) { sk.update(i); }
byte[] byteArr = KllHelper.toByteArray(sk, true);
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
KllFloatsSketch dfsk = KllFloatsSketch.writableWrap(wmem, memReqSvr);
return dfsk;
}
@Test
public void printlnTest() {
String s = "PRINTING: printf in " + this.getClass().getName();
println(s);
printf("%s\n", s);
}
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,382 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDoublesSketchSerDeTest.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.kll;
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.memory.Memory;
import org.testng.annotations.Test;
public class KllDoublesSketchSerDeTest {
@Test
public void serializeDeserializeEmpty() {
final KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance();
//from heap -> byte[] -> heap
final byte[] bytes = sk1.toByteArray();
final KllDoublesSketch sk2 = KllDoublesSketch.heapify(Memory.wrap(bytes));
assertEquals(bytes.length, sk1.getSerializedSizeBytes());
assertTrue(sk2.isEmpty());
assertEquals(sk2.getNumRetained(), sk1.getNumRetained());
assertEquals(sk2.getN(), sk1.getN());
assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
try { sk2.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sk2.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap
final KllDoublesSketch sk3 = KllDoublesSketch.wrap(Memory.wrap(bytes));
assertTrue(sk3.isEmpty());
assertEquals(sk3.getNumRetained(), sk1.getNumRetained());
assertEquals(sk3.getN(), sk1.getN());
assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
try { sk3.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sk3.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap -> byte[] -> compare byte[]
final byte[] bytes2 = sk3.toByteArray();
assertEquals(bytes, bytes2);
}
@Test
public void serializeDeserializeOneValue() {
final KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance();
sk1.update(1);
//from heap -> byte[] -> heap
final byte[] bytes = sk1.toByteArray();
final KllDoublesSketch sk2 = KllDoublesSketch.heapify(Memory.wrap(bytes));
assertEquals(bytes.length, sk1.getSerializedSizeBytes());
assertFalse(sk2.isEmpty());
assertEquals(sk2.getNumRetained(), 1);
assertEquals(sk2.getN(), 1);
assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk2.getMinItem(), 1.0);
assertEquals(sk2.getMaxItem(), 1.0);
assertEquals(sk2.getSerializedSizeBytes(), Long.BYTES + Double.BYTES);
//from heap -> byte[] -> off heap
final KllDoublesSketch sk3 = KllDoublesSketch.wrap(Memory.wrap(bytes));
assertFalse(sk3.isEmpty());
assertEquals(sk3.getNumRetained(), 1);
assertEquals(sk3.getN(), 1);
assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk3.getMinItem(), 1.0);
assertEquals(sk3.getMaxItem(), 1.0);
assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap -> byte[] -> compare byte[]
final byte[] bytes2 = sk3.toByteArray();
assertEquals(bytes, bytes2);
}
@Test
public void serializeDeserializeMultipleValues() {
final KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance();
final int n = 1000;
for (int i = 0; i < n; i++) {
sk1.update(i);
}
assertEquals(sk1.getMinItem(), 0.0);
assertEquals(sk1.getMaxItem(), 999.0);
//from heap -> byte[] -> heap
final byte[] bytes = sk1.toByteArray();
final KllDoublesSketch sk2 = KllDoublesSketch.heapify(Memory.wrap(bytes));
assertEquals(bytes.length, sk1.getSerializedSizeBytes());
assertFalse(sk2.isEmpty());
assertEquals(sk2.getNumRetained(), sk1.getNumRetained());
assertEquals(sk2.getN(), sk1.getN());
assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk2.getMinItem(), sk1.getMinItem());
assertEquals(sk2.getMaxItem(), sk1.getMaxItem());
assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap
final KllDoublesSketch sk3 = KllDoublesSketch.wrap(Memory.wrap(bytes));
assertFalse(sk3.isEmpty());
assertEquals(sk3.getNumRetained(), sk1.getNumRetained());
assertEquals(sk3.getN(), sk1.getN());
assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk3.getMinItem(), sk1.getMinItem());
assertEquals(sk3.getMaxItem(), sk1.getMaxItem());
assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap -> byte[] -> compare byte[]
final byte[] bytes2 = sk3.toByteArray();
assertEquals(bytes, bytes2);
}
}
| 2,383 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllMiscItemsTest.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.kll;
import static org.apache.datasketches.kll.KllSketch.SketchType.ITEMS_SKETCH;
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.Comparator;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.Util;
import org.apache.datasketches.kll.KllItemsSketchSortedView.KllItemsSketchSortedViewIterator;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
public class KllMiscItemsTest {
static final String LS = System.getProperty("line.separator");
public ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
@Test
public void checkSortedViewConstruction() {
final KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
final int n = 20;
final int digits = Util.numDigits(n);
for (int i = 1; i <= n; i++) {
sk.update(Util.intToFixedLengthString(i, digits));
}
KllItemsSketchSortedView<String> sv = sk.getSortedView();
long[] cumWeights = sv.getCumulativeWeights();
String[] values = sv.getQuantiles();
assertEquals(cumWeights.length, 20);
assertEquals(values.length, 20);
for (int i = 0; i < 20; i++) {
assertEquals(cumWeights[i], i + 1);
assertEquals(values[i], Util.intToFixedLengthString(i + 1, digits));
}
}
@Test //set static enablePrinting = true for visual checking
public void checkBounds() {
final KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
final int n = 1000;
final int digits = Util.numDigits(n);
for (int i = 1; i <= n; i++) {
sk.update(Util.intToFixedLengthString(i, digits));
}
final double eps = sk.getNormalizedRankError(false);
final String est = sk.getQuantile(0.5);
final String ub = sk.getQuantileUpperBound(0.5);
final String lb = sk.getQuantileLowerBound(0.5);
assertEquals(ub, sk.getQuantile(.5 + eps));
assertEquals(lb, sk.getQuantile(0.5 - eps));
println("Ext : " + est);
println("UB : " + ub);
println("LB : " + lb);
final double rest = sk.getRank(est);
final double restUB = sk.getRankUpperBound(rest);
final double restLB = sk.getRankLowerBound(rest);
assertTrue(restUB - rest < (2 * eps));
assertTrue(rest - restLB < (2 * eps));
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions1() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(6, (byte)3); //corrupt with odd M
KllItemsSketch.heapify(wmem, Comparator.naturalOrder(), serDe);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions2() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(0, (byte)1); //corrupt preamble ints, should be 2
KllItemsSketch.heapify(wmem, Comparator.naturalOrder(), serDe);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions3() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sk.update("1");
sk.update("2");
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(0, (byte)1); //corrupt preamble ints, should be 5
KllItemsSketch.heapify(wmem, Comparator.naturalOrder(), serDe);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions4() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(1, (byte)0); //corrupt SerVer, should be 1 or 2
KllItemsSketch.heapify(wmem, Comparator.naturalOrder(), serDe);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkHeapifyExceptions5() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
wmem.putByte(2, (byte)0); //corrupt FamilyID, should be 15
KllItemsSketch.heapify(wmem, Comparator.naturalOrder(), serDe);
}
@Test //set static enablePrinting = true for visual checking
public void checkMisc() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) {} //empty
println(sk.toString(true, true));
final int n = 21;
final int digits = Util.numDigits(n);
for (int i = 1; i <= n; i++) {
sk.update(Util.intToFixedLengthString(i, digits));
}
println(sk.toString(true, true));
sk.toByteArray();
final String[] items = sk.getTotalItemsArray();
assertEquals(items.length, 33);
final int[] levels = sk.getLevelsArray(sk.sketchStructure);
assertEquals(levels.length, 3);
assertEquals(sk.getNumLevels(), 2);
}
//@Test //set static enablePrinting = true for visual checking
public void visualCheckToString() {
final KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
int n = 21;
int digits = 3;
for (int i = 1; i <= n; i++) { sk.update(Util.intToFixedLengthString(i, digits)); }
println(sk.toString(true, true));
assertEquals(sk.getNumLevels(), 2);
assertEquals(sk.getMinItem()," 1");
assertEquals(sk.getMaxItem()," 21");
assertEquals(sk.getNumRetained(), 11);
final KllItemsSketch<String> sk2 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
n = 400;
digits = 3;
for (int i = 101; i <= n + 100; i++) { sk2.update(Util.intToFixedLengthString(i, digits)); }
println(LS + sk2.toString(true, true));
assertEquals(sk2.getNumLevels(), 5);
assertEquals(sk2.getMinItem(), "101");
assertEquals(sk2.getMaxItem(), "500");
assertEquals(sk2.getNumRetained(), 52);
sk2.merge(sk);
println(LS + sk2.toString(true, true));
assertEquals(sk2.getNumLevels(), 5);
assertEquals(sk2.getMinItem()," 1");
assertEquals(sk2.getMaxItem(), "500");
assertEquals(sk2.getNumRetained(), 56);
}
@Test //set static enablePrinting = true for visual checking
public void viewHeapCompactions() {
int k = 20;
int n = 108;
int digits = Util.numDigits(n);
int compaction = 0;
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
for (int i = 1; i <= n; i++) {
sk.update(Util.intToFixedLengthString(i, digits));
if (sk.levelsArr[0] == 0) {
println(LS + "#<<< BEFORE COMPACTION # " + (++compaction) + " >>>");
println(sk.toString(true, true));
sk.update(Util.intToFixedLengthString(++i, digits));
println(LS + "#<<< AFTER COMPACTION # " + (compaction) + " >>>");
println(sk.toString(true, true));
assertEquals(sk.getTotalItemsArray()[sk.levelsArr[0]], Util.intToFixedLengthString(i, digits));
}
}
}
@Test //set static enablePrinting = true for visual checking
public void viewCompactionAndSortedView() {
final int n = 43;
final int digits = Util.numDigits(n);
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
for (int i = 1; i <= n; i++) { sk.update(Util.intToFixedLengthString(i, digits)); }
println(sk.toString(true, true));
KllItemsSketchSortedView<String> sv = sk.getSortedView();
KllItemsSketchSortedViewIterator<String> itr = sv.iterator();
println("### SORTED VIEW");
printf("%12s%12s\n", "Value", "CumWeight");
while (itr.next()) {
String v = itr.getQuantile();
long wt = itr.getWeight();
printf("%12s%12d\n", v, wt);
}
}
@Test
public void checkGrowLevels() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
final int n = 21;
final int digits = Util.numDigits(n);
for (int i = 1; i <= n; i++) { sk.update(Util.intToFixedLengthString(i, digits)); }
assertEquals(sk.getNumLevels(), 2);
assertEquals(sk.getTotalItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure)[2], 33);
}
@Test //set static enablePrinting = true for visual checking
public void checkSketchInitializeItemsHeap() {
int k = 20; //don't change this
int n = 21;
final int digits = Util.numDigits(n);
KllItemsSketch<String> sk;
println("#### CASE: FLOAT FULL HEAP");
sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
for (int i = 1; i <= n; i++) { sk.update(Util.intToFixedLengthString(i, digits)); }
println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), n);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getTotalItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), "21");
assertEquals(sk.getMinItem(), " 1");
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT HEAP EMPTY");
sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getTotalItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT HEAP SINGLE");
sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
sk.update("1");
println(sk.toString(true, true));
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getTotalItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), "1");
assertEquals(sk.getMinItem(), "1");
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test //set static enablePrinting = true for visual checking
public void checkSketchInitializeItemsHeapifyCompactMem() {
int k = 20; //don't change this
int n = 21;
final int digits = Util.numDigits(n);
KllItemsSketch<String> sk;
KllItemsSketch<String> sk2;
byte[] compBytes;
Memory mem;
println("#### CASE: FLOAT FULL HEAPIFIED FROM COMPACT");
sk2 = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
for (int i = 1; i <= n; i++) { sk2.update(Util.intToFixedLengthString(i, digits)); }
println(sk2.toString(true, true));
compBytes = sk2.toByteArray();
mem = Memory.wrap(compBytes);
println(KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe));
sk = KllItemsSketch.heapify(mem, Comparator.naturalOrder(), serDe);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getTotalItemsArray().length, 33);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3);
assertEquals(sk.getMaxItem(), "21");
assertEquals(sk.getMinItem(), " 1");
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT EMPTY HEAPIFIED FROM COMPACT");
sk2 = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
//println(sk.toString(true, true));
compBytes = sk2.toByteArray();
mem = Memory.wrap(compBytes);
println(KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe));
sk = KllItemsSketch.heapify(mem, Comparator.naturalOrder(), serDe);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getTotalItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) { }
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) { }
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: FLOAT SINGLE HEAPIFIED FROM COMPACT");
sk2 = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
sk2.update("1");
//println(sk2.toString(true, true));
compBytes = sk2.toByteArray();
mem = Memory.wrap(compBytes);
println(KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe));
sk = KllItemsSketch.heapify(mem, Comparator.naturalOrder(), serDe);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getTotalItemsArray().length, 20);
assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2);
assertEquals(sk.getMaxItem(), "1");
assertEquals(sk.getMinItem(), "1");
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
//public void checkSketchInitializeFloatHeapifyUpdatableMem() Not Supported
@Test //set static enablePrinting = true for visual checking
public void checkMemoryToStringItemsCompact() {
int k = 20; //don't change this
int n = 21;
final int digits = Util.numDigits(n);
KllItemsSketch<String> sk;
KllItemsSketch<String> sk2;
byte[] compBytes;
byte[] compBytes2;
Memory mem;
String s;
println("#### CASE: FLOAT FULL COMPACT");
sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
for (int i = 1; i <= n; i++) { sk.update(Util.intToFixedLengthString(i, digits)); }
compBytes = sk.toByteArray();
mem = Memory.wrap(compBytes);
s = KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllItemsSketch.heapify(mem, Comparator.naturalOrder(), serDe);
compBytes2 = sk2.toByteArray();
mem = Memory.wrap(compBytes2);
s = KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(compBytes, compBytes2);
println("#### CASE: FLOAT EMPTY COMPACT");
sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
compBytes = sk.toByteArray();
mem = Memory.wrap(compBytes);
s = KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllItemsSketch.heapify(mem, Comparator.naturalOrder(), serDe);
compBytes2 = sk2.toByteArray();
mem = Memory.wrap(compBytes2);
s = KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(compBytes, compBytes2);
println("#### CASE: FLOAT SINGLE COMPACT");
sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
sk.update("1");
compBytes = sk.toByteArray();
mem = Memory.wrap(compBytes);
s = KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe);
println("step 1: sketch to byte[]/memory & analyze memory");
println(s);
sk2 = KllItemsSketch.heapify(mem, Comparator.naturalOrder(), serDe);
compBytes2 = sk2.toByteArray();
mem = Memory.wrap(compBytes2);
s = KllPreambleUtil.toString(mem, ITEMS_SKETCH, true, serDe);
println("step 2: memory to heap sketch, to byte[]/memory & analyze memory. Should match above");
println(s);
assertEquals(compBytes, compBytes2);
}
// public void checkMemoryToStringFloatUpdatable() Not Supported
// public void checkSimpleMerge() not supported
@Test
public void checkGetSingleItem() {
int k = 20;
KllItemsSketch<String> skHeap = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
skHeap.update("1");
assertTrue(skHeap instanceof KllHeapItemsSketch);
assertEquals(skHeap.getSingleItem(), "1");
Memory srcMem = Memory.wrap(KllHelper.toByteArray(skHeap, true)); //true is ignored
KllItemsSketch<String> skDirect = KllItemsSketch.wrap(srcMem, Comparator.naturalOrder(), serDe);
assertTrue(skDirect instanceof KllDirectCompactItemsSketch);
assertEquals(skDirect.getSingleItem(), "1");
Memory srcMem2 = Memory.wrap(skHeap.toByteArray());
KllItemsSketch<String> skCompact = KllItemsSketch.wrap(srcMem2, Comparator.naturalOrder(), serDe);
assertTrue(skCompact instanceof KllDirectCompactItemsSketch);
assertEquals(skCompact.getSingleItem(), "1");
}
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,384 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDirectFloatsSketchIteratorTest.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.kll;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class KllDirectFloatsSketchIteratorTest {
private static final DefaultMemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void emptySketch() {
final KllFloatsSketch sketch = getDFSketch(200, 0);
QuantilesFloatsSketchIterator it = sketch.iterator();
Assert.assertFalse(it.next());
}
@Test
public void oneItemSketch() {
final KllFloatsSketch sketch = getDFSketch(200, 0);
sketch.update(0);
QuantilesFloatsSketchIterator it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getQuantile(), 0f);
Assert.assertEquals(it.getWeight(), 1);
Assert.assertFalse(it.next());
}
@Test
public void bigSketches() {
for (int n = 1000; n < 100000; n += 2000) {
final KllFloatsSketch sketch = getDFSketch(200, 0);
for (int i = 0; i < n; i++) {
sketch.update(i);
}
QuantilesFloatsSketchIterator 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);
}
}
private static KllFloatsSketch getDFSketch(final int k, final int n) {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k);
for (int i = 1; i <= n; i++) { sk.update(i); }
byte[] byteArr = KllHelper.toByteArray(sk, true);
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
KllFloatsSketch dfsk = KllFloatsSketch.writableWrap(wmem, memReqSvr);
return dfsk;
}
}
| 2,385 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDirectCompactItemsSketchIteratorTest.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.kll;
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.assertTrue;
import java.util.Comparator;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.Util;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.GenericSortedViewIterator;
import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIterator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class KllDirectCompactItemsSketchIteratorTest {
private ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
@Test
public void emptySketch() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
byte[] byteArr = sk.toByteArray();
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(Memory.wrap(byteArr), Comparator.naturalOrder(), serDe);
assertTrue(sk2 instanceof KllDirectCompactItemsSketch);
QuantilesGenericSketchIterator<String> itr = sk2.iterator();
assertFalse(itr.next());
}
@Test
public void oneItemSketch() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sk.update("1");
byte[] byteArr = sk.toByteArray();
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(Memory.wrap(byteArr), Comparator.naturalOrder(), serDe);
assertTrue(sk2 instanceof KllDirectCompactItemsSketch);
QuantilesGenericSketchIterator<String> itr = sk2.iterator();
assertTrue(itr.next());
assertEquals(itr.getQuantile(), "1");
assertEquals(itr.getWeight(), 1);
assertFalse(itr.next());
}
@Test
public void twoItemSketchForIterator() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sk.update("1");
sk.update("2");
byte[] byteArr = sk.toByteArray();
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(Memory.wrap(byteArr), Comparator.naturalOrder(), serDe);
assertTrue(sk2 instanceof KllDirectCompactItemsSketch);
QuantilesGenericSketchIterator<String> itr = sk2.iterator();
assertTrue(itr.next());
assertEquals(itr.getQuantile(), "2");
assertEquals(itr.getWeight(), 1);
assertTrue(itr.next());
assertEquals(itr.getQuantile(), "1");
assertEquals(itr.getWeight(), 1);
}
@Test
public void twoItemSketchForSortedViewIterator() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sk.update("1");
sk.update("2");
byte[] byteArr = sk.toByteArray();
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(Memory.wrap(byteArr), Comparator.naturalOrder(), serDe);
assertTrue(sk2 instanceof KllDirectCompactItemsSketch);
GenericSortedViewIterator<String> itr = sk2.getSortedView().iterator();
assertTrue(itr.next());
assertEquals(itr.getQuantile(), "1");
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(), "2");
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
public void bigSketches() {
final int digits = 6;
for (int n = 1000; n < 100_000; n += 2000) {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
for (int i = 0; i < n; i++) {
sk.update(Util.intToFixedLengthString(i, digits));
}
byte[] byteArr = sk.toByteArray();
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(Memory.wrap(byteArr), Comparator.naturalOrder(), serDe);
assertTrue(sk2 instanceof KllDirectCompactItemsSketch);
QuantilesGenericSketchIterator<String> itr = sk2.iterator();
int count = 0;
int weight = 0;
while (itr.next()) {
count++;
weight += (int)itr.getWeight();
}
Assert.assertEquals(count, sk.getNumRetained());
Assert.assertEquals(weight, n);
}
}
}
| 2,386 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllItemsSketchSerDeTest.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.kll;
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.Comparator;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.Util;
import org.apache.datasketches.memory.Memory;
import org.testng.annotations.Test;
public class KllItemsSketchSerDeTest {
private ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
@Test
public void serializeDeserializeEmpty() {
final KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
//from heap -> byte[] -> heap
final byte[] bytes = sk1.toByteArray();
final KllItemsSketch<String> sk2 = KllItemsSketch.heapify(Memory.wrap(bytes), Comparator.naturalOrder(), serDe);
assertEquals(bytes.length, sk1.getSerializedSizeBytes());
assertTrue(sk2.isEmpty());
assertEquals(sk2.getNumRetained(), sk1.getNumRetained());
assertEquals(sk2.getN(), sk1.getN());
assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
try { sk2.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sk2.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap
final KllItemsSketch<String> sk3 = KllItemsSketch.wrap(Memory.wrap(bytes), Comparator.naturalOrder(), serDe);
assertTrue(sk3.isEmpty());
assertEquals(sk3.getNumRetained(), sk1.getNumRetained());
assertEquals(sk3.getN(), sk1.getN());
assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
try { sk3.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sk3.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap -> byte[] -> compare byte[]
final byte[] bytes2 = sk3.toByteArray();
assertEquals(bytes, bytes2);
}
@Test
public void serializeDeserializeOneValue() {
final KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe);
sk1.update(" 1");
//from heap -> byte[] -> heap
final byte[] bytes = sk1.toByteArray();
final KllItemsSketch<String> sk2 = KllItemsSketch.heapify(Memory.wrap(bytes), Comparator.naturalOrder(), serDe);
assertEquals(bytes.length, sk1.getSerializedSizeBytes());
assertFalse(sk2.isEmpty());
assertEquals(sk2.getNumRetained(), 1);
assertEquals(sk2.getN(), 1);
assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk2.getMinItem(), " 1");
assertEquals(sk2.getMaxItem(), " 1");
assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap
final KllItemsSketch<String> sk3 = KllItemsSketch.wrap(Memory.wrap(bytes), Comparator.naturalOrder(), serDe);
assertFalse(sk3.isEmpty());
assertEquals(sk3.getNumRetained(), 1);
assertEquals(sk3.getN(), 1);
assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk3.getMinItem(), " 1");
assertEquals(sk3.getMaxItem(), " 1");
assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap -> byte[] -> compare byte[]
final byte[] bytes2 = sk3.toByteArray();
assertEquals(bytes, bytes2);
}
@Test
public void serializeDeserializeMultipleValues() {
final KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
final int n = 1000;
for (int i = 0; i < n; i++) {
sk1.update(Util.intToFixedLengthString(i, 4));
}
assertEquals(sk1.getMinItem(), " 0");
assertEquals(sk1.getMaxItem(), " 999");
//from heap -> byte[] -> heap
final byte[] bytes = sk1.toByteArray();
final KllItemsSketch<String> sk2 = KllItemsSketch.heapify(Memory.wrap(bytes), Comparator.naturalOrder(), serDe);
assertEquals(bytes.length, sk1.getSerializedSizeBytes());
assertFalse(sk2.isEmpty());
assertEquals(sk2.getNumRetained(), sk1.getNumRetained());
assertEquals(sk2.getN(), sk1.getN());
assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk2.getMinItem(), sk1.getMinItem());
assertEquals(sk2.getMaxItem(), sk1.getMaxItem());
assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap
final KllItemsSketch<String> sk3 = KllItemsSketch.wrap(Memory.wrap(bytes), Comparator.naturalOrder(), serDe);
assertFalse(sk3.isEmpty());
assertEquals(sk3.getNumRetained(), sk1.getNumRetained());
assertEquals(sk3.getN(), sk1.getN());
assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false));
assertEquals(sk3.getMinItem(), sk1.getMinItem());
assertEquals(sk3.getMaxItem(), sk1.getMaxItem());
assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes());
//from heap -> byte[] -> off heap -> byte[] -> compare byte[]
final byte[] bytes2 = sk3.toByteArray();
assertEquals(bytes, bytes2);
}
}
| 2,387 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllHelperTest.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.kll;
import static org.apache.datasketches.kll.KllHelper.checkM;
import static org.apache.datasketches.kll.KllSketch.SketchType.DOUBLES_SKETCH;
import static org.apache.datasketches.kll.KllSketch.SketchType.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import java.util.Comparator;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.Util;
import org.apache.datasketches.memory.Memory;
import org.testng.annotations.Test;
public class KllHelperTest {
public ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
@Test
public void checkConvertToCumulative() {
long[] array = {1,2,3,2,1};
long out = KllHelper.convertToCumulative(array);
assertEquals(out, 9);
}
@Test
public void checkCheckM() {
try {
checkM(0);
fail();
} catch (SketchesArgumentException e) {}
try {
checkM(3);
fail();
} catch (SketchesArgumentException e) {}
try {
checkM(10);
fail();
} catch (SketchesArgumentException e) {}
}
@Test
public void checkGetKFromEps() {
final int k = KllSketch.DEFAULT_K;
final double eps = KllHelper.getNormalizedRankError(k, false);
final double epsPmf = KllHelper.getNormalizedRankError(k, true);
final int kEps = KllSketch.getKFromEpsilon(eps, false);
final int kEpsPmf = KllSketch.getKFromEpsilon(epsPmf, true);
assertEquals(kEps, k);
assertEquals(kEpsPmf, k);
}
@Test
public void checkIntCapAux() {
int lvlCap = KllHelper.levelCapacity(10, 61, 0, 8);
assertEquals(lvlCap, 8);
lvlCap = KllHelper.levelCapacity(10, 61, 60, 8);
assertEquals(lvlCap, 10);
}
@Test
public void checkSuperLargeKandLevels() {
//This is beyond what the sketch can be configured for.
final int size = KllHelper.computeTotalItemCapacity(1 << 29, 8, 61);
assertEquals(size, 1_610_612_846);
}
@Test
public void checkUbOnNumLevels() {
assertEquals(KllHelper.ubOnNumLevels(0), 1);
}
@Test
public void checkUpdatableSerDeDouble() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(200);
for (int i = 1; i <= 533; i++) { sk.update(i); }
int retained = sk.getNumRetained();
int numLevels = ((KllSketch)sk).getNumLevels();
println("NumLevels: " + numLevels);
println("NumRetained: " + retained);
byte[] compByteArr1 = sk.toByteArray();
int compBytes1 = compByteArr1.length;
println("compBytes1: " + compBytes1);
byte[] upByteArr1 = KllHelper.toByteArray(sk, true);
int upBytes1 = upByteArr1.length;
println("upBytes1: " + upBytes1);
Memory mem;
KllDoublesSketch sk2;
mem = Memory.wrap(compByteArr1);
sk2 = KllDoublesSketch.heapify(mem);
byte[] compByteArr2 = sk2.toByteArray();
int compBytes2 = compByteArr2.length;
println("compBytes2: " + compBytes2);
assertEquals(compBytes1, compBytes2);
assertEquals(sk2.getNumRetained(), retained);
mem = Memory.wrap(compByteArr2);
sk2 = KllDoublesSketch.heapify(mem);
byte[] upByteArr2 = KllHelper.toByteArray(sk2, true);
int upBytes2 = upByteArr2.length;
println("upBytes2: " + upBytes2);
assertEquals(upBytes1, upBytes2);
assertEquals(sk2.getNumRetained(), retained);
}
@Test
public void checkUpdatableSerDeFloat() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(200);
for (int i = 1; i <= 533; i++) { sk.update(i); }
int retained = sk.getNumRetained();
int numLevels = ((KllSketch)sk).getNumLevels();
println("NumLevels: " + numLevels);
println("NumRetained: " + retained);
byte[] compByteArr1 = sk.toByteArray();
int compBytes1 = compByteArr1.length;
println("compBytes1: " + compBytes1);
byte[] upByteArr1 = KllHelper.toByteArray(sk, true);
int upBytes1 = upByteArr1.length;
println("upBytes1: " + upBytes1);
Memory mem;
KllFloatsSketch sk2;
mem = Memory.wrap(compByteArr1);
sk2 = KllFloatsSketch.heapify(mem);
byte[] compByteArr2 = sk2.toByteArray();
int compBytes2 = compByteArr2.length;
println("compBytes2: " + compBytes2);
assertEquals(compBytes1, compBytes2);
assertEquals(sk2.getNumRetained(), retained);
mem = Memory.wrap(compByteArr2);
sk2 = KllFloatsSketch.heapify(mem);
byte[] upByteArr2 = KllHelper.toByteArray(sk2, true);
int upBytes2 = upByteArr2.length;
println("upBytes2: " + upBytes2);
assertEquals(upBytes1, upBytes2);
assertEquals(sk2.getNumRetained(), retained);
}
@Test
public void checkUpdatableSerDeItem() {
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(200, Comparator.naturalOrder(), serDe);
final int n = 533;
final int digits = Util.numDigits(n);
for (int i = 1; i <= n; i++) { sk.update(Util.intToFixedLengthString(i, digits)); }
int retained = sk.getNumRetained();
int numLevels = ((KllSketch)sk).getNumLevels();
println("NumLevels: " + numLevels);
println("NumRetained: " + retained);
byte[] compByteArr1 = sk.toByteArray();
int compBytes1 = compByteArr1.length;
println("compBytes1: " + compBytes1);
byte[] upByteArr1 = KllHelper.toByteArray(sk, true);
int upBytes1 = upByteArr1.length;
println("upBytes1: " + upBytes1);
assertEquals(upBytes1, compBytes1); //only true for Items Sketch
Memory mem;
KllItemsSketch<String> sk2;
mem = Memory.wrap(compByteArr1);
sk2 = KllItemsSketch.heapify(mem, Comparator.naturalOrder(), serDe);
byte[] compByteArr2 = sk2.toByteArray();
int compBytes2 = compByteArr2.length;
println("compBytes2: " + compBytes2);
assertEquals(compBytes1, compBytes2);
assertEquals(sk2.getNumRetained(), retained);
mem = Memory.wrap(compByteArr2);
sk2 = KllItemsSketch.heapify(mem, Comparator.naturalOrder(), serDe);
byte[] upByteArr2 = KllHelper.toByteArray(sk2, true);
int upBytes2 = upByteArr2.length;
println("upBytes2: " + upBytes2);
assertEquals(upBytes1, upBytes2);
assertEquals(sk2.getNumRetained(), retained);
}
@Test
public void getMaxCompactDoublesSerializedSizeBytes() {
final int sizeBytes =
KllSketch.getMaxSerializedSizeBytes(KllSketch.DEFAULT_K, 1L << 30, DOUBLES_SKETCH, false);
assertEquals(sizeBytes, 5704);
}
@Test
public void getMaxCompactFloatsSerializedSizeBytes() {
final int sizeBytes =
KllSketch.getMaxSerializedSizeBytes(KllSketch.DEFAULT_K, 1L << 30, FLOATS_SKETCH, false);
assertEquals(sizeBytes, 2908);
}
@Test
public void getMaxUpdatableDoubleSerializedSizeBytes() {
final int sizeBytes =
KllSketch.getMaxSerializedSizeBytes(KllSketch.DEFAULT_K, 1L << 30, DOUBLES_SKETCH, true);
assertEquals(sizeBytes, 5708);
}
@Test
public void getMaxUpdatableFloatsSerializedSizeBytes() {
final int sizeBytes =
KllSketch.getMaxSerializedSizeBytes(KllSketch.DEFAULT_K, 1L << 30, FLOATS_SKETCH, true);
assertEquals(sizeBytes, 2912);
}
@Test
public void getMaxUpdatableItemsSerializedSizeBytes() {
try {
KllSketch.getMaxSerializedSizeBytes(KllSketch.DEFAULT_K, 1L << 30, ITEMS_SKETCH, true);
} catch (SketchesArgumentException e) { }
}
@Test
public void getStatsAtNumLevels() {
int k = 200;
int m = 8;
int numLevels = 23;
KllHelper.LevelStats lvlStats =
KllHelper.getFinalSketchStatsAtNumLevels(k, m, numLevels, true);
assertEquals(lvlStats.numItems, 697);
assertEquals(lvlStats.n, 1257766904);
}
@Test
public void getStatsAtNumLevels2() {
int k = 20;
int m = KllSketch.DEFAULT_M;
int numLevels = 2;
KllHelper.LevelStats lvlStats =
KllHelper.getFinalSketchStatsAtNumLevels(k, m, numLevels, true);
assertEquals(lvlStats.numLevels, 2);
assertEquals(lvlStats.numItems, 33);
}
@Test
public void testGetAllLevelStatsDoubles() {
long n = 1L << 30;
int k = 200;
int m = KllSketch.DEFAULT_M;
KllHelper.GrowthStats gStats =
KllHelper.getGrowthSchemeForGivenN(k, m, n, DOUBLES_SKETCH, true);
assertEquals(gStats.maxN, 1_257_766_904);
assertEquals(gStats.numLevels, 23);
assertEquals(gStats.maxItems, 697);
assertEquals(gStats.compactBytes, 5704);
assertEquals(gStats.updatableBytes, 5708);
}
@Test
public void testGetAllLevelStatsFloats() {
long n = 1L << 30;
int k = 200;
int m = KllSketch.DEFAULT_M;
KllHelper.GrowthStats gStats =
KllHelper.getGrowthSchemeForGivenN(k, m, n, FLOATS_SKETCH, true);
assertEquals(gStats.maxN, 1_257_766_904);
assertEquals(gStats.numLevels, 23);
assertEquals(gStats.maxItems, 697);
assertEquals(gStats.compactBytes, 2908);
assertEquals(gStats.updatableBytes, 2912);
}
@Test
public void testGetAllLevelStatsDoubles2() {
long n = 533;
int k = 200;
int m = KllSketch.DEFAULT_M;
KllHelper.GrowthStats gStats =
KllHelper.getGrowthSchemeForGivenN(k, m, n, DOUBLES_SKETCH, true);
assertEquals(gStats.maxN, 533);
assertEquals(gStats.numLevels, 2);
assertEquals(gStats.maxItems, 333);
assertEquals(gStats.compactBytes, 2708);
assertEquals(gStats.updatableBytes, 2712);
}
@Test
public void testGetAllLevelStatsFloats2() {
long n = 533;
int k = 200;
int m = KllSketch.DEFAULT_M;
KllHelper.GrowthStats gStats =
KllHelper.getGrowthSchemeForGivenN(k, m, n, FLOATS_SKETCH, true);
assertEquals(gStats.maxN, 533);
assertEquals(gStats.numLevels, 2);
assertEquals(gStats.maxItems, 333);
assertEquals(gStats.compactBytes, 1368);
assertEquals(gStats.updatableBytes, 1372);
}
@Test
public void testGetAllLevelStatsItems() {
long n = 533;
int k = 200;
int m = KllSketch.DEFAULT_M;
try {
KllHelper.getGrowthSchemeForGivenN(k, m, n, ITEMS_SKETCH, true);
} catch (SketchesArgumentException e) { }
}
/**
* Println Object o
* @param o object to print
*/
static void println(Object o) {
//System.out.println(o.toString());
}
}
| 2,388 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllItemsSketchiteratorTest.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.kll;
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 java.util.Comparator;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.Util;
import org.apache.datasketches.quantilescommon.GenericSortedViewIterator;
import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIterator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class KllItemsSketchiteratorTest {
private ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
@Test
public void emptySketch() {
KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
QuantilesGenericSketchIterator<String> it = sketch.iterator();
Assert.assertFalse(it.next());
}
@Test
public void oneItemSketch() {
KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sketch.update("1");
QuantilesGenericSketchIterator<String> it = sketch.iterator();
Assert.assertTrue(it.next());
Assert.assertEquals(it.getQuantile(), "1");
Assert.assertEquals(it.getWeight(), 1);
Assert.assertFalse(it.next());
}
@Test
public void twoItemSketchForIterator() {
KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sketch.update("1");
sketch.update("2");
QuantilesGenericSketchIterator<String> itr = sketch.iterator();
assertTrue(itr.next());
assertEquals(itr.getQuantile(), "2");
assertEquals(itr.getWeight(), 1);
assertTrue(itr.next());
assertEquals(itr.getQuantile(), "1");
assertEquals(itr.getWeight(), 1);
}
@Test
public void twoItemSketchForSortedViewIterator() {
KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
sketch.update("1");
sketch.update("2");
GenericSortedViewIterator<String> itr = sketch.getSortedView().iterator();
assertTrue(itr.next());
assertEquals(itr.getQuantile(), "1");
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(), "2");
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
public void bigSketches() {
final int digits = 6;
for (int n = 1000; n < 100_000; n += 2000) {
KllItemsSketch<String> sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
for (int i = 0; i < n; i++) {
sketch.update(Util.intToFixedLengthString(i, digits));
}
QuantilesGenericSketchIterator<String> 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,389 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllFloatsSketchTest.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.kll;
import static org.apache.datasketches.kll.KllSketch.SketchType.FLOATS_SKETCH;
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 org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.quantilescommon.FloatsSortedView;
import org.apache.datasketches.quantilescommon.FloatsSortedViewIterator;
import org.testng.annotations.Test;
public class KllFloatsSketchTest {
private static final double PMF_EPS_FOR_K_8 = 0.35; // PMF rank error (epsilon) for k=8
private static final double PMF_EPS_FOR_K_128 = 0.025; // PMF rank error (epsilon) for k=128
private static final double PMF_EPS_FOR_K_256 = 0.013; // PMF rank error (epsilon) for k=256
private static final double NUMERIC_NOISE_TOLERANCE = 1E-6;
private static final DefaultMemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void empty() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
sketch.update(Float.NaN); // this must not change anything
assertTrue(sketch.isEmpty());
assertEquals(sketch.getN(), 0);
assertEquals(sketch.getNumRetained(), 0);
try { sketch.getRank(0); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getQuantile(0.5); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getQuantiles(new double[] {0}); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getPMF(new float[] {0}); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getCDF(new float[] {0}); fail(); } catch (SketchesArgumentException e) {}
assertNotNull(sketch.toString(true, true));
assertNotNull(sketch.toString());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void getQuantileInvalidArg() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
sketch.update(1);
sketch.getQuantile(-1.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void getQuantilesInvalidArg() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
sketch.update(1);
sketch.getQuantiles(new double[] {2.0});
}
@Test
public void oneValue() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
sketch.update(1);
assertFalse(sketch.isEmpty());
assertEquals(sketch.getN(), 1);
assertEquals(sketch.getNumRetained(), 1);
assertEquals(sketch.getRank(0.0f, EXCLUSIVE), 0.0);
assertEquals(sketch.getRank(1.0f, EXCLUSIVE), 0.0);
assertEquals(sketch.getRank(2.0f, EXCLUSIVE), 1.0);
assertEquals(sketch.getRank(0.0f, INCLUSIVE), 0.0);
assertEquals(sketch.getRank(1.0f, INCLUSIVE), 1.0);
assertEquals(sketch.getRank(2.0f, INCLUSIVE), 1.0);
assertEquals(sketch.getMinItem(), 1.0f);
assertEquals(sketch.getMaxItem(), 1.0f);
assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 1.0f);
assertEquals(sketch.getQuantile(0.5, INCLUSIVE), 1.0f);
}
@Test
public void tenValues() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(20);
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, INCLUSIVE), i / 10.0);
}
final float[] 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);
}
for (int i = 0; i >= 10; i++) {
double rank = i/10.0;
float q = rank == 1.0 ? i : i + 1;
assertEquals(sketch.getQuantile(rank, EXCLUSIVE), q);
q = (float)(rank == 0 ? i + 1.0 : i);
assertEquals(sketch.getQuantile(rank, INCLUSIVE), q);
}
{
// getQuantile() and getQuantiles() equivalence EXCLUSIVE
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.0}, EXCLUSIVE);
for (int i = 0; i <= 10; i++) {
assertEquals(sketch.getQuantile(i / 10.0, EXCLUSIVE), quantiles[i]);
}
}
{
// getQuantile() and getQuantiles() equivalence INCLUSIVE
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.0}, INCLUSIVE);
for (int i = 0; i <= 10; i++) {
assertEquals(sketch.getQuantile(i / 10.0, INCLUSIVE), quantiles[i]);
}
}
}
@Test
public void manyValuesEstimationMode() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
final int n = 1_000_000;
for (int i = 0; i < n; i++) {
sketch.update(i);
}
assertEquals(sketch.getN(), n);
// test getRank
for (int i = 0; i < n; i++) {
final double trueRank = (double) i / n;
assertEquals(sketch.getRank(i), trueRank, PMF_EPS_FOR_K_256, "for value " + i);
}
// test getPMF
final double[] pmf = sketch.getPMF(new float[] {n / 2.0F}); // split at median
assertEquals(pmf.length, 2);
assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256);
assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256);
assertEquals(sketch.getMinItem(), 0f);
assertEquals(sketch.getMaxItem(), n - 1f);
// check at every 0.1 percentage point
final double[] fractions = new double[1001];
final double[] reverseFractions = new double[1001]; // check that ordering doesn't matter
for (int i = 0; i <= 1000; i++) {
fractions[i] = (double) i / 1000;
reverseFractions[1000 - i] = fractions[i];
}
final float[] quantiles = sketch.getQuantiles(fractions);
final float[] reverseQuantiles = sketch.getQuantiles(reverseFractions);
float previousQuantile = 0;
for (int i = 0; i <= 1000; i++) {
final float quantile = sketch.getQuantile(fractions[i]);
assertEquals(quantile, quantiles[i]);
assertEquals(quantile, reverseQuantiles[1000 - i]);
assertTrue(previousQuantile <= quantile);
previousQuantile = quantile;
}
}
@Test
public void getRankGetCdfGetPmfConsistency() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
final int n = 1000;
final float[] values = new float[n];
for (int i = 0; i < n; i++) {
sketch.update(i);
values[i] = i;
}
{ // inclusive = false (default)
final double[] ranks = sketch.getCDF(values);
final double[] pmf = sketch.getPMF(values);
double sumPmf = 0;
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i]), NUMERIC_NOISE_TOLERANCE,
"rank vs CDF for value " + i);
sumPmf += pmf[i];
assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i);
}
sumPmf += pmf[n];
assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE);
assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE);
}
{ // inclusive = true
final double[] ranks = sketch.getCDF(values, INCLUSIVE);
final double[] pmf = sketch.getPMF(values, INCLUSIVE);
double sumPmf = 0;
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i], INCLUSIVE), NUMERIC_NOISE_TOLERANCE,
"rank vs CDF for value " + i);
sumPmf += pmf[i];
assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i);
}
sumPmf += pmf[n];
assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE);
assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE);
}
}
@Test
public void merge() {
final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance();
final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance();
final int n = 10000;
for (int i = 0; i < n; i++) {
sketch1.update(i * 1.0f);
sketch2.update((2 * n - i - 1) * 1.0f);
}
assertEquals(sketch1.getMinItem(), 0.0f);
assertEquals(sketch1.getMaxItem(), (n - 1) * 1.0f);
assertEquals(sketch2.getMinItem(), n * 1.0f);
assertEquals(sketch2.getMaxItem(), (2 * n - 1) * 1.0f);
sketch1.merge(sketch2);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), 2L * n);
assertEquals(sketch1.getMinItem(), 0.0f);
assertEquals(sketch1.getMaxItem(), (2 * n - 1) * 1.0f);
assertEquals(sketch1.getQuantile(0.5), n * 1.0f, 2 * n * PMF_EPS_FOR_K_256);
}
@Test
public void mergeLowerK() {
final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance(256);
final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance(128);
final int n = 10000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
sketch2.update(2 * n - i - 1);
}
assertEquals(sketch1.getMinItem(), 0.0f);
assertEquals(sketch1.getMaxItem(), n - 1f);
assertEquals(sketch2.getMinItem(), n);
assertEquals(sketch2.getMaxItem(), 2f * n - 1.0f);
assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false));
assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true));
sketch1.merge(sketch2);
// sketch1 must get "contaminated" by the lower K in sketch2
assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false));
assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true));
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), 2 * n);
assertEquals(sketch1.getMinItem(), 0.0f);
assertEquals(sketch1.getMaxItem(), 2.0f * n - 1.0f);
assertEquals(sketch1.getQuantile(0.5), n, 2 * n * PMF_EPS_FOR_K_128);
}
@Test
public void mergeEmptyLowerK() {
final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance(256);
final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance(128);
final int n = 10_000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
}
// rank error should not be affected by a merge with an empty sketch with lower K
final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true);
sketch1.merge(sketch2);
assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), n);
assertEquals(sketch1.getMinItem(), 0.0f);
assertEquals(sketch1.getMaxItem(), n - 1.0f);
assertEquals(sketch1.getQuantile(0.5), n / 2.0f, n * PMF_EPS_FOR_K_256);
//merge the other way
sketch2.merge(sketch1);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), n);
assertEquals(sketch1.getMinItem(), 0f);
assertEquals(sketch1.getMaxItem(), n - 1.0f);
assertEquals(sketch1.getQuantile(0.5), n / 2.0f, n * PMF_EPS_FOR_K_256);
}
@Test
public void mergeExactModeLowerK() {
final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance(256);
final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance(128);
final int n = 10000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
}
sketch2.update(1);
// rank error should not be affected by a merge with a sketch in exact mode with lower K
final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true);
sketch1.merge(sketch2);
assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge);
}
@Test
public void mergeMinMinValueFromOther() {
final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance();
final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance();
sketch1.update(1);
sketch2.update(2);
sketch2.merge(sketch1);
assertEquals(sketch2.getMinItem(), 1.0F);
}
@Test
public void mergeMinAndMaxFromOther() {
final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance();
for (int i = 1; i <= 1_000_000; i++) {
sketch1.update(i);
}
final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance(10);
sketch2.merge(sketch1);
assertEquals(sketch2.getMinItem(), 1.0F);
assertEquals(sketch2.getMaxItem(), 1_000_000.0F);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void kTooSmall() {
KllFloatsSketch.newHeapInstance(KllSketch.DEFAULT_M - 1);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void kTooLarge() {
KllFloatsSketch.newHeapInstance(KllSketch.MAX_K + 1);
}
@Test
public void minK() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(KllSketch.DEFAULT_M);
for (int i = 0; i < 1000; i++) {
sketch.update(i);
}
assertEquals(sketch.getK(), KllSketch.DEFAULT_M);
assertEquals(sketch.getQuantile(.5), 500.0f, 1000 * PMF_EPS_FOR_K_8);
}
@Test
public void maxK() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(KllSketch.MAX_K);
for (int i = 0; i < 1000; i++) {
sketch.update(i);
}
assertEquals(sketch.getK(), KllSketch.MAX_K);
assertEquals(sketch.getQuantile(0.5), 500, 1000 * PMF_EPS_FOR_K_256);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void outOfOrderSplitPoints() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
sketch.update(0);
sketch.getCDF(new float[] {1.0f, 0.0f});
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void nanSplitPoint() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
sketch.update(0);
sketch.getCDF(new float[] {Float.NaN});
}
@Test
public void getQuantiles() {
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
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 checkReset() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= 100; i++) { sk.update(i); }
long n1 = sk.getN();
float min1 = sk.getMinItem();
float max1 = sk.getMaxItem();
sk.reset();
for (int i = 1; i <= 100; i++) { sk.update(i); }
long n2 = sk.getN();
float min2 = sk.getMinItem();
float max2 = sk.getMaxItem();
assertEquals(n2, n1);
assertEquals(min2, min1);
assertEquals(max2, max1);
}
@Test
public void checkReadOnlyUpdate() {
KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(20);
Memory mem = Memory.wrap(sk1.toByteArray());
KllFloatsSketch sk2 = KllFloatsSketch.wrap(mem);
try { sk2.update(1); fail(); } catch (SketchesArgumentException e) { }
}
@Test
public void checkNewDirectInstanceAndSize() {
WritableMemory wmem = WritableMemory.allocate(3000);
KllFloatsSketch.newDirectInstance(wmem, memReqSvr);
try { KllFloatsSketch.newDirectInstance(null, memReqSvr); fail(); }
catch (NullPointerException e) { }
try { KllFloatsSketch.newDirectInstance(wmem, null); fail(); }
catch (NullPointerException e) { }
int updateSize = KllSketch.getMaxSerializedSizeBytes(200, 0, FLOATS_SKETCH, true);
int compactSize = KllSketch.getMaxSerializedSizeBytes(200, 0, FLOATS_SKETCH, false);
assertTrue(compactSize < updateSize);
}
@Test
public void sortedView() {
final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance();
sk.update(3);
sk.update(1);
sk.update(2);
final FloatsSortedView view = sk.getSortedView();
final FloatsSortedViewIterator itr = view.iterator();
assertEquals(itr.next(), true);
assertEquals(itr.getQuantile(), 1);
assertEquals(itr.getWeight(), 1);
assertEquals(itr.getCumulativeWeight(EXCLUSIVE), 0);
assertEquals(itr.getCumulativeWeight(INCLUSIVE), 1);
assertEquals(itr.next(), true);
assertEquals(itr.getQuantile(), 2);
assertEquals(itr.getWeight(), 1);
assertEquals(itr.getCumulativeWeight(EXCLUSIVE), 1);
assertEquals(itr.getCumulativeWeight(INCLUSIVE), 2);
assertEquals(itr.next(), true);
assertEquals(itr.getQuantile(), 3);
assertEquals(itr.getWeight(), 1);
assertEquals(itr.getCumulativeWeight(EXCLUSIVE), 2);
assertEquals(itr.getCumulativeWeight(INCLUSIVE), 3);
assertEquals(itr.next(), false);
}
@Test //also visual
public void checkCDF_PDF() {
final double[] cdfI = {.25, .50, .75, 1.0, 1.0 };
final double[] cdfE = {0.0, .25, .50, .75, 1.0 };
final double[] pmfI = {.25, .25, .25, .25, 0.0 };
final double[] pmfE = {0.0, .25, .25, .25, .25 };
final double toll = 1E-10;
final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance();
final float[] floatIn = {10, 20, 30, 40};
for (int i = 0; i < floatIn.length; i++) { sketch.update(floatIn[i]); }
float[] sp = new float[] { 10, 20, 30, 40 };
println("SplitPoints:");
for (int i = 0; i < sp.length; i++) {
printf("%10.2f", sp[i]);
}
println("");
println("INCLUSIVE:");
double[] cdf = sketch.getCDF(sp, INCLUSIVE);
double[] pmf = sketch.getPMF(sp, INCLUSIVE);
printf("%10s%10s\n", "CDF", "PMF");
for (int i = 0; i < cdf.length; i++) {
printf("%10.2f%10.2f\n", cdf[i], pmf[i]);
assertEquals(cdf[i], cdfI[i], toll);
assertEquals(pmf[i], pmfI[i], toll);
}
println("EXCLUSIVE");
cdf = sketch.getCDF(sp, EXCLUSIVE);
pmf = sketch.getPMF(sp, EXCLUSIVE);
printf("%10s%10s\n", "CDF", "PMF");
for (int i = 0; i < cdf.length; i++) {
printf("%10.2f%10.2f\n", cdf[i], pmf[i]);
assertEquals(cdf[i], cdfE[i], toll);
assertEquals(pmf[i], pmfE[i], toll);
}
}
@Test
public void checkWrapCase1Floats() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
Memory mem = Memory.wrap(sk.toByteArray());
KllFloatsSketch sk2 = KllFloatsSketch.wrap(mem);
assertTrue(mem.isReadOnly());
assertTrue(sk2.isReadOnly());
assertFalse(sk2.isDirect());
}
@Test
public void checkWritableWrapCase6And2Floats() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
WritableMemory wmem = WritableMemory.writableWrap(KllHelper.toByteArray(sk, true));
KllFloatsSketch sk2 = KllFloatsSketch.writableWrap(wmem, memReqSvr);
assertFalse(wmem.isReadOnly());
assertFalse(sk2.isReadOnly());
assertFalse(sk2.isDirect());
}
@Test
public void checkKllSketchCase5Floats() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
WritableMemory wmem = WritableMemory.writableWrap(sk.toByteArray());
KllFloatsSketch sk2 = KllFloatsSketch.writableWrap(wmem, memReqSvr);
assertFalse(wmem.isReadOnly());
assertTrue(sk2.isReadOnly());
assertFalse(sk2.isDirect());
}
@Test
public void checkKllSketchCase3Floats() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
Memory mem = Memory.wrap(KllHelper.toByteArray(sk, true));
WritableMemory wmem = (WritableMemory) mem;
KllFloatsSketch sk2 = KllFloatsSketch.writableWrap(wmem, memReqSvr);
assertTrue(wmem.isReadOnly());
assertTrue(sk2.isReadOnly());
assertFalse(sk2.isDirect());
}
@Test
public void checkKllSketchCase7Floats() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++) { sk.update(i); }
Memory mem = Memory.wrap(KllHelper.toByteArray(sk, true));
WritableMemory wmem = (WritableMemory) mem;
KllFloatsSketch sk2 = KllFloatsSketch.writableWrap(wmem, memReqSvr);
assertTrue(wmem.isReadOnly());
assertTrue(sk2.isReadOnly());
assertFalse(sk2.isDirect());
}
@Test
public void checkReadOnlyExceptions() {
int[] intArr = new int[0];
int intV = 2;
int idx = 1;
KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(20);
Memory mem = Memory.wrap(sk1.toByteArray());
KllFloatsSketch sk2 = KllFloatsSketch.wrap(mem);
try { sk2.setLevelsArray(intArr); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setLevelsArrayAt(idx,intV); fail(); } catch (SketchesArgumentException e) { }
}
@Test
public void checkIsSameResource() {
int cap = 128;
WritableMemory wmem = WritableMemory.allocate(cap);
WritableMemory reg1 = wmem.writableRegion(0, 64);
WritableMemory reg2 = wmem.writableRegion(64, 64);
assertFalse(reg1 == reg2);
assertFalse(reg1.isSameResource(reg2));
WritableMemory reg3 = wmem.writableRegion(0, 64);
assertFalse(reg1 == reg3);
assertTrue(reg1.isSameResource(reg3));
byte[] byteArr1 = KllFloatsSketch.newHeapInstance(20).toByteArray();
reg1.putByteArray(0, byteArr1, 0, byteArr1.length);
KllFloatsSketch sk1 = KllFloatsSketch.wrap(reg1);
byte[] byteArr2 = KllFloatsSketch.newHeapInstance(20).toByteArray();
reg2.putByteArray(0, byteArr2, 0, byteArr2.length);
assertFalse(sk1.isSameResource(reg2));
byte[] byteArr3 = KllFloatsSketch.newHeapInstance(20).toByteArray();
reg3.putByteArray(0, byteArr3, 0, byteArr3.length);
assertTrue(sk1.isSameResource(reg3));
}
@Test
public void checkSortedViewAfterReset() {
KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20);
sk.update(1.0f);
FloatsSortedView sv = sk.getSortedView();
float fsv = sv.getQuantile(1.0, INCLUSIVE);
assertEquals(fsv, 1.0f);
sk.reset();
try { sk.getSortedView(); fail(); } catch (SketchesArgumentException e) { }
}
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,390 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllItemsSketchSortedViewString.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.kll;
import java.util.Comparator;
/**
* For testing only
*/
public class KllItemsSketchSortedViewString extends KllItemsSketchSortedView<String> {
public KllItemsSketchSortedViewString(
final String[] quantiles,
final long[] cumWeights,
final long totalN,
final String minItem,
final Comparator<String> comparator) {
super(quantiles, cumWeights, totalN, minItem, comparator);
}
}
| 2,391 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDirectCompactItemsSketchTest.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.kll;
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.Comparator;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.Util;
import org.apache.datasketches.memory.Memory;
import org.testng.annotations.Test;
public class KllDirectCompactItemsSketchTest {
public ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
@Test
public void checkRODirectCompact() {
int k = 20;
final int n = 21;
final int digits = Util.numDigits(n);
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
for (int i = 1; i <= n; i++) { sk.update(Util.intToFixedLengthString(i, digits)); }
byte[] byteArr = KllHelper.toByteArray(sk, true); //request for updatable is denied -> COMPACT, RO
Memory srcMem = Memory.wrap(byteArr); //compact RO fmt
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(srcMem, Comparator.naturalOrder(), serDe);
assertTrue(sk2 instanceof KllDirectCompactItemsSketch);
println(sk2.toString(true, false));
assertFalse(sk2.isMemoryUpdatableFormat());
assertTrue(sk2.isReadOnly());
assertEquals(sk2.getMinItem(), " 1");
assertEquals(sk2.getMaxItem(), "21");
}
@Test
public void checkDirectCompactSingleItem() {
int k = 20;
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
sk.update("1");
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(Memory.wrap(sk.toByteArray()), Comparator.naturalOrder(), serDe);
assertTrue(sk2 instanceof KllDirectCompactItemsSketch);
//println(sk2.toString(true, false));
assertTrue(sk2.isReadOnly());
assertEquals(sk2.getSingleItem(), "1");
sk.update("2");
sk2 = KllItemsSketch.wrap(Memory.wrap(sk.toByteArray()), Comparator.naturalOrder(), serDe);
assertEquals(sk2.getN(), 2);
try {
sk2.getSingleItem(); //not a single item
fail();
} catch (SketchesArgumentException e) { }
}
@Test
public void checkHeapGetFullItemsArray() {
int k = 20;
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
String[] itemsArr = sk.getTotalItemsArray();
for (int j = 0; j < k; j++) { assertNull(itemsArr[j]); }
sk.update(" 1"); //single
itemsArr = sk.getTotalItemsArray();
for (int j = 0; j < k - 1; j++) { assertNull(itemsArr[j]); }
assertEquals(itemsArr[k - 1], " 1");
sk.update(" 2"); //multiple
itemsArr = sk.getTotalItemsArray();
for (int j = 0; j < k - 2; j++) { assertNull(itemsArr[j]); }
assertEquals(itemsArr[k - 1], " 1");
assertEquals(itemsArr[k - 2], " 2");
}
@Test
public void checkDirectCompactGetFullItemsArray() {
int k = 20;
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(Memory.wrap(sk.toByteArray()), Comparator.naturalOrder(), serDe);
String[] itemsArr = sk2.getTotalItemsArray(); //empty
for (int j = 0; j < k; j++) { assertNull(itemsArr[j]); }
sk.update(" 1"); //single
sk2 = KllItemsSketch.wrap(Memory.wrap(sk.toByteArray()), Comparator.naturalOrder(), serDe);
itemsArr = sk2.getTotalItemsArray();
for (int j = 0; j < k - 1; j++) { assertNull(itemsArr[j]); }
assertEquals(itemsArr[k - 1], " 1");
sk.update(" 2"); //multi
sk2 = KllItemsSketch.wrap(Memory.wrap(sk.toByteArray()), Comparator.naturalOrder(), serDe);
itemsArr = sk2.getTotalItemsArray();
for (int j = 0; j < k - 2; j++) { assertNull(itemsArr[j]); }
assertEquals(itemsArr[k - 1], " 1");
assertEquals(itemsArr[k - 2], " 2");
}
@Test
public void checkHeapAndDirectCompactGetRetainedItemsArray() {
int k = 20;
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
String[] retArr = sk.getRetainedItemsArray();
assertEquals(retArr.length, sk.getNumRetained());
assertEquals(retArr.length, 0);
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(Memory.wrap(sk.toByteArray()), Comparator.naturalOrder(), serDe);
retArr = sk2.getRetainedItemsArray();
assertEquals(retArr.length, sk2.getNumRetained());
assertEquals(retArr.length, 0);
sk.update(" 1");
retArr = sk.getRetainedItemsArray();
assertEquals(retArr.length, sk.getNumRetained());
assertEquals(retArr.length, 1);
assertEquals(retArr[0], " 1");
sk2 = KllItemsSketch.wrap(Memory.wrap(sk.toByteArray()), Comparator.naturalOrder(), serDe);
retArr = sk2.getRetainedItemsArray();
assertEquals(retArr.length, sk2.getNumRetained());
assertEquals(retArr.length, 1);
assertEquals(retArr[0], " 1");
for (int i = 2; i <= 21; i++) { sk.update(Util.intToFixedLengthString(i, 2)); }
retArr = sk.getRetainedItemsArray();
assertEquals(retArr.length, sk.getNumRetained());
assertEquals(retArr.length, 11);
sk2 = KllItemsSketch.wrap(Memory.wrap(sk.toByteArray()), Comparator.naturalOrder(), serDe);
assertEquals(retArr.length, sk2.getNumRetained());
assertEquals(retArr.length, 11);
}
@Test
public void checkMinAndMax() {
int k = 20;
KllItemsSketch<String> sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe);
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(Memory.wrap(sk.toByteArray()), Comparator.naturalOrder(), serDe);
try { sk2.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sk2.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
sk.update(" 1");
sk2 = KllItemsSketch.wrap(Memory.wrap(sk.toByteArray()), Comparator.naturalOrder(), serDe);
assertEquals(sk2.getMaxItem()," 1");
assertEquals(sk2.getMinItem()," 1");
for (int i = 2; i <= 21; i++) { sk.update(Util.intToFixedLengthString(i, 2)); }
sk2 = KllItemsSketch.wrap(Memory.wrap(sk.toByteArray()), Comparator.naturalOrder(), serDe);
assertEquals(sk2.getMaxItem(),"21");
assertEquals(sk2.getMinItem()," 1");
}
@Test
public void checkQuantile() {
KllItemsSketch<String> sk1 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe);
for (int i = 1; i <= 1000; i++) { sk1.update(Util.intToFixedLengthString(i, 4)); }
KllItemsSketch<String> sk2 = KllItemsSketch.wrap(Memory.wrap(sk1.toByteArray()), Comparator.naturalOrder(), serDe);
String med2 = sk2.getQuantile(0.5);
String med1 = sk1.getQuantile(0.5);
assertEquals(med1, med2);
println("Med1: " + med1);
println("Med2: " + med2);
}
@Test
public void checkCompactSingleItemMerge() {
int k = 20;
KllItemsSketch<String> skH1 =
KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); //Heap with 1 (single)
skH1.update("21");
KllItemsSketch<String> skDC1 = //Direct Compact with 1 (single)
KllItemsSketch.wrap(Memory.wrap(skH1.toByteArray()), Comparator.naturalOrder(), serDe);
KllItemsSketch<String> skH20 = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); //Heap with 20
for (int i = 1; i <= 20; i++) { skH20.update(Util.intToFixedLengthString(i, 2)); }
skH20.merge(skDC1);
assertEquals(skH20.getN(), 21);
}
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,392 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDirectDoublesSketchTest.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.kll;
import static org.apache.datasketches.kll.KllSketch.SketchType.DOUBLES_SKETCH;
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 org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.memory.DefaultMemoryRequestServer;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
public class KllDirectDoublesSketchTest {
private static final double PMF_EPS_FOR_K_8 = 0.35; // PMF rank error (epsilon) for k=8
private static final double PMF_EPS_FOR_K_128 = 0.025; // PMF rank error (epsilon) for k=128
private static final double PMF_EPS_FOR_K_256 = 0.013; // PMF rank error (epsilon) for k=256
private static final double NUMERIC_NOISE_TOLERANCE = 1E-6;
private static final DefaultMemoryRequestServer memReqSvr = new DefaultMemoryRequestServer();
@Test
public void empty() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0);
sketch.update(Double.NaN); // this must not change anything
assertTrue(sketch.isEmpty());
assertEquals(sketch.getN(), 0);
assertEquals(sketch.getNumRetained(), 0);
try { sketch.getRank(0.5); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getQuantile(0.5); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getQuantiles(new double[] {0.0, 1.0}); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getPMF(new double[] {0}); fail(); } catch (SketchesArgumentException e) {}
try { sketch.getCDF(new double[0]); fail(); } catch (SketchesArgumentException e) {}
assertNotNull(sketch.toString(true, true));
assertNotNull(sketch.toString());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void getQuantileInvalidArg() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0);
sketch.update(1);
sketch.getQuantile(-1.0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void getQuantilesInvalidArg() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0);
sketch.update(1);
sketch.getQuantiles(new double[] {2.0});
}
@Test
public void oneValue() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0);
sketch.update(1);
assertFalse(sketch.isEmpty());
assertEquals(sketch.getN(), 1);
assertEquals(sketch.getNumRetained(), 1);
assertEquals(sketch.getRank(1, EXCLUSIVE), 0.0);
assertEquals(sketch.getRank(2, EXCLUSIVE), 1.0);
assertEquals(sketch.getMinItem(), 1.0);
assertEquals(sketch.getMaxItem(), 1.0);
assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 1.0);
}
@Test
public void manyValuesEstimationMode() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0);
final int n = 1_000_000;
for (int i = 0; i < n; i++) {
sketch.update(i);
}
assertEquals(sketch.getN(), n);
// test getRank
for (int i = 0; i < n; i++) {
final double trueRank = (double) i / n;
assertEquals(sketch.getRank(i), trueRank, PMF_EPS_FOR_K_256, "for value " + i);
}
// test getPMF
final double[] pmf = sketch.getPMF(new double[] {n / 2.0}); // split at median
assertEquals(pmf.length, 2);
assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256);
assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256);
assertEquals(sketch.getMinItem(), 0.0); // min value is exact
assertEquals(sketch.getMaxItem(), n - 1.0); // max value is exact
// check at every 0.1 percentage point
final double[] ranks = new double[1001];
final double[] reverseFractions = new double[1001]; // check that ordering doesn't matter
for (int i = 0; i <= 1000; i++) {
ranks[i] = (double) i / 1000;
reverseFractions[1000 - i] = ranks[i];
}
final double[] quantiles = sketch.getQuantiles(ranks);
final double[] reverseQuantiles = sketch.getQuantiles(reverseFractions);
double previousQuantile = 0.0;
for (int i = 0; i <= 1000; i++) {
final double quantile = sketch.getQuantile(ranks[i]);
assertEquals(quantile, quantiles[i]);
assertEquals(quantile, reverseQuantiles[1000 - i]);
assertTrue(previousQuantile <= quantile);
previousQuantile = quantile;
}
}
@Test
public void getRankGetCdfGetPmfConsistency() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0);
final int n = 1000;
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);
final double[] pmf = sketch.getPMF(values);
double sumPmf = 0;
for (int i = 0; i < n; i++) {
assertEquals(ranks[i], sketch.getRank(values[i]), NUMERIC_NOISE_TOLERANCE,
"rank vs CDF for value " + i);
sumPmf += pmf[i];
assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i);
}
sumPmf += pmf[n];
assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE);
assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE);
}
@Test
public void merge() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0);
final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(200, 0);
final int n = 10_000;
for (int i = 0; i < n; i++) {
sketch1.update(i * 1.0);
sketch2.update((2 * n - i - 1) * 1.0);
}
assertEquals(sketch1.getMinItem(), 0.0);
assertEquals(sketch1.getMaxItem(), (n - 1) * 1.0);
assertEquals(sketch2.getMinItem(), n * 1.0);
assertEquals(sketch2.getMaxItem(), (2 * n - 1) * 1.0);
sketch1.merge(sketch2);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), 2L * n);
assertEquals(sketch1.getMinItem(), 0.0);
assertEquals(sketch1.getMaxItem(), (2 * n - 1) * 1.0);
assertEquals(sketch1.getQuantile(0.5), n * 1.0, n * PMF_EPS_FOR_K_256);
}
@Test
public void mergeLowerK() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(256, 0);
final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(128, 0);
final int n = 10_000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
sketch2.update(2 * n - i - 1);
}
assertEquals(sketch1.getMinItem(), 0.0f);
assertEquals(sketch1.getMaxItem(), n - 1f);
assertEquals(sketch2.getMinItem(), n);
assertEquals(sketch2.getMaxItem(), 2f * n - 1f);
assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false));
assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true));
sketch1.merge(sketch2);
// sketch1 must get "contaminated" by the lower K in sketch2
assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false));
assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true));
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), 2 * n);
assertEquals(sketch1.getMinItem(), 0.0);
assertEquals(sketch1.getMaxItem(), 2.0 * n - 1.0);
assertEquals(sketch1.getQuantile(0.5), n, n * PMF_EPS_FOR_K_128);
}
@Test
public void mergeEmptyLowerK() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(256, 0);
final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(128, 0);
final int n = 10_000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
}
// rank error should not be affected by a merge with an empty sketch with lower K
final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true);
sketch1.merge(sketch2);
assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), n);
assertEquals(sketch1.getMinItem(), 0.0);
assertEquals(sketch1.getMaxItem(), n - 1.0);
assertEquals(sketch1.getQuantile(0.5), n / 2.0, n / 2 * PMF_EPS_FOR_K_256);
//merge the other way
sketch2.merge(sketch1);
assertFalse(sketch1.isEmpty());
assertEquals(sketch1.getN(), n);
assertEquals(sketch1.getMinItem(), 0.0);
assertEquals(sketch1.getMaxItem(), n - 1.0);
assertEquals(sketch1.getQuantile(0.5), n / 2.0, n / 2 * PMF_EPS_FOR_K_256);
}
@Test
public void mergeExactModeLowerK() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(256, 0);
final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(128, 0);
final int n = 10000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
}
sketch2.update(1);
// rank error should not be affected by a merge with a sketch in exact mode with lower K
final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true);
sketch1.merge(sketch2);
assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge);
}
@Test
public void mergeMinMinValueFromOther() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0);
final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(200, 0);
sketch1.update(1);
sketch2.update(2);
sketch2.merge(sketch1);
assertEquals(sketch2.getMinItem(), 1.0);
}
@Test
public void mergeMinAndMaxFromOther() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0);
final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(200, 0);
for (int i = 1; i <= 1_000_000; i++) {
sketch1.update(i);
}
sketch2.merge(sketch1);
assertEquals(sketch2.getMinItem(), 1);
assertEquals(sketch2.getMaxItem(), 1_000_000);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void kTooSmall() {
getUpdatableDirectDoublesSketch(KllSketch.DEFAULT_M - 1, 0);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void kTooLarge() {
getUpdatableDirectDoublesSketch(KllSketch.MAX_K + 1, 0);
}
@Test
public void minK() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(KllSketch.DEFAULT_M, 0);
for (int i = 0; i < 1000; i++) {
sketch.update(i);
}
assertEquals(sketch.getK(), KllSketch.DEFAULT_M);
assertEquals(sketch.getQuantile(0.5), 500, 500 * PMF_EPS_FOR_K_8);
}
@Test
public void maxK() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(KllSketch.MAX_K, 0);
for (int i = 0; i < 1000; i++) {
sketch.update(i);
}
assertEquals(sketch.getK(), KllSketch.MAX_K);
assertEquals(sketch.getQuantile(0.5), 500, 500 * PMF_EPS_FOR_K_256);
}
@Test
public void serializeDeserializeEmptyViaCompactHeapify() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0);
final byte[] bytes = sketch1.toByteArray(); //compact
final KllDoublesSketch sketch2 = KllDoublesSketch.heapify(Memory.wrap(bytes));
assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(false));
assertTrue(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained());
assertEquals(sketch2.getN(), sketch1.getN());
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
try { sketch2.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch2.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sketch2.currentSerializedSizeBytes(false),
sketch1.currentSerializedSizeBytes(false));
}
@Test
public void serializeDeserializeEmptyViaUpdatableWritableWrap() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0);
final byte[] bytes = KllHelper.toByteArray(sketch1, true);
final KllDoublesSketch sketch2 =
KllDoublesSketch.writableWrap(WritableMemory.writableWrap(bytes),memReqSvr);
assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true));
assertTrue(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained());
assertEquals(sketch2.getN(), sketch1.getN());
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
try { sketch2.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
try { sketch2.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sketch2.currentSerializedSizeBytes(true),
sketch1.currentSerializedSizeBytes(true));
}
@Test
public void serializeDeserializeOneValueViaCompactHeapify() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0);
sketch1.update(1);
final byte[] bytes = sketch1.toByteArray();
final KllDoublesSketch sketch2 = KllDoublesSketch.heapify(Memory.wrap(bytes));
assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(false));
assertFalse(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), 1);
assertEquals(sketch2.getN(), 1);
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
assertTrue(Double.isFinite(sketch2.getMinItem()));
assertTrue(Double.isFinite(sketch2.getMaxItem()));
assertEquals(sketch2.currentSerializedSizeBytes(false), 8 + Double.BYTES);
}
@Test
public void serializeDeserializeOneValueViaUpdatableWritableWrap() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0);
sketch1.update(1);
final byte[] bytes = KllHelper.toByteArray(sketch1, true);
final KllDoublesSketch sketch2 =
KllDoublesSketch.writableWrap(WritableMemory.writableWrap(bytes),memReqSvr);
assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true));
assertFalse(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), 1);
assertEquals(sketch2.getN(), 1);
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
assertEquals(sketch2.getMinItem(), 1.0);
assertEquals(sketch2.getMaxItem(), 1.0);
assertEquals(sketch2.currentSerializedSizeBytes(false), 8 + Double.BYTES);
assertEquals(sketch2.currentSerializedSizeBytes(true), bytes.length);
}
@Test
public void serializeDeserializeFullViaCompactHeapify() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 1000);
final byte[] byteArr1 = sketch1.toByteArray(); //compact
final KllDoublesSketch sketch2 = KllDoublesSketch.heapify(Memory.wrap(byteArr1));
assertEquals(byteArr1.length, sketch1.currentSerializedSizeBytes(false));
assertFalse(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained());
assertEquals(sketch2.getN(), sketch1.getN());
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
assertEquals(sketch2.getMinItem(), sketch1.getMinItem());
assertEquals(sketch2.getMaxItem(), sketch1.getMaxItem());
assertEquals(sketch2.currentSerializedSizeBytes(false), sketch1.currentSerializedSizeBytes(false));
}
@Test
public void serializeDeserializeFullViaUpdatableWritableWrap() {
final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0);
final int n = 1000;
for (int i = 0; i < n; i++) {
sketch1.update(i);
}
final byte[] bytes = KllHelper.toByteArray(sketch1, true); //updatable
final KllDoublesSketch sketch2 =
KllDoublesSketch.writableWrap(WritableMemory.writableWrap(bytes),memReqSvr);
assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true));
assertFalse(sketch2.isEmpty());
assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained());
assertEquals(sketch2.getN(), sketch1.getN());
assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false));
assertEquals(sketch2.getMinItem(), sketch1.getMinItem());
assertEquals(sketch2.getMaxItem(), sketch1.getMaxItem());
assertEquals(sketch2.currentSerializedSizeBytes(true), sketch1.currentSerializedSizeBytes(true));
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void outOfOrderSplitPoints() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0);
sketch.update(0);
sketch.getCDF(new double[] {1, 0});
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void nanSplitPoint() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0);
sketch.update(0);
sketch.getCDF(new double[] {Double.NaN});
}
@Test
public void getQuantiles() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 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 checkSimpleMergeDirect() { //used for troubleshooting
int k = 20;
int n1 = 21;
int n2 = 43;
KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(k);
KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= n1; i++) {
sk1.update(i);
}
for (int i = 1; i <= n2; i++) {
sk2.update(i + 100);
}
println("SK1:");
println(sk1.toString(true, true));
println("SK2:");
println(sk2.toString(true, true));
WritableMemory wmem1 = WritableMemory.writableWrap(KllHelper.toByteArray(sk1, true));
WritableMemory wmem2 = WritableMemory.writableWrap(KllHelper.toByteArray(sk2, true));
KllDoublesSketch dsk1 = KllDoublesSketch.writableWrap(wmem1, memReqSvr);
KllDoublesSketch dsk2 = KllDoublesSketch.writableWrap(wmem2, memReqSvr);
println("BEFORE MERGE");
println(dsk1.toString(true, true));
dsk1.merge(dsk2);
println("AFTER MERGE");
println(dsk1.toString(true, true));
}
@Test
public void checkSketchInitializeDirectDoubleUpdatableMem() {
int k = 20; //don't change this
KllDoublesSketch sk;
KllDoublesSketch sk2;
byte[] compBytes;
WritableMemory wmem;
println("#### CASE: DOUBLE FULL DIRECT FROM UPDATABLE");
sk2 = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= k + 1; i++) { sk2.update(i); }
//println(sk2.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
println(KllPreambleUtil.toString(compBytes, DOUBLES_SKETCH, true));
sk = KllDoublesSketch.writableWrap(wmem, memReqSvr);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), k + 1);
assertEquals(sk.getNumRetained(), 11);
assertFalse(sk.isEmpty());
assertTrue(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 33);
assertEquals(sk.levelsArr.length, 3);
assertEquals(sk.getMaxItem(), 21.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 2);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: DOUBLE EMPTY HEAPIFIED FROM UPDATABLE");
sk2 = KllDoublesSketch.newHeapInstance(k);
//println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
println(KllPreambleUtil.toString(compBytes, DOUBLES_SKETCH, true));
sk = KllDoublesSketch.writableWrap(wmem, memReqSvr);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 0);
assertEquals(sk.getNumRetained(), 0);
assertTrue(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.levelsArr.length, 2);
try { sk.getMaxItem(); fail(); } catch (SketchesArgumentException e) {}
try { sk.getMinItem(); fail(); } catch (SketchesArgumentException e) {}
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
println("#### CASE: DOUBLE SINGLE HEAPIFIED FROM UPDATABLE");
sk2 = KllDoublesSketch.newHeapInstance(k);
sk2.update(1);
//println(sk.toString(true, true));
compBytes = KllHelper.toByteArray(sk2, true);
wmem = WritableMemory.writableWrap(compBytes);
println(KllPreambleUtil.toString(compBytes, DOUBLES_SKETCH, true));
sk = KllDoublesSketch.writableWrap(wmem, memReqSvr);
assertEquals(sk.getK(), k);
assertEquals(sk.getN(), 1);
assertEquals(sk.getNumRetained(), 1);
assertFalse(sk.isEmpty());
assertFalse(sk.isEstimationMode());
assertEquals(sk.getMinK(), k);
assertEquals(sk.getDoubleItemsArray().length, 20);
assertEquals(sk.levelsArr.length, 2);
assertEquals(sk.getMaxItem(), 1.0);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getNumLevels(), 1);
assertFalse(sk.isLevelZeroSorted());
}
@Test
public void checkGetWritableMemory() {
final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 200);
assertEquals(sketch.getK(), 200);
assertEquals(sketch.getN(), 200);
assertFalse(sketch.isEmpty());
assertTrue(sketch.isMemoryUpdatableFormat());
assertFalse(sketch.isEstimationMode());
assertTrue(sketch.isDoublesSketch());
assertFalse(sketch.isLevelZeroSorted());
assertFalse(sketch.isFloatsSketch());
final WritableMemory wmem = sketch.getWritableMemory();
final KllDoublesSketch sk = KllHeapDoublesSketch.heapifyImpl(wmem);
assertEquals(sk.getK(), 200);
assertEquals(sk.getN(), 200);
assertFalse(sk.isEmpty());
assertFalse(sk.isMemoryUpdatableFormat());
assertFalse(sk.isEstimationMode());
assertTrue(sk.isDoublesSketch());
assertFalse(sk.isLevelZeroSorted());
assertFalse(sk.isFloatsSketch());
}
@Test
public void checkReset() {
WritableMemory dstMem = WritableMemory.allocate(6000);
KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(20, dstMem, memReqSvr);
for (int i = 1; i <= 100; i++) { sk.update(i); }
long n1 = sk.getN();
double min1 = sk.getMinItem();
double max1 = sk.getMaxItem();
sk.reset();
for (int i = 1; i <= 100; i++) { sk.update(i); }
long n2 = sk.getN();
double min2 = sk.getMinItem();
double max2 = sk.getMaxItem();
assertEquals(n2, n1);
assertEquals(min2, min1);
assertEquals(max2, max1);
}
@Test
public void checkHeapify() {
WritableMemory dstMem = WritableMemory.allocate(6000);
KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(20, dstMem, memReqSvr);
for (int i = 1; i <= 100; i++) { sk.update(i); }
KllDoublesSketch sk2 = KllHeapDoublesSketch.heapifyImpl(dstMem);
assertEquals(sk2.getMinItem(), 1.0);
assertEquals(sk2.getMaxItem(), 100.0);
}
@Test
public void checkMergeKllDoublesSketch() {
WritableMemory dstMem = WritableMemory.allocate(6000);
KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(20, dstMem, memReqSvr);
for (int i = 1; i <= 21; i++) { sk.update(i); }
KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++ ) { sk2.update(i + 100); }
sk.merge(sk2);
assertEquals(sk.getMinItem(), 1.0);
assertEquals(sk.getMaxItem(), 121.0);
}
@Test
public void checkReverseMergeKllDoubleSketch() {
WritableMemory dstMem = WritableMemory.allocate(6000);
KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(20, dstMem, memReqSvr);
for (int i = 1; i <= 21; i++) { sk.update(i); }
KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++ ) { sk2.update(i + 100); }
sk2.merge(sk);
assertEquals(sk2.getMinItem(), 1.0);
assertEquals(sk2.getMaxItem(), 121.0);
}
@Test
public void checkWritableWrapOfCompactForm() {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20);
for (int i = 1; i <= 21; i++ ) { sk.update(i); }
WritableMemory srcMem = WritableMemory.writableWrap(sk.toByteArray());
KllDoublesSketch sk2 = KllDoublesSketch.writableWrap(srcMem, memReqSvr);
assertEquals(sk2.getMinItem(), 1.0);
assertEquals(sk2.getMaxItem(), 21.0);
}
@Test
public void checkReadOnlyExceptions() {
int k = 20;
double[] dblArr = new double[0];
double dblV = 1.0f;
int idx = 1;
boolean bool = true;
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k);
KllDoublesSketch sk2 = KllDoublesSketch.wrap(Memory.wrap(sk.toByteArray()));
try { sk2.incN(); fail(); } catch (SketchesArgumentException e) { }
try { sk2.incNumLevels(); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setDoubleItemsArray(dblArr); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setDoubleItemsArrayAt(idx, dblV); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setLevelZeroSorted(bool); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setMaxItem(dblV); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setMinItem(dblV); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setMinK(idx); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setN(idx); fail(); } catch (SketchesArgumentException e) { }
try { sk2.setNumLevels(idx); fail(); } catch (SketchesArgumentException e) { }
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkMergeExceptions() {
KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(20);
WritableMemory srcMem1 = WritableMemory.writableWrap(sk1.toByteArray());
KllDoublesSketch sk2 = KllDoublesSketch.writableWrap(srcMem1, memReqSvr);
sk2.merge(sk1);
}
@Test
public void checkMergeExceptionsWrongType() {
KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(20);
KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(20);
try { sk1.merge(sk2); fail(); } catch (ClassCastException e) { }
try { sk2.merge(sk1); fail(); } catch (ClassCastException e) { }
}
private static KllDoublesSketch getUpdatableDirectDoublesSketch(final int k, final int n) {
KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k);
for (int i = 1; i <= n; i++) { sk.update(i); }
byte[] byteArr = KllHelper.toByteArray(sk, true);
WritableMemory wmem = WritableMemory.writableWrap(byteArr);
KllDoublesSketch ddsk = KllDoublesSketch.writableWrap(wmem, memReqSvr);
return ddsk;
}
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,393 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/kll/KllDoublesValidationTest.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.kll;
import static org.apache.datasketches.common.Util.isOdd;
import org.testng.Assert;
import org.testng.annotations.Test;
/* A test record contains:
0. testIndex
1. K
2. N
3. stride (for generating the input)
4. numLevels
5. numSamples
6. hash of the retained samples
*/
// These results are for the version that delays the roll up until the next value comes in.
// The @Test annotations have to be enabled to use this class and a section in KllDoublesHelper also
// needs to be enabled.
@SuppressWarnings("unused")
public class KllDoublesValidationTest {
//Used only with manual running of checkTestResults(..)
private static final long[] correctResultsWithReset = {
0, 200, 180, 3246533, 1, 180, 1098352976109474698L,
1, 200, 198, 8349603, 1, 198, 686681527497651888L,
2, 200, 217, 676491, 2, 117, 495856134049157644L,
3, 200, 238, 3204507, 2, 138, 44453438498725402L,
4, 200, 261, 2459373, 2, 161, 719830627391926938L,
5, 200, 287, 5902143, 2, 187, 389303173170515580L,
6, 200, 315, 5188793, 2, 215, 985218890825795000L,
7, 200, 346, 801923, 2, 246, 589362992166904413L,
8, 200, 380, 2466269, 2, 280, 1081848693781775853L,
9, 200, 418, 5968041, 2, 318, 533825689515788397L,
10, 200, 459, 3230027, 2, 243, 937332670315558786L,
11, 200, 504, 5125875, 2, 288, 1019197831515566845L,
12, 200, 554, 4195571, 3, 230, 797351479150148224L,
13, 200, 609, 2221181, 3, 285, 451246040374318529L,
14, 200, 669, 5865503, 3, 345, 253851269470815909L,
15, 200, 735, 831703, 3, 411, 491974970526372303L,
16, 200, 808, 4830785, 3, 327, 1032107507126916277L,
17, 200, 888, 1356257, 3, 407, 215225420986342944L,
18, 200, 976, 952071, 3, 417, 600280049738270697L,
19, 200, 1073, 6729833, 3, 397, 341758522977365969L,
20, 200, 1180, 6017925, 3, 406, 1080227312339182949L,
21, 200, 1298, 4229891, 3, 401, 1092460534756675086L,
22, 200, 1427, 7264889, 4, 320, 884533400696890024L,
23, 200, 1569, 5836327, 4, 462, 660575800011134382L,
24, 200, 1725, 5950087, 4, 416, 669373957401387528L,
25, 200, 1897, 2692555, 4, 406, 607308667566496888L,
26, 200, 2086, 1512443, 4, 459, 744260340112029032L,
27, 200, 2294, 2681171, 4, 434, 199120609113802485L,
28, 200, 2523, 3726521, 4, 450, 570993497599288304L,
29, 200, 2775, 2695247, 4, 442, 306717093329516310L,
30, 200, 3052, 5751175, 5, 400, 256024589545754217L,
31, 200, 3357, 1148897, 5, 514, 507276662329207479L,
32, 200, 3692, 484127, 5, 457, 1082660223488175122L,
33, 200, 4061, 6414559, 5, 451, 620820308918522117L,
34, 200, 4467, 5587461, 5, 466, 121975084804459305L,
35, 200, 4913, 1615017, 5, 483, 152986529342916376L,
36, 200, 5404, 6508535, 5, 492, 858526451332425960L,
37, 200, 5944, 2991657, 5, 492, 624906434274621995L,
38, 200, 6538, 6736565, 6, 511, 589153542019036049L,
39, 200, 7191, 1579893, 6, 507, 10255312374117907L,
40, 200, 7910, 412509, 6, 538, 570863587164194186L,
41, 200, 8701, 1112089, 6, 477, 553100668286355347L,
42, 200, 9571, 1258813, 6, 526, 344845406406036297L,
43, 200, 10528, 1980049, 6, 508, 411846569527905064L,
44, 200, 11580, 2167127, 6, 520, 966876726203675488L,
45, 200, 12738, 1975435, 7, 561, 724125506920592732L,
46, 200, 14011, 4289627, 7, 560, 753686005174215572L,
47, 200, 15412, 5384001, 7, 494, 551637841878573955L,
48, 200, 16953, 2902685, 7, 560, 94602851752354802L,
49, 200, 18648, 4806445, 7, 562, 597672400688514221L,
50, 200, 20512, 2085, 7, 529, 417280161591969960L,
51, 200, 22563, 6375939, 7, 558, 11300453985206678L,
52, 200, 24819, 7837057, 7, 559, 283668599967437754L,
53, 200, 27300, 6607975, 8, 561, 122183647493325363L,
54, 200, 30030, 1519191, 8, 550, 1145227891427321202L,
55, 200, 33033, 808061, 8, 568, 71070843834364939L,
56, 200, 36336, 2653529, 8, 570, 450311772805359006L,
57, 200, 39969, 2188957, 8, 561, 269670427054904115L,
58, 200, 43965, 5885655, 8, 539, 1039064186324091890L,
59, 200, 48361, 6185889, 8, 574, 178055275082387938L,
60, 200, 53197, 208767, 9, 579, 139766040442973048L,
61, 200, 58516, 2551345, 9, 569, 322655279254252950L,
62, 200, 64367, 1950873, 9, 569, 101542216315768285L,
63, 200, 70803, 2950429, 9, 582, 72294008568551853L,
64, 200, 77883, 3993977, 9, 572, 299014330559512530L,
65, 200, 85671, 428871, 9, 585, 491351721800568188L,
66, 200, 94238, 6740849, 9, 577, 656204268858348899L,
67, 200, 103661, 2315497, 9, 562, 829926273188300764L,
68, 200, 114027, 5212835, 10, 581, 542222554617639557L,
69, 200, 125429, 4213475, 10, 593, 713339189579860773L,
70, 200, 137971, 2411583, 10, 592, 649651658985845357L,
71, 200, 151768, 5243307, 10, 567, 1017459402785275179L,
72, 200, 166944, 2468367, 10, 593, 115034451827634398L,
73, 200, 183638, 2210923, 10, 583, 365735165000548572L,
74, 200, 202001, 321257, 10, 591, 928479940794929153L,
75, 200, 222201, 8185105, 11, 600, 780163958693677795L,
76, 200, 244421, 6205349, 11, 598, 132454307780236135L,
77, 200, 268863, 3165901, 11, 600, 369824066179493948L,
78, 200, 295749, 2831723, 11, 595, 80968411797441666L,
79, 200, 325323, 464193, 11, 594, 125773061716381917L,
80, 200, 357855, 7499035, 11, 576, 994150328579932916L,
81, 200, 393640, 1514479, 11, 596, 111092193875842594L,
82, 200, 433004, 668493, 12, 607, 497338041653302784L,
83, 200, 476304, 3174931, 12, 606, 845986926165673887L,
84, 200, 523934, 914611, 12, 605, 354993119685278556L,
85, 200, 576327, 7270385, 12, 602, 937679531753465428L,
86, 200, 633959, 1956979, 12, 598, 659413123921208266L,
87, 200, 697354, 3137635, 12, 606, 874228711599628459L,
88, 200, 767089, 214923, 12, 608, 1077644643342432307L,
89, 200, 843797, 3084545, 13, 612, 79317113064339979L,
90, 200, 928176, 7800899, 13, 612, 357414065779796772L,
91, 200, 1020993, 6717253, 13, 615, 532723577905833296L,
92, 200, 1123092, 5543015, 13, 614, 508695073250223746L,
93, 200, 1235401, 298785, 13, 616, 34344606952783179L,
94, 200, 1358941, 4530313, 13, 607, 169924026179364121L,
95, 200, 1494835, 4406457, 13, 612, 1026773494313671061L,
96, 200, 1644318, 1540983, 13, 614, 423454640036650614L,
97, 200, 1808749, 7999631, 14, 624, 466122870338520329L,
98, 200, 1989623, 4295537, 14, 621, 609309853701283445L,
99, 200, 2188585, 7379971, 14, 622, 141739898871015642L,
100, 200, 2407443, 6188931, 14, 621, 22515080776738923L,
101, 200, 2648187, 6701239, 14, 619, 257441864177795548L,
102, 200, 2913005, 2238709, 14, 623, 867028825821064773L,
103, 200, 3204305, 5371075, 14, 625, 1110615471273395112L,
104, 200, 3524735, 7017341, 15, 631, 619518037415974467L,
105, 200, 3877208, 323337, 15, 633, 513230912593541122L,
106, 200, 4264928, 6172471, 15, 628, 885861662583325072L,
107, 200, 4691420, 5653803, 15, 633, 754052473303005204L,
108, 200, 5160562, 1385265, 15, 630, 294993765757975100L,
109, 200, 5676618, 4350899, 15, 617, 1073144684944932303L,
110, 200, 6244279, 1272235, 15, 630, 308982934296855020L,
111, 200, 6868706, 1763939, 16, 638, 356231694823272867L,
112, 200, 7555576, 3703411, 16, 636, 20043268926300101L,
113, 200, 8311133, 6554171, 16, 637, 121111429906734123L,
};
private static int[] makeInputArray(int n, int stride) {
assert isOdd(stride);
int mask = (1 << 23) - 1;
int cur = 0;
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
cur += stride;
cur &= mask;
arr[i] = cur;
}
return arr;
}
//@Test //only enabled to test the above makeInputArray(..)
public void testMakeInputArray() {
final int[] array = { 3654721, 7309442, 2575555, 6230276, 1496389, 5151110 };
Assert.assertEquals(makeInputArray(6, 3654721), array);
}
private static long simpleHashOfSubArray(final double[] arr, final int start, final int subLength) {
final long multiplier = 738219921; // an arbitrary odd 30-bit number
final long mask60 = (1L << 60) - 1;
long accum = 0;
for (int i = start; i < (start + subLength); i++) {
accum += (long) arr[i];
accum *= multiplier;
accum &= mask60;
accum ^= accum >> 30;
}
return accum;
}
//@Test //only enabled to test the above simpleHashOfSubArray(..)
public void testHash() {
double[] array = { 907500, 944104, 807020, 219921, 678370, 955217, 426885 };
Assert.assertEquals(simpleHashOfSubArray(array, 1, 5), 1141543353991880193L);
}
/*
* Please note that this test should be run with a modified version of KllDoublesHelper
* that chooses directions alternately instead of randomly.
* See the instructions at the bottom of that class.
*/
//@Test //NEED TO ENABLE HERE AND BELOW FOR VALIDATION
public void checkTestResults() {
int numTests = correctResultsWithReset.length / 7;
for (int testI = 0; testI < numTests; testI++) {
//KllDoublesHelper.nextOffset = 0; //NEED TO ENABLE
assert (int) correctResultsWithReset[7 * testI] == testI;
int k = (int) correctResultsWithReset[(7 * testI) + 1];
int n = (int) correctResultsWithReset[(7 * testI) + 2];
int stride = (int) correctResultsWithReset[(7 * testI) + 3];
int[] inputArray = makeInputArray(n, stride);
KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(k);
for (int i = 0; i < n; i++) {
sketch.update(inputArray[i]);
}
int numLevels = sketch.getNumLevels();
int numSamples = sketch.getNumRetained();
int[] levels = sketch.getLevelsArray(sketch.sketchStructure);
long hashedSamples = simpleHashOfSubArray(sketch.getDoubleItemsArray(), levels[0], numSamples);
System.out.print(testI);
assert correctResultsWithReset[(7 * testI) + 4] == numLevels;
assert correctResultsWithReset[(7 * testI) + 5] == numSamples;
assert correctResultsWithReset[7 * testI + 6] == hashedSamples;
if (correctResultsWithReset[(7 * testI) + 6] == hashedSamples) {
System.out.println(" pass");
} else {
System.out.print(" " + correctResultsWithReset[(7 * testI) + 6] + " != " + hashedSamples);
System.out.println(" fail");
System.out.println(sketch.toString(true, true));
break;
}
}
}
}
| 2,394 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/sampling/ReservoirItemsUnionTest.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.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.ArrayList;
import org.testng.annotations.Test;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfNumbersSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
// Tests mostly focus on Long since other types are already tested in ReservoirItemsSketchTest.
public class ReservoirItemsUnionTest {
@Test
public void checkEmptyUnion() {
final ReservoirItemsUnion<Long> riu = ReservoirItemsUnion.newInstance(1024);
final byte[] unionBytes = riu.toByteArray(new ArrayOfLongsSerDe());
// will intentionally break if changing empty union serialization
assertEquals(unionBytes.length, 8);
println(riu.toString());
}
@Test
public void checkInstantiation() {
final int n = 100;
final int k = 25;
// create empty unions
ReservoirItemsUnion<Long> riu = ReservoirItemsUnion.newInstance(k);
assertNull(riu.getResult());
riu.update(5L);
assertNotNull(riu.getResult());
// pass in a sketch, as both an object and memory
final ReservoirItemsSketch<Long> ris = ReservoirItemsSketch.newInstance(k);
for (long i = 0; i < n; ++i) {
ris.update(i);
}
riu.reset();
assertEquals(riu.getResult().getN(), 0);
riu.update(ris);
assertEquals(riu.getResult().getN(), ris.getN());
final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
final byte[] sketchBytes = ris.toByteArray(serDe); // only the gadget is serialized
final Memory mem = Memory.wrap(sketchBytes);
riu = ReservoirItemsUnion.newInstance(ris.getK());
riu.update(mem, serDe);
assertNotNull(riu.getResult());
println(riu.toString());
}
/*
@Test
public void checkReadOnlyInstantiation() {
final int k = 100;
final ReservoirItemsUnion<Long> union = ReservoirItemsUnion.newInstance(k);
for (long i = 0; i < 2 * k; ++i) {
union.update(i);
}
final byte[] unionBytes = union.toByteArray(new ArrayOfLongsSerDe());
final Memory mem = Memory.wrap(unionBytes);
final ReservoirItemsUnion<Long> riu;
riu = ReservoirItemsUnion.heapify(mem, new ArrayOfLongsSerDe());
assertNotNull(riu);
assertEquals(riu.getMaxK(), k);
ReservoirItemsSketchTest.validateReservoirEquality(riu.getResult(), union.getResult());
}
*/
@Test
public void checkNullUpdate() {
final ReservoirItemsUnion<Long> riu = ReservoirItemsUnion.newInstance(1024);
assertNull(riu.getResult());
// null sketch
final ReservoirItemsSketch<Long> nullSketch = null;
riu.update(nullSketch);
assertNull(riu.getResult());
// null memory
riu.update(null, new ArrayOfLongsSerDe());
assertNull(riu.getResult());
// null item
riu.update((Long) null);
assertNull(riu.getResult());
// valid input
riu.update(5L);
assertNotNull(riu.getResult());
}
@Test
public void checkSerialization() {
final int n = 100;
final int k = 25;
final ReservoirItemsUnion<Long> riu = ReservoirItemsUnion.newInstance(k);
for (long i = 0; i < n; ++i) {
riu.update(i);
}
final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
final byte[] unionBytes = riu.toByteArray(serDe);
final Memory mem = Memory.wrap(unionBytes);
println(PreambleUtil.preambleToString(mem));
final ReservoirItemsUnion<Long> rebuiltUnion = ReservoirItemsUnion.heapify(mem, serDe);
assertEquals(riu.getMaxK(), rebuiltUnion.getMaxK());
ReservoirItemsSketchTest.validateReservoirEquality(riu.getResult(), rebuiltUnion.getResult());
}
@Test
public void checkVersionConversionWithEmptyGadget() {
final int k = 32768;
final short encK = ReservoirSize.computeSize(k);
final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
final ReservoirItemsUnion<String> riu = ReservoirItemsUnion.newInstance(k);
final byte[] unionBytesOrig = riu.toByteArray(serDe);
// get a new byte[], manually revert to v1, then reconstruct
final byte[] unionBytes = riu.toByteArray(serDe);
final WritableMemory unionMem = WritableMemory.writableWrap(unionBytes);
unionMem.putByte(SER_VER_BYTE, (byte) 1);
unionMem.putInt(RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes
unionMem.putShort(RESERVOIR_SIZE_SHORT, encK);
println(PreambleUtil.preambleToString(unionMem));
final ReservoirItemsUnion<String> rebuilt = ReservoirItemsUnion.heapify(unionMem, serDe);
final byte[] rebuiltBytes = rebuilt.toByteArray(serDe);
assertEquals(unionBytesOrig.length, rebuiltBytes.length);
for (int i = 0; i < unionBytesOrig.length; ++i) {
assertEquals(unionBytesOrig[i], rebuiltBytes[i]);
}
}
@Test
public void checkVersionConversionWithGadget() {
final long n = 32;
final int k = 256;
final short encK = ReservoirSize.computeSize(k);
final ArrayOfNumbersSerDe serDe = new ArrayOfNumbersSerDe();
final ReservoirItemsUnion<Number> rlu = ReservoirItemsUnion.newInstance(k);
for (long i = 0; i < n; ++i) {
rlu.update(i);
}
final byte[] unionBytesOrig = rlu.toByteArray(serDe);
// get a new byte[], manually revert to v1, then reconstruct
final byte[] unionBytes = rlu.toByteArray(serDe);
final WritableMemory unionMem = WritableMemory.writableWrap(unionBytes);
unionMem.putByte(SER_VER_BYTE, (byte) 1);
unionMem.putInt(RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes
unionMem.putShort(RESERVOIR_SIZE_SHORT, encK);
// force gadget header to v1, too
final int offset = Family.RESERVOIR_UNION.getMaxPreLongs() << 3;
unionMem.putByte(offset + SER_VER_BYTE, (byte) 1);
unionMem.putInt(offset + RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes
unionMem.putShort(offset + RESERVOIR_SIZE_SHORT, encK);
final ReservoirItemsUnion<Number> rebuilt = ReservoirItemsUnion.heapify(unionMem, serDe);
final byte[] rebuiltBytes = rebuilt.toByteArray(serDe);
assertEquals(unionBytesOrig.length, rebuiltBytes.length);
for (int i = 0; i < unionBytesOrig.length; ++i) {
assertEquals(unionBytesOrig[i], rebuiltBytes[i]);
}
}
//@SuppressWarnings("null") // this is the point of the test
@Test(expectedExceptions = NullPointerException.class)
public void checkNullMemoryInstantiation() {
ReservoirItemsUnion.heapify(null, new ArrayOfStringsSerDe());
}
@Test
public void checkDownsampledUpdate() {
final int bigK = 1024;
final int smallK = 256;
final int n = 2048;
final ReservoirItemsSketch<Long> sketch1 = getBasicSketch(n, smallK);
final ReservoirItemsSketch<Long> sketch2 = getBasicSketch(2 * n, bigK);
final ReservoirItemsUnion<Long> riu = ReservoirItemsUnion.newInstance(smallK);
assertEquals(riu.getMaxK(), smallK);
riu.update(sketch1);
assertNotNull(riu.getResult());
assertEquals(riu.getResult().getK(), smallK);
riu.update(sketch2);
assertEquals(riu.getResult().getK(), smallK);
assertEquals(riu.getResult().getNumSamples(), smallK);
}
@Test
public void checkUnionResetWithInitialSmallK() {
final int maxK = 25;
final int sketchK = 10;
final ReservoirItemsUnion<Long> riu = ReservoirItemsUnion.newInstance(maxK);
ReservoirItemsSketch<Long> ris = getBasicSketch(2 * sketchK, sketchK); // in sampling mode
riu.update(ris);
assertEquals(riu.getMaxK(), maxK);
assertNotNull(riu.getResult());
assertEquals(riu.getResult().getK(), sketchK);
riu.reset();
assertNotNull(riu.getResult());
// feed in sketch in sampling mode, with larger k than old gadget
ris = getBasicSketch(2 * maxK, maxK + 1);
riu.update(ris);
assertEquals(riu.getMaxK(), maxK);
assertNotNull(riu.getResult());
assertEquals(riu.getResult().getK(), maxK);
}
@Test
public void checkNewGadget() {
final int maxK = 1024;
final int bigK = 1536;
final int smallK = 128;
// downsample input sketch, use as gadget (exact mode, but irrelevant here)
final ReservoirItemsSketch<Long> bigKSketch = getBasicSketch(maxK / 2, bigK);
final byte[] bigKBytes = bigKSketch.toByteArray(new ArrayOfLongsSerDe());
final Memory bigKMem = Memory.wrap(bigKBytes);
ReservoirItemsUnion<Long> riu = ReservoirItemsUnion.newInstance(maxK);
riu.update(bigKMem, new ArrayOfLongsSerDe());
assertNotNull(riu.getResult());
assertEquals(riu.getResult().getK(), maxK);
assertEquals(riu.getResult().getN(), maxK / 2);
// sketch k < maxK but in sampling mode
final ReservoirItemsSketch<Long> smallKSketch = getBasicSketch(maxK, smallK);
final byte[] smallKBytes = smallKSketch.toByteArray(new ArrayOfLongsSerDe());
final Memory smallKMem = Memory.wrap(smallKBytes);
riu = ReservoirItemsUnion.newInstance(maxK);
riu.update(smallKMem, new ArrayOfLongsSerDe());
assertNotNull(riu.getResult());
assertTrue(riu.getResult().getK() < maxK);
assertEquals(riu.getResult().getK(), smallK);
assertEquals(riu.getResult().getN(), maxK);
// sketch k < maxK and in exact mode
final ReservoirItemsSketch<Long> smallKExactSketch = getBasicSketch(smallK, smallK);
final byte[] smallKExactBytes = smallKExactSketch.toByteArray(new ArrayOfLongsSerDe());
final Memory smallKExactMem = Memory.wrap(smallKExactBytes);
riu = ReservoirItemsUnion.newInstance(maxK);
riu.update(smallKExactMem, new ArrayOfLongsSerDe());
assertNotNull(riu.getResult());
assertEquals(riu.getResult().getK(), maxK);
assertEquals(riu.getResult().getN(), smallK);
}
@Test
public void checkListInputUpdate() {
final int k = 32;
final int n = 64;
final ReservoirItemsUnion<Integer> riu = ReservoirItemsUnion.newInstance(k);
ArrayList<Integer> data = new ArrayList<>(k);
for (int i = 0; i < k; ++i) {
data.add(i);
}
riu.update(n, k, data);
assertNotNull(riu.getResult());
assertEquals(riu.getResult().getN(), n);
assertEquals(riu.getResult().getK(), k); // power of 2, so exact
data = new ArrayList<>(2 * k);
for (int i = 0; i < (2 * k); ++i) {
data.add(i);
}
riu.update(10 * n, 2 * k, data);
assertEquals(riu.getResult().getN(), 11 * n); // total = n + 10n
assertEquals(riu.getResult().getK(), k); // should have downsampled the 2nd
}
@Test
public void checkStandardMergeNoCopy() {
final int k = 1024;
final int n1 = 256;
final int n2 = 256;
final ReservoirItemsSketch<Long> sketch1 = getBasicSketch(n1, k);
final ReservoirItemsSketch<Long> sketch2 = getBasicSketch(n2, k);
final ReservoirItemsUnion<Long> riu = ReservoirItemsUnion.newInstance(k);
riu.update(sketch1);
riu.update(sketch2);
assertNotNull(riu.getResult());
assertEquals(riu.getResult().getK(), k);
assertEquals(riu.getResult().getN(), n1 + n2);
assertEquals(riu.getResult().getNumSamples(), n1 + n2);
// creating from Memory should avoid a copy
final int n3 = 2048;
final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
final ReservoirItemsSketch<Long> sketch3 = getBasicSketch(n3, k);
final byte[] sketch3Bytes = sketch3.toByteArray(serDe);
final Memory mem = Memory.wrap(sketch3Bytes);
riu.update(mem, serDe);
assertEquals(riu.getResult().getK(), k);
assertEquals(riu.getResult().getN(), n1 + n2 + n3);
assertEquals(riu.getResult().getNumSamples(), k);
}
@Test
public void checkStandardMergeWithCopy() {
// this will check the other code route to a standard merge,
// but will copy sketch2 to be non-destructive.
final int k = 1024;
final int n1 = 768;
final int n2 = 2048;
final ReservoirItemsSketch<Long> sketch1 = getBasicSketch(n1, k);
final ReservoirItemsSketch<Long> sketch2 = getBasicSketch(n2, k);
final ReservoirItemsUnion<Long> riu = ReservoirItemsUnion.newInstance(k);
riu.update(sketch1);
riu.update(sketch2);
riu.update(10L);
assertNotNull(riu.getResult());
assertEquals(riu.getResult().getK(), k);
assertEquals(riu.getResult().getN(), n1 + n2 + 1);
assertEquals(riu.getResult().getNumSamples(), k);
}
@Test
public void checkWeightedMerge() {
final int k = 1024;
final int n1 = 16384;
final int n2 = 2048;
final ReservoirItemsSketch<Long> sketch1 = getBasicSketch(n1, k);
final ReservoirItemsSketch<Long> sketch2 = getBasicSketch(n2, k);
ReservoirItemsUnion<Long> riu = ReservoirItemsUnion.newInstance(k);
riu.update(sketch1);
riu.update(sketch2);
assertNotNull(riu.getResult());
assertEquals(riu.getResult().getK(), k);
assertEquals(riu.getResult().getN(), n1 + n2);
assertEquals(riu.getResult().getNumSamples(), k);
// now merge into the sketch for updating -- results should match
riu = ReservoirItemsUnion.newInstance(k);
riu.update(sketch2);
riu.update(sketch1);
assertNotNull(riu.getResult());
assertEquals(riu.getResult().getK(), k);
assertEquals(riu.getResult().getN(), n1 + n2);
assertEquals(riu.getResult().getNumSamples(), k);
}
@Test
public void checkPolymorphicType() {
final int k = 4;
final ReservoirItemsUnion<Number> riu = ReservoirItemsUnion.newInstance(k);
riu.update(2.2);
riu.update(6L);
final ReservoirItemsSketch<Number> ris = ReservoirItemsSketch.newInstance(k);
ris.update(1);
ris.update(3.7f);
riu.update(ris);
final ArrayOfNumbersSerDe serDe = new ArrayOfNumbersSerDe();
final byte[] sketchBytes = riu.toByteArray(serDe, Number.class);
final Memory mem = Memory.wrap(sketchBytes);
final ReservoirItemsUnion<Number> rebuiltRiu = ReservoirItemsUnion.heapify(mem, serDe);
// validateReservoirEquality can't handle abstract base class
assertNotNull(riu.getResult());
assertNotNull(rebuiltRiu.getResult());
assertEquals(riu.getResult().getNumSamples(), rebuiltRiu.getResult().getNumSamples());
final Number[] samples1 = riu.getResult().getSamples(Number.class);
final Number[] samples2 = rebuiltRiu.getResult().getSamples(Number.class);
assertNotNull(samples1);
assertNotNull(samples2);
assertEquals(samples1.length, samples2.length);
for (int i = 0; i < samples1.length; ++i) {
assertEquals(samples1[i], samples2[i]);
}
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadPreLongs() {
final ReservoirItemsUnion<Number> riu = ReservoirItemsUnion.newInstance(1024);
final WritableMemory mem = WritableMemory.writableWrap(riu.toByteArray(new ArrayOfNumbersSerDe()));
mem.putByte(PREAMBLE_LONGS_BYTE, (byte) 0); // corrupt the preLongs count
ReservoirItemsUnion.heapify(mem, new ArrayOfNumbersSerDe());
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
final ReservoirItemsUnion<String> riu = ReservoirItemsUnion.newInstance(1024);
final WritableMemory mem = WritableMemory.writableWrap(riu.toByteArray(new ArrayOfStringsSerDe()));
mem.putByte(SER_VER_BYTE, (byte) 0); // corrupt the serialization version
ReservoirItemsUnion.heapify(mem, new ArrayOfStringsSerDe());
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadFamily() {
final ReservoirItemsUnion<Double> rlu = ReservoirItemsUnion.newInstance(1024);
final WritableMemory mem = WritableMemory.writableWrap(rlu.toByteArray(new ArrayOfDoublesSerDe()));
mem.putByte(FAMILY_BYTE, (byte) 0); // corrupt the family ID
ReservoirItemsUnion.heapify(mem, new ArrayOfDoublesSerDe());
fail();
}
private static ReservoirItemsSketch<Long> getBasicSketch(final int n, final int k) {
final ReservoirItemsSketch<Long> rls = ReservoirItemsSketch.newInstance(k);
for (long i = 0; i < n; ++i) {
rls.update(i);
}
return rls;
}
/**
* 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,395 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/sampling/ReservoirSizeTest.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.assertTrue;
import static org.testng.Assert.fail;
import org.apache.datasketches.common.SketchesArgumentException;
import org.testng.annotations.Test;
public class ReservoirSizeTest {
@Test
public void checkComputeSize() {
short enc;
enc = ReservoirSize.computeSize(1);
assertEquals(enc, (short) 0x0000);
enc = ReservoirSize.computeSize(128);
assertEquals(enc, (short) 0x3800);
enc = ReservoirSize.computeSize(200);
assertEquals(enc, (short) 0x3C80);
enc = ReservoirSize.computeSize(4097);
assertEquals(enc, (short) 0x6001);
// NOTE: 0x61C4 is exact but Java seems to have numerical precision issues
enc = ReservoirSize.computeSize(5000);
assertEquals(enc, (short) 0x61C5);
enc = ReservoirSize.computeSize(25000);
assertEquals(enc, (short) 0x7436);
// Encoding cannot represent 32767 with an exponent of 14, so need to go to the next power of 2
enc = ReservoirSize.computeSize(32767);
assertEquals(enc, (short) 0x7800);
enc = ReservoirSize.computeSize(95342);
assertEquals(enc, (short) 0x83A4);
try {
ReservoirSize.computeSize(-1);
fail();
} catch (final SketchesArgumentException e) {
assertTrue(e.getMessage().startsWith("Can only encode strictly positive sketch sizes less than"));
}
}
@Test
public void checkDecodeValue() {
int dec;
dec = ReservoirSize.decodeValue((short) 0x0000);
assertEquals(dec, 1);
dec = ReservoirSize.decodeValue((short) 0x3800);
assertEquals(dec, 128);
dec = ReservoirSize.decodeValue((short) 0x3C80);
assertEquals(dec, 200);
dec = ReservoirSize.decodeValue((short) 0x6001);
assertEquals(dec, 4098);
dec = ReservoirSize.decodeValue((short) 0x61C4);
assertEquals(dec, 5000);
dec = ReservoirSize.decodeValue((short) 0x7435);
assertEquals(dec, 25000);
dec = ReservoirSize.decodeValue((short) 0x83A4);
assertEquals(dec, 95360);
try {
ReservoirSize.decodeValue((short) -1);
fail();
} catch (final SketchesArgumentException e) {
assertTrue(e.getMessage().startsWith("Maximum valid encoded value is "));
}
}
@Test
public void checkRelativeError() {
// Generate some random values and ensure the relative error of the decoded result is
// within epsilon (eps) of the target.
// This condition should always hold regardless of the random seed used.
final double eps = 1.0 / ReservoirSize.BINS_PER_OCTAVE;
final int maxValue = 2146959359; // based on MAX_ABS_VALUE
final int numIters = 100;
for (int i = 0; i < numIters; ++i) {
final int input = SamplingUtil.rand().nextInt(maxValue) + 1;
final int result = ReservoirSize.decodeValue(ReservoirSize.computeSize(input));
// result must be no smaller than input
assertTrue(result >= input, "encoded/decoded result < input: " + result + " vs "
+ input + " (iter " + i + ")");
// cap on max error
final double relativeError = ((double) result - input) / input;
assertTrue(relativeError <= eps, "Error exceeds tolerance. Expected relative error <= "
+ eps + "; " + "found " + relativeError);
}
}
}
| 2,396 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/sampling/ReservoirItemsSketchTest.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.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.math.BigDecimal;
import java.util.ArrayList;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfNumbersSerDe;
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.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 ReservoirItemsSketchTest {
private static final double EPS = 1e-8;
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkInvalidK() {
ReservoirItemsSketch.<Integer>newInstance(0);
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
final WritableMemory mem = getBasicSerializedLongsRIS();
mem.putByte(SER_VER_BYTE, (byte) 0); // corrupt the serialization version
ReservoirItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadFamily() {
final WritableMemory mem = getBasicSerializedLongsRIS();
mem.putByte(FAMILY_BYTE, (byte) Family.ALPHA.getID()); // corrupt the family ID
try {
PreambleUtil.preambleToString(mem);
} catch (final SketchesArgumentException e) {
assertTrue(e.getMessage().startsWith("Inspecting preamble with Sampling family"));
}
ReservoirItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadPreLongs() {
final WritableMemory mem = getBasicSerializedLongsRIS();
mem.putByte(PREAMBLE_LONGS_BYTE, (byte) 0); // corrupt the preLongs count
ReservoirItemsSketch.heapify(mem, new ArrayOfLongsSerDe());
fail();
}
@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 checkEmptySketch() {
final ReservoirItemsSketch<String> ris = ReservoirItemsSketch.newInstance(5);
assertTrue(ris.getSamples() == null);
final byte[] sketchBytes = ris.toByteArray(new ArrayOfStringsSerDe());
final Memory mem = Memory.wrap(sketchBytes);
// only minPreLongs bytes and should deserialize to empty
assertEquals(sketchBytes.length, Family.RESERVOIR.getMinPreLongs() << 3);
final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
final ReservoirItemsSketch<String> loadedRis = ReservoirItemsSketch.heapify(mem, serDe);
assertEquals(loadedRis.getNumSamples(), 0);
println("Empty sketch:");
println(" Preamble:");
println(PreambleUtil.preambleToString(mem));
println(" Sketch:");
println(ris.toString());
}
@Test
public void checkUnderFullReservoir() {
final int k = 128;
final int n = 64;
final ReservoirItemsSketch<String> ris = ReservoirItemsSketch.newInstance(k);
int expectedLength = 0;
for (int i = 0; i < n; ++i) {
final String intStr = Integer.toString(i);
expectedLength += intStr.length() + Integer.BYTES;
ris.update(intStr);
}
assertEquals(ris.getNumSamples(), n);
final String[] data = ris.getSamples();
assertNotNull(data);
assertEquals(ris.getNumSamples(), ris.getN());
assertEquals(data.length, n);
// items in submit order until reservoir at capacity so check
for (int i = 0; i < n; ++i) {
assertEquals(data[i], Integer.toString(i));
}
// not using validateSerializeAndDeserialize() to check with a non-Long
ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
expectedLength += Family.RESERVOIR.getMaxPreLongs() << 3;
final byte[] sketchBytes = ris.toByteArray(serDe);
assertEquals(sketchBytes.length, expectedLength);
// ensure reservoir rebuilds correctly
final Memory mem = Memory.wrap(sketchBytes);
final ReservoirItemsSketch<String> loadedRis = ReservoirItemsSketch.heapify(mem, serDe);
validateReservoirEquality(ris, loadedRis);
println("Under-full reservoir:");
println(" Preamble:");
println(PreambleUtil.preambleToString(mem));
println(" Sketch:");
println(ris.toString());
}
@Test
public void checkFullReservoir() {
final int k = 1000;
final int n = 2000;
// specify smaller ResizeFactor to ensure multiple resizes
final ReservoirItemsSketch<Long> ris = ReservoirItemsSketch.newInstance(k, ResizeFactor.X2);
for (int i = 0; i < n; ++i) {
ris.update((long) i);
}
assertEquals(ris.getNumSamples(), ris.getK());
validateSerializeAndDeserialize(ris);
println("Full reservoir:");
println(" Preamble:");
byte[] byteArr = ris.toByteArray(new ArrayOfLongsSerDe());
println(ReservoirItemsSketch.toString(byteArr));
ReservoirItemsSketch.toString(Memory.wrap(byteArr));
println(" Sketch:");
println(ris.toString());
}
@Test
public void checkPolymorphicType() {
final ReservoirItemsSketch<Number> ris = ReservoirItemsSketch.newInstance(6);
assertNull(ris.getSamples());
assertNull(ris.getSamples(Number.class));
// using mixed types
ris.update(1);
ris.update(2L);
ris.update(3.0);
ris.update((short) (44023 & 0xFFFF));
ris.update((byte) (68 & 0xFF));
ris.update(4.0F);
final Number[] data = ris.getSamples(Number.class);
assertNotNull(data);
assertEquals(data.length, 6);
// copying samples without specifying Number.class should fail
try {
ris.getSamples();
fail();
} catch (final ArrayStoreException e) {
// expected
}
// likewise for toByteArray() (which uses getDataSamples() internally for type handling)
final ArrayOfNumbersSerDe serDe = new ArrayOfNumbersSerDe();
try {
ris.toByteArray(serDe);
fail();
} catch (final ArrayStoreException e) {
// expected
}
final byte[] sketchBytes = ris.toByteArray(serDe, Number.class);
assertEquals(sketchBytes.length, 49);
final Memory mem = Memory.wrap(sketchBytes);
final ReservoirItemsSketch<Number> loadedRis = ReservoirItemsSketch.heapify(mem, serDe);
assertEquals(ris.getNumSamples(), loadedRis.getNumSamples());
final Number[] samples1 = ris.getSamples(Number.class);
final Number[] samples2 = loadedRis.getSamples(Number.class);
assertNotNull(samples1);
assertNotNull(samples2);
assertEquals(samples1.length, samples2.length);
for (int i = 0; i < samples1.length; ++i) {
assertEquals(samples1[i], samples2[i]);
}
}
@Test
public void checkArrayOfNumbersSerDeErrors() {
// Highly debatable whether this belongs here vs a stand-alone test class
final ReservoirItemsSketch<Number> ris = ReservoirItemsSketch.newInstance(6);
assertNull(ris.getSamples());
assertNull(ris.getSamples(Number.class));
// using mixed types, but BigDecimal not supported by serde class
ris.update(1);
ris.update(new BigDecimal(2));
// this should work since BigDecimal is an instance of Number
final Number[] data = ris.getSamples(Number.class);
assertNotNull(data);
assertEquals(data.length, 2);
// toByteArray() should fail
final ArrayOfNumbersSerDe serDe = new ArrayOfNumbersSerDe();
try {
ris.toByteArray(serDe, Number.class);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
// force entry to a supported type
data[1] = 3.0;
final byte[] bytes = serDe.serializeToByteArray(data);
// change first element to indicate something unsupported
bytes[0] = 'q';
try {
serDe.deserializeFromMemory(Memory.wrap(bytes), 0, 2);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
}
@Test
public void checkBadConstructorArgs() {
final ArrayList<String> data = new ArrayList<>(128);
for (int i = 0; i < 128; ++i) {
data.add(Integer.toString(i));
}
final ResizeFactor rf = ResizeFactor.X8;
// no items
try {
ReservoirItemsSketch.<Byte>newInstance(null, 128, rf, 128);
fail();
} catch (final SketchesException e) {
assertTrue(e.getMessage().contains("null reservoir"));
}
// size too small
try {
ReservoirItemsSketch.newInstance(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 {
ReservoirItemsSketch.newInstance(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 {
ReservoirItemsSketch.newInstance(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 {
ReservoirItemsSketch.newInstance(data, 256, rf, 256);
fail();
} catch (final SketchesException e) {
assertTrue(e.getMessage().contains("too few samples"));
}
}
@Test
public void checkRawSamples() {
final int k = 32;
final long n = 12;
final ReservoirItemsSketch<Long> ris = ReservoirItemsSketch.newInstance(k, ResizeFactor.X2);
for (long i = 0; i < n; ++i) {
ris.update(i);
}
Long[] samples = ris.getSamples();
assertNotNull(samples);
assertEquals(samples.length, n);
final ArrayList<Long> rawSamples = ris.getRawSamplesAsList();
assertEquals(rawSamples.size(), n);
// change a value and make sure getDataSamples() reflects that change
assertEquals((long) rawSamples.get(0), 0L);
rawSamples.set(0, -1L);
samples = ris.getSamples();
assertEquals((long) samples[0], -1L);
assertEquals(samples.length, n);
}
@Test
public void checkSketchCapacity() {
final ArrayList<Long> data = new ArrayList<>(64);
for (long i = 0; i < 64; ++i) {
data.add(i);
}
final long itemsSeen = (1L << 48) - 2;
final ReservoirItemsSketch<Long> ris = ReservoirItemsSketch.newInstance(data, itemsSeen,
ResizeFactor.X8, 64);
// this should work, the next should fail
ris.update(0L);
try {
ris.update(0L);
fail();
} catch (final SketchesStateException e) {
assertTrue(e.getMessage().contains("Sketch has exceeded capacity for total items seen"));
}
ris.reset();
assertEquals(ris.getN(), 0);
ris.update(1L);
assertEquals(ris.getN(), 1L);
}
@Test
public void checkSampleWeight() {
final int k = 32;
final ReservoirItemsSketch<Integer> ris = ReservoirItemsSketch.newInstance(k);
for (int i = 0; i < (k / 2); ++i) {
ris.update(i);
}
assertEquals(ris.getImplicitSampleWeight(), 1.0); // should be exact value here
// will have 3k/2 total samples when done
for (int i = 0; i < k; ++i) {
ris.update(i);
}
assertTrue((ris.getImplicitSampleWeight() - 1.5) < EPS);
}
@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 ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
final ReservoirItemsSketch<Long> ris = ReservoirItemsSketch.newInstance(k);
final byte[] sketchBytesOrig = ris.toByteArray(serDe);
// get a new byte[], manually revert to v1, then reconstruct
final byte[] sketchBytes = ris.toByteArray(serDe);
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);
println(PreambleUtil.preambleToString(sketchMem));
final ReservoirItemsSketch<Long> rebuilt = ReservoirItemsSketch.heapify(sketchMem, serDe);
final byte[] rebuiltBytes = rebuilt.toByteArray(serDe);
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 short tgtIdx = 5;
final ReservoirItemsSketch<Short> ris = ReservoirItemsSketch.newInstance(k);
ris.update(null);
assertEquals(ris.getN(), 0);
for (short i = 0; i < k; ++i) {
ris.update(i);
}
assertEquals((short) ris.getValueAtPosition(tgtIdx), tgtIdx);
ris.insertValueAtPosition((short) -1, tgtIdx);
assertEquals((short) ris.getValueAtPosition(tgtIdx), (short) -1);
}
@Test
public void checkBadSetAndGetValue() {
final int k = 20;
final int tgtIdx = 5;
final ReservoirItemsSketch<Integer> ris = ReservoirItemsSketch.newInstance(k);
try {
ris.getValueAtPosition(0);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
for (int i = 0; i < k; ++i) {
ris.update(i);
}
assertEquals((int) ris.getValueAtPosition(tgtIdx), tgtIdx);
try {
ris.insertValueAtPosition(-1, -1);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
try {
ris.insertValueAtPosition(-1, k + 1);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
try {
ris.getValueAtPosition(-1);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
try {
ris.getValueAtPosition(k + 1);
fail();
} catch (final SketchesArgumentException e) {
// expected
}
}
@Test
public void checkForceIncrement() {
final int k = 100;
final ReservoirItemsSketch<Long> rls = ReservoirItemsSketch.newInstance(k);
for (long 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) - 2);
fail();
} catch (final SketchesStateException e) {
// expected
}
}
@Test
public void checkEstimateSubsetSum() {
final int k = 10;
final ReservoirItemsSketch<Long> sketch = ReservoirItemsSketch.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 getBasicSerializedLongsRIS() {
final int k = 10;
final int n = 20;
final ReservoirItemsSketch<Long> ris = ReservoirItemsSketch.newInstance(k);
assertEquals(ris.getNumSamples(), 0);
for (int i = 0; i < n; ++i) {
ris.update((long) i);
}
assertEquals(ris.getNumSamples(), Math.min(n, k));
assertEquals(ris.getN(), n);
assertEquals(ris.getK(), k);
final byte[] sketchBytes = ris.toByteArray(new ArrayOfLongsSerDe());
return WritableMemory.writableWrap(sketchBytes);
}
private static void validateSerializeAndDeserialize(final ReservoirItemsSketch<Long> ris) {
final byte[] sketchBytes = ris.toByteArray(new ArrayOfLongsSerDe());
assertEquals(sketchBytes.length,
(Family.RESERVOIR.getMaxPreLongs() + ris.getNumSamples()) << 3);
// ensure full reservoir rebuilds correctly
final Memory mem = Memory.wrap(sketchBytes);
final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
final ReservoirItemsSketch<Long> loadedRis = ReservoirItemsSketch.heapify(mem, serDe);
validateReservoirEquality(ris, loadedRis);
}
static <T> void validateReservoirEquality(final ReservoirItemsSketch<T> ris1,
final ReservoirItemsSketch<T> ris2) {
assertEquals(ris1.getNumSamples(), ris2.getNumSamples());
if (ris1.getNumSamples() == 0) { return; }
final Object[] samples1 = ris1.getSamples();
final Object[] samples2 = ris2.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,397 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/sampling/ReservoirLongsUnionTest.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.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.testng.annotations.Test;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
public class ReservoirLongsUnionTest {
@Test
public void checkEmptyUnion() {
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(1024);
final byte[] unionBytes = rlu.toByteArray();
// will intentionally break if changing empty union serialization
assertEquals(unionBytes.length, 8);
println(rlu.toString());
}
@Test
public void checkInstantiation() {
final int n = 100;
final int k = 25;
// create empty unions
ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k);
assertNull(rlu.getResult());
rlu.update(5);
assertNotNull(rlu.getResult());
// pass in a sketch, as both an object and memory
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k);
for (int i = 0; i < n; ++i) {
rls.update(i);
}
rlu.reset();
assertEquals(rlu.getResult().getN(), 0);
rlu.update(rls);
assertEquals(rlu.getResult().getN(), rls.getN());
final byte[] sketchBytes = rls.toByteArray();
final Memory mem = Memory.wrap(sketchBytes);
rlu = ReservoirLongsUnion.newInstance(rls.getK());
rlu.update(mem);
assertNotNull(rlu.getResult());
println(rlu.toString());
}
/*
@Test
public void checkReadOnlyInstantiation() {
final int k = 100;
final ReservoirLongsUnion union = ReservoirLongsUnion.newInstance(k);
for (long i = 0; i < 2 * k; ++i) {
union.update(i);
}
final byte[] unionBytes = union.toByteArray();
final Memory mem = Memory.wrap(unionBytes);
final ReservoirLongsUnion rlu;
rlu = ReservoirLongsUnion.heapify(mem);
assertNotNull(rlu);
assertEquals(rlu.getMaxK(), k);
ReservoirLongsSketchTest.validateReservoirEquality(rlu.getResult(), union.getResult());
}
*/
@Test
public void checkNullUpdate() {
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(1024);
assertNull(rlu.getResult());
// null sketch
rlu.update((ReservoirLongsSketch) null);
assertNull(rlu.getResult());
// null memory
rlu.update((Memory) null);
assertNull(rlu.getResult());
// valid input
rlu.update(5L);
assertNotNull(rlu.getResult());
}
@Test
public void checkSerialization() {
final int n = 100;
final int k = 25;
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k);
for (int i = 0; i < n; ++i) {
rlu.update(i);
}
final byte[] unionBytes = rlu.toByteArray();
final Memory mem = Memory.wrap(unionBytes);
final ReservoirLongsUnion rebuiltUnion = ReservoirLongsUnion.heapify(mem);
validateUnionEquality(rlu, rebuiltUnion);
}
@Test
public void checkVersionConversionWithEmptyGadget() {
final int k = 32768;
final short encK = ReservoirSize.computeSize(k);
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k);
final byte[] unionBytesOrig = rlu.toByteArray();
// get a new byte[], manually revert to v1, then reconstruct
final byte[] unionBytes = rlu.toByteArray();
final WritableMemory unionMem = WritableMemory.writableWrap(unionBytes);
unionMem.putByte(SER_VER_BYTE, (byte) 1);
unionMem.putInt(RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes
unionMem.putShort(RESERVOIR_SIZE_SHORT, encK);
println(PreambleUtil.preambleToString(unionMem));
final ReservoirLongsUnion rebuilt = ReservoirLongsUnion.heapify(unionMem);
final byte[] rebuiltBytes = rebuilt.toByteArray();
assertEquals(unionBytesOrig.length, rebuiltBytes.length);
for (int i = 0; i < unionBytesOrig.length; ++i) {
assertEquals(unionBytesOrig[i], rebuiltBytes[i]);
}
}
@Test
public void checkVersionConversionWithGadget() {
final long n = 32;
final int k = 256;
final short encK = ReservoirSize.computeSize(k);
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k);
for (long i = 0; i < n; ++i) {
rlu.update(i);
}
final byte[] unionBytesOrig = rlu.toByteArray();
// get a new byte[], manually revert to v1, then reconstruct
final byte[] unionBytes = rlu.toByteArray();
final WritableMemory unionMem = WritableMemory.writableWrap(unionBytes);
unionMem.putByte(SER_VER_BYTE, (byte) 1);
unionMem.putInt(RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes
unionMem.putShort(RESERVOIR_SIZE_SHORT, encK);
// force gadget header to v1, too
final int offset = Family.RESERVOIR_UNION.getMaxPreLongs() << 3;
unionMem.putByte(offset + SER_VER_BYTE, (byte) 1);
unionMem.putInt(offset + RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes
unionMem.putShort(offset + RESERVOIR_SIZE_SHORT, encK);
final ReservoirLongsUnion rebuilt = ReservoirLongsUnion.heapify(unionMem);
final byte[] rebuiltBytes = rebuilt.toByteArray();
assertEquals(unionBytesOrig.length, rebuiltBytes.length);
for (int i = 0; i < unionBytesOrig.length; ++i) {
assertEquals(unionBytesOrig[i], rebuiltBytes[i]);
}
}
//@SuppressWarnings("null") // this is the point of the test
@Test(expectedExceptions = java.lang.NullPointerException.class)
public void checkNullMemoryInstantiation() {
ReservoirLongsUnion.heapify(null);
}
@Test
public void checkDownsampledUpdate() {
final int bigK = 1024;
final int bigN = 131072;
final int smallK = 256;
final int smallN = 2048;
final ReservoirLongsSketch sketch1 = getBasicSketch(smallN, smallK);
final ReservoirLongsSketch sketch2 = getBasicSketch(bigN, bigK);
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(smallK);
assertEquals(rlu.getMaxK(), smallK);
rlu.update(sketch1);
assertNotNull(rlu.getResult());
assertEquals(rlu.getResult().getK(), smallK);
rlu.update(sketch2);
assertEquals(rlu.getResult().getK(), smallK);
assertEquals(rlu.getResult().getNumSamples(), smallK);
}
@Test
public void checkUnionResetWithInitialSmallK() {
final int maxK = 25;
final int sketchK = 10;
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(maxK);
ReservoirLongsSketch rls = getBasicSketch(2 * sketchK, sketchK); // in sampling mode
rlu.update(rls);
assertEquals(rlu.getMaxK(), maxK);
assertNotNull(rlu.getResult());
assertEquals(rlu.getResult().getK(), sketchK);
rlu.reset();
assertNotNull(rlu.getResult());
// feed in sketch in sampling mode, with larger k than old gadget
rls = getBasicSketch(2 * maxK, maxK + 1);
rlu.update(rls);
assertEquals(rlu.getMaxK(), maxK);
assertNotNull(rlu.getResult());
assertEquals(rlu.getResult().getK(), maxK);
}
@Test
public void checkNewGadget() {
final int maxK = 1024;
final int bigK = 1536;
final int smallK = 128;
// downsample input sketch, use as gadget (exact mode, but irrelevant here)
final ReservoirLongsSketch bigKSketch = getBasicSketch(maxK / 2, bigK);
final byte[] bigKBytes = bigKSketch.toByteArray();
final Memory bigKMem = Memory.wrap(bigKBytes);
ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(maxK);
rlu.update(bigKMem);
assertNotNull(rlu.getResult());
assertEquals(rlu.getResult().getK(), maxK);
assertEquals(rlu.getResult().getN(), maxK / 2);
// sketch k < maxK but in sampling mode
final ReservoirLongsSketch smallKSketch = getBasicSketch(maxK, smallK);
final byte[] smallKBytes = smallKSketch.toByteArray();
final Memory smallKMem = Memory.wrap(smallKBytes);
rlu = ReservoirLongsUnion.newInstance(maxK);
rlu.update(smallKMem);
assertNotNull(rlu.getResult());
assertTrue(rlu.getResult().getK() < maxK);
assertEquals(rlu.getResult().getK(), smallK);
assertEquals(rlu.getResult().getN(), maxK);
// sketch k < maxK and in exact mode
final ReservoirLongsSketch smallKExactSketch = getBasicSketch(smallK, smallK);
final byte[] smallKExactBytes = smallKExactSketch.toByteArray();
final Memory smallKExactMem = Memory.wrap(smallKExactBytes);
rlu = ReservoirLongsUnion.newInstance(maxK);
rlu.update(smallKExactMem);
assertNotNull(rlu.getResult());
assertEquals(rlu.getResult().getK(), maxK);
assertEquals(rlu.getResult().getN(), smallK);
}
@Test
public void checkStandardMergeNoCopy() {
final int k = 1024;
final int n1 = 256;
final int n2 = 256;
final ReservoirLongsSketch sketch1 = getBasicSketch(n1, k);
final ReservoirLongsSketch sketch2 = getBasicSketch(n2, k);
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k);
rlu.update(sketch1);
rlu.update(sketch2);
assertNotNull(rlu.getResult());
assertEquals(rlu.getResult().getK(), k);
assertEquals(rlu.getResult().getN(), n1 + n2);
assertEquals(rlu.getResult().getNumSamples(), n1 + n2);
// creating from Memory should avoid a copy
final int n3 = 2048;
final ReservoirLongsSketch sketch3 = getBasicSketch(n3, k);
final byte[] sketch3Bytes = sketch3.toByteArray();
final Memory mem = Memory.wrap(sketch3Bytes);
rlu.update(mem);
assertEquals(rlu.getResult().getK(), k);
assertEquals(rlu.getResult().getN(), n1 + n2 + n3);
assertEquals(rlu.getResult().getNumSamples(), k);
}
@Test
public void checkStandardMergeWithCopy() {
// this will check the other code route to a standard merge,
// but will copy sketch2 to be non-destructive.
final int k = 1024;
final int n1 = 768;
final int n2 = 2048;
final ReservoirLongsSketch sketch1 = getBasicSketch(n1, k);
final ReservoirLongsSketch sketch2 = getBasicSketch(n2, k);
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k);
rlu.update(sketch1);
rlu.update(sketch2);
rlu.update(10);
assertNotNull(rlu.getResult());
assertEquals(rlu.getResult().getK(), k);
assertEquals(rlu.getResult().getN(), n1 + n2 + 1);
assertEquals(rlu.getResult().getNumSamples(), k);
}
@Test
public void checkWeightedMerge() {
final int k = 1024;
final int n1 = 16384;
final int n2 = 2048;
final ReservoirLongsSketch sketch1 = getBasicSketch(n1, k);
final ReservoirLongsSketch sketch2 = getBasicSketch(n2, k);
ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k);
rlu.update(sketch1);
rlu.update(sketch2);
assertNotNull(rlu.getResult());
assertEquals(rlu.getResult().getK(), k);
assertEquals(rlu.getResult().getN(), n1 + n2);
assertEquals(rlu.getResult().getNumSamples(), k);
// now merge into the sketch for updating -- results should match
rlu = ReservoirLongsUnion.newInstance(k);
rlu.update(sketch2);
rlu.update(sketch1);
assertNotNull(rlu.getResult());
assertEquals(rlu.getResult().getK(), k);
assertEquals(rlu.getResult().getN(), n1 + n2);
assertEquals(rlu.getResult().getNumSamples(), k);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadPreLongs() {
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(1024);
final WritableMemory mem = WritableMemory.writableWrap(rlu.toByteArray());
mem.putByte(PREAMBLE_LONGS_BYTE, (byte) 0); // corrupt the preLongs count
ReservoirLongsUnion.heapify(mem);
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(1024);
final WritableMemory mem = WritableMemory.writableWrap(rlu.toByteArray());
mem.putByte(SER_VER_BYTE, (byte) 0); // corrupt the serialization version
ReservoirLongsUnion.heapify(mem);
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadFamily() {
final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(1024);
final WritableMemory mem = WritableMemory.writableWrap(rlu.toByteArray());
mem.putByte(FAMILY_BYTE, (byte) 0); // corrupt the family ID
ReservoirLongsUnion.heapify(mem);
fail();
}
private static void validateUnionEquality(final ReservoirLongsUnion rlu1,
final ReservoirLongsUnion rlu2) {
assertEquals(rlu1.getMaxK(), rlu2.getMaxK());
ReservoirLongsSketchTest.validateReservoirEquality(rlu1.getResult(), rlu2.getResult());
}
private static ReservoirLongsSketch getBasicSketch(final int n, final int k) {
final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k);
for (int i = 0; i < n; ++i) {
rls.update(i);
}
return rls;
}
/**
* 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,398 |
0 | Create_ds/datasketches-java/src/test/java/org/apache/datasketches | Create_ds/datasketches-java/src/test/java/org/apache/datasketches/sampling/VarOptItemsUnionTest.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.PREAMBLE_LONGS_BYTE;
import static org.apache.datasketches.sampling.PreambleUtil.SER_VER_BYTE;
import static org.apache.datasketches.sampling.VarOptItemsSketchTest.EPS;
import static org.apache.datasketches.sampling.VarOptItemsSketchTest.getUnweightedLongsVIS;
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.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
/**
* @author Jon Malkin
*/
public class VarOptItemsUnionTest {
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
final int k = 25;
final int n = 30;
final VarOptItemsUnion<Long> union = VarOptItemsUnion.newInstance(k);
union.update(getUnweightedLongsVIS(k, n));
final byte[] bytes = union.toByteArray(new ArrayOfLongsSerDe());
final WritableMemory mem = WritableMemory.writableWrap(bytes);
mem.putByte(SER_VER_BYTE, (byte) 0); // corrupt the serialization version
VarOptItemsUnion.heapify(mem, new ArrayOfLongsSerDe());
fail();
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadPreLongs() {
final int k = 25;
final int n = 30;
final VarOptItemsUnion<Long> union = VarOptItemsUnion.newInstance(k);
union.update(getUnweightedLongsVIS(k, n));
final byte[] bytes = union.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));
VarOptItemsUnion.heapify(mem, new ArrayOfLongsSerDe());
fail();
}
@Test
public void unionEmptySketch() {
final int k = 2048;
final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
// we'll union from Memory for good measure
final byte[] sketchBytes = VarOptItemsSketch.<String>newInstance(k).toByteArray(serDe);
final Memory mem = Memory.wrap(sketchBytes);
final VarOptItemsUnion<String> union = VarOptItemsUnion.newInstance(k);
union.update(mem, serDe);
final VarOptItemsSketch<String> result = union.getResult();
assertEquals(result.getN(), 0);
assertEquals(result.getHRegionCount(), 0);
assertEquals(result.getRRegionCount(), 0);
assertTrue(Double.isNaN(result.getTau()));
}
@Test
public void unionTwoExactSketches() {
final int n = 4; // 2n < k
final int k = 10;
final VarOptItemsSketch<Integer> sk1 = VarOptItemsSketch.newInstance(k);
final VarOptItemsSketch<Integer> sk2 = VarOptItemsSketch.newInstance(k);
for (int i = 1; i <= n; ++i) {
sk1.update(i, i);
sk2.update(-i, i);
}
final VarOptItemsUnion<Integer> union = VarOptItemsUnion.newInstance(k);
union.update(sk1);
union.update(sk2);
final VarOptItemsSketch<Integer> result = union.getResult();
assertEquals(result.getN(), 2 * n);
assertEquals(result.getHRegionCount(), 2 * n);
assertEquals(result.getRRegionCount(), 0);
}
@Test
public void unionHeavySamplingSketch() {
final int n1 = 20;
final int k1 = 10;
final int n2 = 6;
final int k2 = 5;
final VarOptItemsSketch<Integer> sk1 = VarOptItemsSketch.newInstance(k1);
final VarOptItemsSketch<Integer> sk2 = VarOptItemsSketch.newInstance(k2);
for (int i = 1; i <= n1; ++i) {
sk1.update(i, i);
}
for (int i = 1; i < n2; ++i) { // we'll add a very heavy one later
sk2.update(-i, i + 1000.0);
}
sk2.update(-n2, 1000000.0);
final VarOptItemsUnion<Integer> union = VarOptItemsUnion.newInstance(k1);
union.update(sk1);
union.update(sk2);
VarOptItemsSketch<Integer> result = union.getResult();
assertEquals(result.getN(), n1 + n2);
assertEquals(result.getK(), k2); // heavy enough it'll pull back to k2
assertEquals(result.getHRegionCount(), 1);
assertEquals(result.getRRegionCount(), k2 - 1);
union.reset();
assertEquals(union.getOuterTau(), 0.0);
result = union.getResult();
assertEquals(result.getK(), k1);
assertEquals(result.getN(), 0);
}
@Test
public void unionIdenticalSamplingSketches() {
final int k = 20;
final int n = 50;
VarOptItemsSketch<Long> sketch = getUnweightedLongsVIS(k, n);
final VarOptItemsUnion<Long> union = VarOptItemsUnion.newInstance(k);
union.update(sketch);
union.update(sketch);
VarOptItemsSketch<Long> result = union.getResult();
double expectedWeight = 2.0 * n; // unweighted, aka uniform weight of 1.0
assertEquals(result.getN(), 2 * n);
assertEquals(result.getTotalWtR(), expectedWeight);
// add another sketch, such that sketchTau < outerTau
sketch = getUnweightedLongsVIS(k, k + 1); // tau = (k + 1) / k
union.update(sketch);
result = union.getResult();
expectedWeight = (2.0 * n) + k + 1;
assertEquals(result.getN(), (2 * n) + k + 1);
assertEquals(result.getTotalWtR(), expectedWeight, EPS);
union.reset();
assertEquals(union.getOuterTau(), 0.0);
result = union.getResult();
assertEquals(result.getK(), k);
assertEquals(result.getN(), 0);
}
@Test
public void unionSmallSamplingSketch() {
final int kSmall = 16;
final int n1 = 32;
final int n2 = 64;
final int kMax = 128;
// small k sketch, but sampling
VarOptItemsSketch<Long> sketch = getUnweightedLongsVIS(kSmall, n1);
sketch.update(-1L, n1 ^ 2); // add a heavy item
final VarOptItemsUnion<Long> union = VarOptItemsUnion.newInstance(kMax);
union.update(sketch);
// another one, but different n to get a different per-item weight
sketch = getUnweightedLongsVIS(kSmall, n2);
union.update(sketch);
// should trigger migrateMarkedItemsByDecreasingK()
final VarOptItemsSketch<Long> result = union.getResult();
assertEquals(result.getN(), n1 + n2 + 1);
assertEquals(result.getTotalWtR(), 96.0, EPS); // n1+n2 light items, ignore the heavy one
}
@Test
public void unionExactReservoirSketch() {
// build a varopt union which contains both heavy and light items, then copy it and
// compare unioning:
// 1. A varopt sketch of items with weight 1.0
// 2. A reservoir sample made of the same input items as above
// and we should find that the resulting unions are equivalent.
final int k = 20;
final long n = 2 * k;
final VarOptItemsSketch<Long> baseVis = VarOptItemsSketch.newInstance(k);
for (long i = 1; i <= n; ++i) {
baseVis.update(-i, i);
}
baseVis.update(-n - 1L, n * n);
baseVis.update(-n - 2L, n * n);
baseVis.update(-n - 3L, n * n);
final VarOptItemsUnion<Long> union1 = VarOptItemsUnion.newInstance(k);
union1.update(baseVis);
final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
final Memory unionImg = Memory.wrap(union1.toByteArray(serDe));
final VarOptItemsUnion<Long> union2 = VarOptItemsUnion.heapify(unionImg, serDe);
compareUnionsExact(union1, union2); // sanity check
final VarOptItemsSketch<Long> vis = VarOptItemsSketch.newInstance(k);
final ReservoirItemsSketch<Long> ris = ReservoirItemsSketch.newInstance(k);
union2.update((ReservoirItemsSketch<Long>) null);
union2.update(ris); // empty
compareUnionsExact(union1, union2); // union2 should be unchanged
for (long i = 1; i < (k - 1); ++i) {
ris.update(i);
vis.update(i, 1.0);
}
union1.update(vis);
union2.update(ris);
compareUnionsEquivalent(union1, union2);
}
@Test
public void unionSamplingReservoirSketch() {
// Like unionExactReservoirSketch, but merge in reservoir first, with reservoir in sampling mode
final int k = 20;
final long n = k * k;
final VarOptItemsUnion<Long> union1 = VarOptItemsUnion.newInstance(k);
final VarOptItemsUnion<Long> union2 = VarOptItemsUnion.newInstance(k);
compareUnionsExact(union1, union2); // sanity check
final VarOptItemsSketch<Long> vis = VarOptItemsSketch.newInstance(k);
final ReservoirItemsSketch<Long> ris = ReservoirItemsSketch.newInstance(k);
for (long i = 1; i < n; ++i) {
ris.update(i);
vis.update(i, 1.0);
}
union1.update(vis);
union2.update(ris);
compareUnionsEquivalent(union1, union2);
// repeat to trigger equal tau scenario
union1.update(vis);
union2.update(ris);
compareUnionsEquivalent(union1, union2);
// create and add a sketch with some heavy items
final VarOptItemsSketch<Long> newVis = VarOptItemsSketch.newInstance(k);
for (long i = 1; i <= n; ++i) {
newVis.update(-i, i);
}
newVis.update(-n - 1L, n * n);
newVis.update(-n - 2L, n * n);
newVis.update(-n - 3L, n * n);
union1.update(newVis);
union2.update(newVis);
compareUnionsEquivalent(union1, union2);
}
@Test
public void unionReservoirVariousTauValues() {
final int k = 20;
final long n = 2 * k;
final VarOptItemsSketch<Long> baseVis = VarOptItemsSketch.newInstance(k);
for (long i = 1; i <= n; ++i) {
baseVis.update(-i, 1.0);
}
final VarOptItemsUnion<Long> union1 = VarOptItemsUnion.newInstance(k);
union1.update(baseVis);
final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
final Memory unionImg = Memory.wrap(union1.toByteArray(serDe));
final VarOptItemsUnion<Long> union2 = VarOptItemsUnion.heapify(unionImg, serDe);
compareUnionsExact(union1, union2); // sanity check
// reservoir tau will be greater than gadget's tau
VarOptItemsSketch<Long> vis = VarOptItemsSketch.newInstance(k);
ReservoirItemsSketch<Long> ris = ReservoirItemsSketch.newInstance(k);
for (long i = 1; i < (2 * n); ++i) {
ris.update(i);
vis.update(i, 1.0);
}
union1.update(vis);
union2.update(ris);
compareUnionsEquivalent(union1, union2);
// reservoir tau will be smaller than gadget's tau
vis = VarOptItemsSketch.newInstance(k);
ris = ReservoirItemsSketch.newInstance(k);
for (long i = 1; i <= (k + 1); ++i) {
ris.update(i);
vis.update(i, 1.0);
}
union1.update(vis);
union2.update(ris);
compareUnionsEquivalent(union1, union2);
}
@Test
public void serializeEmptyUnion() {
final int k = 100;
final VarOptItemsUnion<String> union = VarOptItemsUnion.newInstance(k);
// null inputs to update() should leave the union empty
union.update((VarOptItemsSketch<String>) null);
union.update(null, new ArrayOfStringsSerDe());
final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
final byte[] bytes = union.toByteArray(serDe);
assertEquals(bytes.length, 8);
final Memory mem = Memory.wrap(bytes);
final VarOptItemsUnion<String> rebuilt = VarOptItemsUnion.heapify(mem, serDe);
final VarOptItemsSketch<String> sketch = rebuilt.getResult();
assertEquals(sketch.getN(), 0);
assertEquals(rebuilt.toString(), union.toString());
}
@Test
public void serializeExactUnion() {
final int n1 = 32;
final int n2 = 64;
final int k = 128;
final VarOptItemsSketch<Long> sketch1 = getUnweightedLongsVIS(k, n1);
final VarOptItemsSketch<Long> sketch2 = getUnweightedLongsVIS(k, n2);
final VarOptItemsUnion<Long> union = VarOptItemsUnion.newInstance(k);
union.update(sketch1);
union.update(sketch2);
final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
final byte[] unionBytes = union.toByteArray(serDe);
final Memory mem = Memory.wrap(unionBytes);
final VarOptItemsUnion<Long> rebuilt = VarOptItemsUnion.heapify(mem, serDe);
compareUnionsExact(rebuilt, union);
assertEquals(rebuilt.toString(), union.toString());
}
@Test
public void serializeSamplingUnion() {
final int n = 256;
final int k = 128;
final VarOptItemsSketch<Long> sketch = getUnweightedLongsVIS(k, n);
sketch.update(n + 1L, 1000.0);
sketch.update(n + 2L, 1001.0);
sketch.update(n + 3L, 1002.0);
sketch.update(n + 4L, 1003.0);
sketch.update(n + 5L, 1004.0);
sketch.update(n + 6L, 1005.0);
sketch.update(n + 7L, 1006.0);
sketch.update(n + 8L, 1007.0);
final VarOptItemsUnion<Long> union = VarOptItemsUnion.newInstance(k);
union.update(sketch);
final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
final byte[] unionBytes = union.toByteArray(serDe);
final Memory mem = Memory.wrap(unionBytes);
final VarOptItemsUnion<Long> rebuilt = VarOptItemsUnion.heapify(mem, serDe);
compareUnionsExact(rebuilt, union);
assertEquals(rebuilt.toString(), union.toString());
}
private static <T> void compareUnionsExact(final VarOptItemsUnion<T> u1,
final VarOptItemsUnion<T> u2) {
assertEquals(u1.getOuterTau(), u2.getOuterTau());
final VarOptItemsSketch<T> sketch1 = u1.getResult();
final VarOptItemsSketch<T> sketch2 = u2.getResult();
assertEquals(sketch1.getN(), sketch2.getN());
assertEquals(sketch1.getHRegionCount(), sketch2.getHRegionCount());
assertEquals(sketch1.getRRegionCount(), sketch2.getRRegionCount());
final VarOptItemsSamples<T> s1 = sketch1.getSketchSamples();
final VarOptItemsSamples<T> s2 = sketch2.getSketchSamples();
assertEquals(s1.getNumSamples(), s2.getNumSamples());
assertEquals(s1.weights(), s2.weights());
assertEquals(s1.items(), s2.items());
}
private static <T> void compareUnionsEquivalent(final VarOptItemsUnion<T> u1,
final VarOptItemsUnion<T> u2) {
assertEquals(u1.getOuterTau(), u2.getOuterTau());
final VarOptItemsSketch<T> sketch1 = u1.getResult();
final VarOptItemsSketch<T> sketch2 = u2.getResult();
assertEquals(sketch1.getN(), sketch2.getN());
assertEquals(sketch1.getHRegionCount(), sketch2.getHRegionCount());
assertEquals(sketch1.getRRegionCount(), sketch2.getRRegionCount());
final VarOptItemsSamples<T> s1 = sketch1.getSketchSamples();
final VarOptItemsSamples<T> s2 = sketch2.getSketchSamples();
assertEquals(s1.getNumSamples(), s2.getNumSamples());
assertEquals(s1.weights(), s2.weights());
// only compare exact items; others can differ as long as weights match
for (int i = 0; i < sketch1.getHRegionCount(); ++i) {
assertEquals(s1.items(i), s2.items(i));
}
}
/**
* Wrapper around System.out.println() allowing a simple way to disable logging in tests
* @param msg The message to print
*/
@SuppressWarnings("unused")
private static void println(final String msg) {
//System.out.println(msg);
}
}
| 2,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.