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/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation
Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation/constraints/ValidLocalDateTimeString.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.fineract.cn.lang.validation.constraints; import org.apache.fineract.cn.lang.validation.CheckLocalDateTimeString; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * The annotated string must either null or must contain a time which can be * read by DateConverter.fromIsoString() * * @author Myrle Krantz */ @SuppressWarnings("unused") @Target({ FIELD, METHOD, PARAMETER}) @Retention(RUNTIME) @Documented @Constraint(validatedBy = CheckLocalDateTimeString.class) public @interface ValidLocalDateTimeString { String message() default "Invalid local date time string."; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; }
5,700
0
Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation
Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation/constraints/ValidApplicationName.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.fineract.cn.lang.validation.constraints; import org.apache.fineract.cn.lang.validation.CheckApplicationName; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * The annotated string must not be null, and must contain an application name of the form * appname-v1 * * @author Myrle Krantz */ @SuppressWarnings("unused") @Target({ FIELD, METHOD, PARAMETER}) @Retention(RUNTIME) @Documented @Constraint(validatedBy = CheckApplicationName.class) public @interface ValidApplicationName { String message() default "Invalid fineract identifier."; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; }
5,701
0
Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation
Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation/constraints/ValidIdentifier.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.fineract.cn.lang.validation.constraints; import org.apache.fineract.cn.lang.validation.CheckIdentifier; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * The annotated string must not be null, must have a minimum length of 2, and must be * equals to itself URL-encoded. * * @author Myrle Krantz */ @SuppressWarnings("unused") @Target({ FIELD, METHOD, PARAMETER}) @Retention(RUNTIME) @Documented @Constraint(validatedBy = CheckIdentifier.class) public @interface ValidIdentifier { String message() default "Invalid fineract identifier."; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; int maxLength() default 32; boolean optional() default false; }
5,702
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/PigTestingUtil.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.pig; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.datasketches.Family; import org.apache.datasketches.theta.UpdateSketch; @SuppressWarnings("javadoc") public class PigTestingUtil { public static final String LS = System.getProperty("line.separator"); /** * Returns a tuple constructed from the given array of objects. * * @param in Array of objects. * @throws ExecException this is thrown by Pig * @return tuple */ public static Tuple createTupleFromArray(Object[] in) throws ExecException { int len = in.length; Tuple tuple = TupleFactory.getInstance().newTuple(len); for (int i = 0; i < in.length; i++ ) { tuple.set(i, in[i]); } return tuple; } /** * Returns a Pig DataByteArray constructed from a QuickSelectSketch. * * @param nomSize of the Sketch. Note, minimum size is 16. * Cache size will autoscale from a minimum of 16. * @param start start value * @param numValues number of values in the range * @return DataByteArray */ public static DataByteArray createDbaFromQssRange(int nomSize, int start, int numValues) { UpdateSketch skA = UpdateSketch.builder().setNominalEntries(nomSize).build(); for (int i = start; i < (start + numValues); i++ ) { skA.update(i); } byte[] byteArr = skA.compact(true, null).toByteArray(); return new DataByteArray(byteArr); } /** * Returns a Pig DataByteArray constructed from a AlphaSketch. * * @param nomSize of the Sketch. Note, minimum nominal size is 512. * Cache size will autoscale from a minimum of 512. * @param start start value * @param numValues number of values in the range * @return DataByteArray */ public static DataByteArray createDbaFromAlphaRange(int nomSize, int start, int numValues) { UpdateSketch skA = UpdateSketch.builder().setFamily(Family.ALPHA) .setNominalEntries(nomSize).build(); for (int i = start; i < (start + numValues); i++ ) { skA.update(i); } byte[] byteArr = skA.compact(true, null).toByteArray(); return new DataByteArray(byteArr); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); } }
5,703
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/hll/SketchToStringTest.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.pig.hll; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.hll.HllSketch; @SuppressWarnings("javadoc") public class SketchToStringTest { private static final TupleFactory tupleFactory = TupleFactory.getInstance(); @Test public void nullInputTuple() throws Exception { EvalFunc<String> func = new SketchToString(); String result = func.exec(null); Assert.assertNull(result); } @Test public void emptyInputTuple() throws Exception { EvalFunc<String> func = new SketchToString(); String result = func.exec(tupleFactory.newTuple()); Assert.assertNull(result); } @Test public void normalCase() throws Exception { EvalFunc<String> func = new SketchToString(); HllSketch sketch = new HllSketch(12); String result = func.exec(tupleFactory.newTuple(new DataByteArray(sketch.toCompactByteArray()))); Assert.assertNotNull(result); Assert.assertTrue(result.length() > 0); } }
5,704
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/hll/UnionSketchTest.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.pig.hll; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.hll.HllSketch; import org.apache.datasketches.hll.TgtHllType; @SuppressWarnings("javadoc") public class UnionSketchTest { private static final TupleFactory tupleFactory = TupleFactory.getInstance(); private static final BagFactory bagFactory = BagFactory.getInstance(); @Test public void execNullInputTuple() throws Exception { EvalFunc<DataByteArray> func = new UnionSketch(); DataByteArray result = func.exec(null); HllSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<DataByteArray> func = new UnionSketch("10"); DataByteArray result = func.exec(tupleFactory.newTuple()); HllSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getLgConfigK(), 10); } @Test public void execEmptyBag() throws Exception { EvalFunc<DataByteArray> func = new UnionSketch("10", "HLL_6"); DataByteArray result = func.exec(tupleFactory.newTuple(bagFactory.newDefaultBag())); HllSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getLgConfigK(), 10); Assert.assertEquals(sketch.getTgtHllType(), TgtHllType.HLL_6); } @Test public void execNormalCase() throws Exception { EvalFunc<DataByteArray> func = new UnionSketch(); HllSketch inputSketch = new HllSketch(12); inputSketch.update(1); inputSketch.update(2); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple(new DataByteArray(inputSketch.toCompactByteArray()))); DataByteArray result = func.exec(tupleFactory.newTuple(bag)); HllSketch sketch = DataToSketchTest.getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); } @Test public void accumulator() throws Exception { Accumulator<DataByteArray> func = new UnionSketch(); // no input yet DataByteArray result = func.getValue(); HllSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); // null input tuple func.accumulate(null); result = func.getValue(); sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty input tuple func.accumulate(tupleFactory.newTuple()); result = func.getValue(); sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty bag func.accumulate(tupleFactory.newTuple(bagFactory.newDefaultBag())); result = func.getValue(); sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); // normal case HllSketch inputSketch = new HllSketch(12); inputSketch.update(1); inputSketch.update(2); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple(new DataByteArray(inputSketch.toCompactByteArray()))); func.accumulate(tupleFactory.newTuple(bag)); result = func.getValue(); sketch = DataToSketchTest.getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); // cleanup func.cleanup(); result = func.getValue(); sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicInitial() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getInitial()).newInstance(); Tuple input = tupleFactory.newTuple(); Tuple result = func.exec(input); Assert.assertEquals(result, input); } @Test public void algebraicIntermediateNullInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()).newInstance(); Tuple result = func.exec(null); HllSketch sketch = DataToSketchTest.getSketch((DataByteArray) result.get(0)); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()) .getConstructor(String.class).newInstance("10"); Tuple result = func.exec(tupleFactory.newTuple()); HllSketch sketch = DataToSketchTest.getSketch((DataByteArray) result.get(0)); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getLgConfigK(), 10); } @Test public void algebraicIntermediateFromInitial() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()) .getConstructor(String.class, String.class).newInstance("10", "HLL_6"); HllSketch inputSketch = new HllSketch(12); inputSketch.update(1); inputSketch.update(2); inputSketch.update(3); DataBag outerBag = bagFactory.newDefaultBag(); DataBag innerBag = bagFactory.newDefaultBag(); innerBag.add(tupleFactory.newTuple(new DataByteArray(inputSketch.toCompactByteArray()))); outerBag.add(tupleFactory.newTuple(innerBag)); Tuple result = func.exec(tupleFactory.newTuple(outerBag)); HllSketch sketch = DataToSketchTest.getSketch((DataByteArray) result.get(0)); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 3.0, 0.01); Assert.assertEquals(sketch.getLgConfigK(), 10); Assert.assertEquals(sketch.getTgtHllType(), TgtHllType.HLL_6); } @Test public void algebraicIntermediateFromIntermediate() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()).newInstance(); HllSketch inputSketch = new HllSketch(12); inputSketch.update("a"); inputSketch.update("b"); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple(new DataByteArray(inputSketch.toCompactByteArray()))); Tuple result = func.exec(tupleFactory.newTuple(bag)); HllSketch sketch = DataToSketchTest.getSketch((DataByteArray) result.get(0)); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); } @Test public void algebraicFinalNullInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()).newInstance(); DataByteArray result = func.exec(null); HllSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicFinalEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()) .getConstructor(String.class).newInstance("10"); DataByteArray result = func.exec(tupleFactory.newTuple()); HllSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getLgConfigK(), 10); } @Test public void algebraicFinalFromInitial() throws Exception { @SuppressWarnings("unchecked") EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()) .getConstructor(String.class, String.class).newInstance("10", "HLL_6"); HllSketch inputSketch = new HllSketch(12); inputSketch.update(1); inputSketch.update(2); inputSketch.update(3); DataBag outerBag = bagFactory.newDefaultBag(); DataBag innerBag = bagFactory.newDefaultBag(); innerBag.add(tupleFactory.newTuple(new DataByteArray(inputSketch.toCompactByteArray()))); outerBag.add(tupleFactory.newTuple(innerBag)); DataByteArray result = func.exec(tupleFactory.newTuple(outerBag)); HllSketch sketch = DataToSketchTest.getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 3.0, 0.01); Assert.assertEquals(sketch.getLgConfigK(), 10); Assert.assertEquals(sketch.getTgtHllType(), TgtHllType.HLL_6); } @Test public void algebraicFinalFromIntermediate() throws Exception { @SuppressWarnings("unchecked") EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()).newInstance(); HllSketch inputSketch = new HllSketch(12); inputSketch.update("a"); inputSketch.update("b"); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple(new DataByteArray(inputSketch.toCompactByteArray()))); DataByteArray result = func.exec(tupleFactory.newTuple(bag)); HllSketch sketch = DataToSketchTest.getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); } }
5,705
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/hll/DataToSketchTest.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.pig.hll; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.hll.HllSketch; import org.apache.datasketches.hll.TgtHllType; @SuppressWarnings("javadoc") public class DataToSketchTest { private static final TupleFactory tupleFactory = TupleFactory.getInstance(); private static final BagFactory bagFactory = BagFactory.getInstance(); @Test public void execNullInputTuple() throws Exception { EvalFunc<DataByteArray> func = new DataToSketch(); DataByteArray result = func.exec(null); HllSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<DataByteArray> func = new DataToSketch("10"); DataByteArray result = func.exec(tupleFactory.newTuple()); HllSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getLgConfigK(), 10); } @Test public void execEmptyBag() throws Exception { EvalFunc<DataByteArray> func = new DataToSketch("10", "HLL_6"); DataByteArray result = func.exec(tupleFactory.newTuple(bagFactory.newDefaultBag())); HllSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getLgConfigK(), 10); Assert.assertEquals(sketch.getTgtHllType(), TgtHllType.HLL_6); } @Test(expectedExceptions = IllegalArgumentException.class) public void execUnsupportedType() throws Exception { EvalFunc<DataByteArray> func = new DataToSketch(); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple(new Object())); func.exec(tupleFactory.newTuple(bag)); } @Test public void execVariousTypesOfInput() throws Exception { EvalFunc<DataByteArray> func = new DataToSketch(); DataBag bag = bagFactory.newDefaultBag(); Tuple tupleWithNull = tupleFactory.newTuple(1); tupleWithNull.set(0, null); bag.add(tupleWithNull); bag.add(tupleFactory.newTuple(Byte.valueOf((byte) 1))); bag.add(tupleFactory.newTuple(Integer.valueOf(2))); bag.add(tupleFactory.newTuple(Long.valueOf(3))); bag.add(tupleFactory.newTuple(Float.valueOf(1))); bag.add(tupleFactory.newTuple(Double.valueOf(2))); bag.add(tupleFactory.newTuple(new DataByteArray(new byte[] {(byte) 1}))); bag.add(tupleFactory.newTuple("a")); DataByteArray result = func.exec(tupleFactory.newTuple(bag)); HllSketch sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 7.0, 0.01); } @Test public void accumulator() throws Exception { Accumulator<DataByteArray> func = new DataToSketch(); // no input yet DataByteArray result = func.getValue(); HllSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // null input tuple func.accumulate(null); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty input tuple func.accumulate(tupleFactory.newTuple()); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty bag func.accumulate(tupleFactory.newTuple(bagFactory.newDefaultBag())); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // normal case DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple("a")); bag.add(tupleFactory.newTuple("b")); func.accumulate(tupleFactory.newTuple(bag)); result = func.getValue(); sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); // cleanup func.cleanup(); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicInitial() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getInitial()).newInstance(); Tuple input = tupleFactory.newTuple(); Tuple result = func.exec(input); Assert.assertEquals(result, input); } @Test public void algebraicInitialWithLgK() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getInitial()) .getConstructor(String.class).newInstance("10"); Tuple input = tupleFactory.newTuple(); Tuple result = func.exec(input); Assert.assertEquals(result, input); } @Test public void algebraicInitialWithLgKAndTgtHllType() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getInitial()) .getConstructor(String.class, String.class).newInstance("10", "HLL_6"); Tuple input = tupleFactory.newTuple(); Tuple result = func.exec(input); Assert.assertEquals(result, input); } @Test public void algebraicIntermediateNullInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); Tuple result = func.exec(null); HllSketch sketch = getSketch((DataByteArray) result.get(0)); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()) .getConstructor(String.class).newInstance("10"); Tuple result = func.exec(tupleFactory.newTuple()); HllSketch sketch = getSketch((DataByteArray) result.get(0)); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getLgConfigK(), 10); } @Test public void algebraicIntermediateEmptyBag() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()) .getConstructor(String.class, String.class).newInstance("10", "HLL_6"); Tuple result = func.exec(tupleFactory.newTuple(bagFactory.newDefaultBag())); HllSketch sketch = getSketch((DataByteArray) result.get(0)); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getLgConfigK(), 10); Assert.assertEquals(sketch.getTgtHllType(), TgtHllType.HLL_6); } @Test public void algebraicIntermediateFromInitial() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); DataBag outerBag = bagFactory.newDefaultBag(); DataBag innerBag = bagFactory.newDefaultBag(); innerBag.add(tupleFactory.newTuple("a")); innerBag.add(tupleFactory.newTuple("b")); innerBag.add(tupleFactory.newTuple("c")); outerBag.add(tupleFactory.newTuple(innerBag)); Tuple result = func.exec(tupleFactory.newTuple(outerBag)); HllSketch sketch = getSketch((DataByteArray) result.get(0)); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 3.0, 0.01); } @Test public void algebraicIntermediateFromIntermediate() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); HllSketch inputSketch = new HllSketch(12); inputSketch.update("a"); inputSketch.update("b"); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple(new DataByteArray(inputSketch.toCompactByteArray()))); Tuple result = func.exec(tupleFactory.newTuple(bag)); HllSketch sketch = getSketch((DataByteArray) result.get(0)); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); } @Test public void algebraicFinalNullInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); DataByteArray result = func.exec(null); HllSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicFinalEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()) .getConstructor(String.class).newInstance("10"); DataByteArray result = func.exec(tupleFactory.newTuple()); HllSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getLgConfigK(), 10); } @Test public void algebraicFinalEmptyBag() throws Exception { @SuppressWarnings("unchecked") EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()) .getConstructor(String.class, String.class).newInstance("10", "HLL_6"); DataByteArray result = func.exec(tupleFactory.newTuple(bagFactory.newDefaultBag())); HllSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getLgConfigK(), 10); Assert.assertEquals(sketch.getTgtHllType(), TgtHllType.HLL_6); } @Test public void algebraicFinalFromInitial() throws Exception { @SuppressWarnings("unchecked") EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); DataBag outerBag = bagFactory.newDefaultBag(); DataBag innerBag = bagFactory.newDefaultBag(); innerBag.add(tupleFactory.newTuple("a")); innerBag.add(tupleFactory.newTuple("b")); innerBag.add(tupleFactory.newTuple("c")); outerBag.add(tupleFactory.newTuple(innerBag)); DataByteArray result = func.exec(tupleFactory.newTuple(outerBag)); HllSketch sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 3.0, 0.01); } @Test public void algebraicFinalFromIntermediate() throws Exception { @SuppressWarnings("unchecked") EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); HllSketch inputSketch = new HllSketch(12); inputSketch.update("a"); inputSketch.update("b"); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple(new DataByteArray(inputSketch.toCompactByteArray()))); DataByteArray result = func.exec(tupleFactory.newTuple(bag)); HllSketch sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); } static HllSketch getSketch(DataByteArray dba) throws Exception { Assert.assertNotNull(dba); Assert.assertTrue(dba.size() > 0); return HllSketch.heapify(dba.get()); } }
5,706
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/hll/SketchToEstimateTest.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.pig.hll; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.hll.HllSketch; @SuppressWarnings("javadoc") public class SketchToEstimateTest { private static final TupleFactory tupleFactory = TupleFactory.getInstance(); @Test public void nullInputTuple() throws Exception { EvalFunc<Double> func = new SketchToEstimate(); Double result = func.exec(null); Assert.assertNull(result); } @Test public void emptyInputTuple() throws Exception { EvalFunc<Double> func = new SketchToEstimate(); Double result = func.exec(tupleFactory.newTuple()); Assert.assertNull(result); } @Test public void normalCase() throws Exception { EvalFunc<Double> func = new SketchToEstimate(); HllSketch sketch = new HllSketch(12); sketch.update(1); sketch.update(2); Double result = func.exec(tupleFactory.newTuple(new DataByteArray(sketch.toCompactByteArray()))); Assert.assertNotNull(result); Assert.assertEquals(result, 2.0, 0.01); } }
5,707
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/hll/SketchToEstimateAndErrorBoundsTest.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.pig.hll; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.hll.HllSketch; @SuppressWarnings("javadoc") public class SketchToEstimateAndErrorBoundsTest { private static final TupleFactory tupleFactory = TupleFactory.getInstance(); @Test public void nullInputTuple() throws Exception { EvalFunc<Tuple> func = new SketchToEstimateAndErrorBounds(); Tuple result = func.exec(null); Assert.assertNull(result); } @Test public void emptyInputTuple() throws Exception { EvalFunc<Tuple> func = new SketchToEstimateAndErrorBounds(); Tuple result = func.exec(tupleFactory.newTuple()); Assert.assertNull(result); } @Test public void normalCase() throws Exception { EvalFunc<Tuple> func = new SketchToEstimateAndErrorBounds(); HllSketch sketch = new HllSketch(12); sketch.update(1); sketch.update(2); Tuple result = func.exec(tupleFactory.newTuple(new DataByteArray(sketch.toCompactByteArray()))); Assert.assertNotNull(result); Assert.assertEquals((Double) result.get(0), 2.0, 0.01); Assert.assertTrue((Double) result.get(1) <= 2.0); Assert.assertTrue((Double) result.get(2) >= 2.0); } @Test public void schema() throws Exception { EvalFunc<Tuple> func = new SketchToEstimateAndErrorBounds(); Schema inputSchema = new Schema(new Schema.FieldSchema("Sketch", DataType.BYTEARRAY)); Schema outputSchema = func.outputSchema(inputSchema); Assert.assertNotNull(outputSchema); Assert.assertEquals(outputSchema.size(), 1); Assert.assertEquals(DataType.findTypeName(outputSchema.getField(0).type), "tuple"); Schema innerSchema = outputSchema.getField(0).schema; Assert.assertEquals(innerSchema.size(), 3); Assert.assertEquals(DataType.findTypeName(innerSchema.getField(0).type), "double"); Assert.assertEquals(DataType.findTypeName(innerSchema.getField(1).type), "double"); Assert.assertEquals(DataType.findTypeName(innerSchema.getField(2).type), "double"); } }
5,708
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/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.pig.hash; import static org.apache.datasketches.pig.PigTestingUtil.LS; import static org.junit.Assert.assertNotNull; import java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.FuncSpec; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.PigContext; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; /** * Tests the MurmurHash3 class. */ @SuppressWarnings({"unchecked", "javadoc" }) public class MurmurHash3Test { private static final TupleFactory mTupleFactory = TupleFactory.getInstance(); private String hashUdfName = "org.apache.datasketches.pig.hash.MurmurHash3"; @Test public void checkExceptions1() throws IOException { EvalFunc<Tuple> hashUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.hashUdfName)); Tuple in, out; //Empty input tuple in = mTupleFactory.newTuple(0); out = hashUdf.exec(in); Assert.assertNull(out); } @Test(expectedExceptions = IllegalArgumentException.class) public void checkExceptions2() throws IOException { EvalFunc<Tuple> hashUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.hashUdfName)); Tuple in, out; //seed must be INTEGER or LONG in = mTupleFactory.newTuple(2); in.set(0, "ABC"); in.set(1, Double.valueOf(9001)); out = hashUdf.exec(in); assertNotNull(out); } @Test(expectedExceptions = IllegalArgumentException.class) public void checkExceptions3() throws IOException { EvalFunc<Tuple> hashUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.hashUdfName)); Tuple in, out; //improper hash object = Tuple in = mTupleFactory.newTuple(1); in.set(0, in); out = hashUdf.exec(in); assertNotNull(out); } @Test(expectedExceptions = IllegalArgumentException.class) public void checkExceptions4() throws IOException { EvalFunc<Tuple> hashUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.hashUdfName)); Tuple in, out; //divisor must be INTEGER in = mTupleFactory.newTuple(3); in.set(0, "ABC"); in.set(1, 0); in.set(2, Long.valueOf(8)); out = hashUdf.exec(in); assertNotNull(out); } @Test(expectedExceptions = IllegalArgumentException.class) public void checkExceptions5() throws IOException { EvalFunc<Tuple> hashUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.hashUdfName)); Tuple in, out; //divisor must be INTEGER > 0 in = mTupleFactory.newTuple(3); in.set(0, "ABC"); in.set(1, 0); in.set(2, Integer.valueOf(0)); out = hashUdf.exec(in); assertNotNull(out); } @Test public void check1ValidArg() throws IOException { EvalFunc<Tuple> hashUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.hashUdfName)); Tuple in, out; //test Integer, Long, Float, Double, DataByteArray, String in = mTupleFactory.newTuple(1); in.set(0, null); out = hashUdf.exec(in); Assert.assertNull(out.get(0)); Assert.assertNull(out.get(1)); Assert.assertNull(out.get(2)); in.set(0, Integer.valueOf(1)); out = hashUdf.exec(in); checkOutput(out, false); in.set(0, Long.valueOf(1)); out = hashUdf.exec(in); checkOutput(out, false); in.set(0, Float.valueOf(1.0f)); out = hashUdf.exec(in); checkOutput(out, false); in.set(0, Double.valueOf(0.0)); out = hashUdf.exec(in); checkOutput(out, false); in.set(0, Double.valueOf( -0.0)); out = hashUdf.exec(in); checkOutput(out, false); in.set(0, Double.NaN); out = hashUdf.exec(in); checkOutput(out, false); in.set(0, "1"); out = hashUdf.exec(in); checkOutput(out, false); in.set(0, ""); //empty out = hashUdf.exec(in); Assert.assertNull(out.get(0)); Assert.assertNull(out.get(1)); Assert.assertNull(out.get(2)); byte[] bArr = { 1, 2, 3, 4 }; DataByteArray dba = new DataByteArray(bArr); in.set(0, dba); out = hashUdf.exec(in); checkOutput(out, false); bArr = new byte[0]; //empty dba = new DataByteArray(bArr); in.set(0, dba); out = hashUdf.exec(in); Assert.assertNull(out.get(0)); Assert.assertNull(out.get(1)); Assert.assertNull(out.get(2)); } @Test public void check2ValidArg() throws IOException { EvalFunc<Tuple> hashUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.hashUdfName)); Tuple in, out; //test String, seed in = mTupleFactory.newTuple(2); in.set(0, "1"); //2nd is null out = hashUdf.exec(in); checkOutput(out, false); in.set(0, "1"); in.set(1, 9001); out = hashUdf.exec(in); checkOutput(out, false); in.set(0, "1"); in.set(1, 9001L); out = hashUdf.exec(in); checkOutput(out, false); } @Test public void check3ValidArg() throws IOException { EvalFunc<Tuple> hashUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.hashUdfName)); Tuple in, out; //test String, seed in = mTupleFactory.newTuple(3); in.set(0, "1"); //2nd is null //3rd is null out = hashUdf.exec(in); checkOutput(out, false); in.set(0, "1"); in.set(1, 9001); //3rd is null out = hashUdf.exec(in); checkOutput(out, false); in.set(0, "1"); in.set(1, 9001); in.set(2, 7); out = hashUdf.exec(in); checkOutput(out, true); } @Test public void check3ValidArgs() throws IOException { EvalFunc<Tuple> hashUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.hashUdfName)); Tuple in, out; //test multiple integers, seed in = mTupleFactory.newTuple(3); for (int i = 0; i < 10; i++ ) { in.set(0, i); in.set(1, 9001); in.set(2, 7); out = hashUdf.exec(in); checkOutput(out, true); } } private static void checkOutput(Tuple out, boolean checkMod) throws IOException { long h0 = (Long) out.get(0); long h1 = (Long) out.get(1); Assert.assertNotEquals(h0, 0L); Assert.assertNotEquals(h1, 0L); if (checkMod) { int r = (Integer) out.get(2); Assert.assertTrue(r >= 0, "" + r); } } /** * Test the outputSchema method for MurmurHash3. * @throws IOException thrown by Pig */ @Test public void outputSchemaTestMurmurHash3Udf() throws IOException { EvalFunc<Tuple> hashUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.hashUdfName)); Schema inputSchema = null; Schema nullOutputSchema = null; Schema outputSchema = null; Schema.FieldSchema outputOuterFs0 = null; Schema outputInnerSchema = null; Schema.FieldSchema outputInnerFs0 = null; Schema.FieldSchema outputInnerFs1 = null; Schema.FieldSchema outputInnerFs2 = null; nullOutputSchema = hashUdf.outputSchema(null); //CHARARRAY is one of many different input types inputSchema = Schema.generateNestedSchema(DataType.BAG, DataType.CHARARRAY); outputSchema = hashUdf.outputSchema(inputSchema); outputOuterFs0 = outputSchema.getField(0); outputInnerSchema = outputOuterFs0.schema; outputInnerFs0 = outputInnerSchema.getField(0); outputInnerFs1 = outputInnerSchema.getField(1); outputInnerFs2 = outputInnerSchema.getField(2); Assert.assertNull(nullOutputSchema, "Should be null"); Assert.assertNotNull(outputOuterFs0, "outputSchema.getField(0) may not be null"); String expected = "tuple"; String result = DataType.findTypeName(outputOuterFs0.type); Assert.assertEquals(result, expected); expected = "long"; Assert.assertNotNull(outputInnerFs0, "innerSchema.getField(0) may not be null"); result = DataType.findTypeName(outputInnerFs0.type); Assert.assertEquals(result, expected); expected = "long"; Assert.assertNotNull(outputInnerFs1, "innerSchema.getField(1) may not be null"); result = DataType.findTypeName(outputInnerFs1.type); Assert.assertEquals(result, expected); expected = "int"; Assert.assertNotNull(outputInnerFs2, "innerSchema.getField(2) may not be null"); result = DataType.findTypeName(outputInnerFs2.type); Assert.assertEquals(result, expected); //print schemas //@formatter:off StringBuilder sb = new StringBuilder(); sb.append("input schema: ").append(inputSchema).append(LS) .append("output schema: ").append(outputSchema).append(LS) .append("outputOuterFs: ").append(outputOuterFs0) .append(", type: ").append(DataType.findTypeName(outputOuterFs0.type)).append(LS) .append("outputInnerSchema: ").append(outputInnerSchema).append(LS) .append("outputInnerFs0: ").append(outputInnerFs0) .append(", type: ").append(DataType.findTypeName(outputInnerFs0.type)).append(LS) .append("outputInnerFs1: ").append(outputInnerFs1) .append(", type: ").append(DataType.findTypeName(outputInnerFs1.type)).append(LS) .append("outputInnerFs2: ").append(outputInnerFs2) .append(", type: ").append(DataType.findTypeName(outputInnerFs2.type)).append(LS); println(sb.toString()); //@formatter:on //end print schemas } @Test public void printlnTest() { println(this.getClass().getSimpleName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
5,709
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/ArrayOfDoublesSketchToEstimatesTest.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.pig.tuple; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class ArrayOfDoublesSketchToEstimatesTest { @Test public void nullInput() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToEstimates(); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } @Test public void emptyInput() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToEstimates(); Tuple resultTuple = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(resultTuple); } @Test public void emptySketch() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToEstimates(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 2); Assert.assertEquals(resultTuple.get(0), 0.0); Assert.assertEquals(resultTuple.get(1), 0.0); } @Test public void normalCase() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToEstimates(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); int iterations = 100000; for (int i = 0; i < iterations; i++) { sketch.update(i, new double[] {1}); } for (int i = 0; i < iterations; i++) { sketch.update(i, new double[] {1}); } Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 2); Assert.assertEquals((double) resultTuple.get(0), iterations, iterations * 0.03); Assert.assertEquals((double) resultTuple.get(1), 2 * iterations, 2 * iterations * 0.03); } }
5,710
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/ArrayOfDoublesSketchToEstimateAndErrorBoundsTest.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.pig.tuple; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.junit.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class ArrayOfDoublesSketchToEstimateAndErrorBoundsTest { static final TupleFactory tupleFactory = TupleFactory.getInstance(); @Test public void nullInput() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToEstimateAndErrorBounds(); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } @Test public void emptyInputTuple() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToEstimateAndErrorBounds(); Tuple resultTuple = func.exec(tupleFactory.newTuple()); Assert.assertNull(resultTuple); } @Test public void emptyInputSketch() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToEstimateAndErrorBounds(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); Tuple resultTuple = func.exec(tupleFactory.newTuple(new DataByteArray(sketch.compact().toByteArray()))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals(resultTuple.get(0), 0.0); Assert.assertEquals(resultTuple.get(1), 0.0); Assert.assertEquals(resultTuple.get(2), 0.0); } @Test public void nonEmptyInputSketchExactMode() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToEstimateAndErrorBounds(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); sketch.update(1, new double[] {0}); Tuple resultTuple = func.exec(tupleFactory.newTuple(new DataByteArray(sketch.compact().toByteArray()))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals(resultTuple.get(0), 1.0); Assert.assertEquals(resultTuple.get(1), 1.0); Assert.assertEquals(resultTuple.get(2), 1.0); } @Test public void nonEmptyInputSketchEstimationMode() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToEstimateAndErrorBounds(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); int numKeys = 10000; // to saturate the sketch with default number of nominal entries (4K) for (int i = 0; i < numKeys; i++ ) { sketch.update(i, new double[] {0}); } Tuple resultTuple = func.exec(tupleFactory.newTuple(new DataByteArray(sketch.compact().toByteArray()))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); double estimate = (double) resultTuple.get(0); double lowerBound = (double) resultTuple.get(1); double upperBound = (double) resultTuple.get(2); Assert.assertEquals(estimate, numKeys, numKeys * 0.04); Assert.assertEquals(lowerBound, numKeys, numKeys * 0.04); Assert.assertEquals(upperBound, numKeys, numKeys * 0.04); Assert.assertTrue(lowerBound < estimate); Assert.assertTrue(upperBound > estimate); } }
5,711
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/ArrayOfDoublesSketchesToPValueEstimatesTest.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.pig.tuple; import java.io.IOException; import java.util.Random; import org.apache.commons.math3.stat.inference.TTest; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; /** * Test p-value estimation of two ArrayOfDoublesSketch. */ public class ArrayOfDoublesSketchesToPValueEstimatesTest { /** * Check null input to UDF. * @throws IOException from EvalFunc<Tuple>.exec(...) */ @Test public void nullInput() throws IOException { EvalFunc<Tuple> func = new ArrayOfDoublesSketchesToPValueEstimates(); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } /** * Check input of empty tuple. * @throws IOException from EvalFunc<Tuple>.exec(...) */ @Test public void emptyInput() throws IOException { EvalFunc<Tuple> func = new ArrayOfDoublesSketchesToPValueEstimates(); Tuple resultTuple = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(resultTuple); } /** * Check input of single empty sketch. * @throws IOException from EvalFunc<Tuple>.exec(...) */ @Test public void oneEmptySketch() throws IOException { EvalFunc<Tuple> func = new ArrayOfDoublesSketchesToPValueEstimates(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNull(resultTuple); } /** * Check input of two empty sketches. * @throws IOException from EvalFunc<Tuple>.exec(...) */ @Test public void twoEmptySketches() throws IOException { EvalFunc<Tuple> func = new ArrayOfDoublesSketchesToPValueEstimates(); ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().build(); ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().build(); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketchA.compact().toByteArray()), new DataByteArray(sketchB.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNull(resultTuple); } /** * Check p-value for the smoker data set. Single metric. * @throws IOException from EvalFunc<Tuple>.exec(...) */ @Test public void smokerDatasetSingleMetric() throws IOException { EvalFunc<Tuple> func = new ArrayOfDoublesSketchesToPValueEstimates(); // Create the two sketches ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder() .setNumberOfValues(1) .setNominalEntries(16) .build(); ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder() .setNumberOfValues(1) .setNominalEntries(16) .build(); // Sample dataset (smoker/non-smoker brain size) double[] groupA = {7.3, 6.5, 5.2, 6.3, 7.0, 5.9, 5.2, 5.0, 4.7, 5.7, 5.7, 3.3, 5.0, 4.6, 4.8, 3.8, 4.6}; double[] groupB = {4.2, 4.0, 2.6, 4.9, 4.4, 4.4, 5.5, 5.1, 5.1, 3.2, 3.9, 3.2, 4.9, 4.3, 4.8, 2.4, 5.5, 5.5, 3.7}; // Add values to A sketch for (int i = 0; i < groupA.length; i++) { sketchA.update(i, new double[] {groupA[i]}); } // Add values to B sketch for (int i = 0; i < groupB.length; i++) { sketchB.update(i, new double[] {groupB[i]}); } // Convert to a tuple and execute the UDF Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketchA.compact().toByteArray()), new DataByteArray(sketchB.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); // Should get 1 p-value back Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); // Check p-value values, with a delta Assert.assertEquals((double) resultTuple.get(0), 0.0043, 0.0001); } /** * Check p-value for a large data set. * @throws IOException from EvalFunc<Tuple>.exec(...) */ @Test public void largeDataSet() throws IOException { EvalFunc<Tuple> func = new ArrayOfDoublesSketchesToPValueEstimates(); // Create the two sketches ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder() .setNumberOfValues(1) .setNominalEntries(16000) .build(); ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder() .setNumberOfValues(1) .setNominalEntries(16000) .build(); // Number of values to use. int n = 100000; int bShift = 1000; double[] a = new double[n]; double[] b = new double[n]; // Random number generator Random rand = new Random(41L); // Add values to A sketch for (int i = 0; i < n; i++) { double val = rand.nextGaussian(); sketchA.update(i, new double[] {val}); a[i] = val; } // Add values to B sketch for (int i = 0; i < n; i++) { double val = rand.nextGaussian() + bShift; sketchB.update(i, new double[] {val}); b[i] = val; } TTest tTest = new TTest(); double expectedPValue = tTest.tTest(a, b); // Convert to a tuple and execute the UDF Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketchA.compact().toByteArray()), new DataByteArray(sketchB.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); // Should get 1 p-value back Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); // Check p-value values, with a delta Assert.assertEquals((double) resultTuple.get(0), expectedPValue, 0.01); } /** * Check p-value for two metrics at the same time. * @throws IOException from EvalFunc<Tuple>.exec(...) */ @Test public void twoMetrics() throws IOException { EvalFunc<Tuple> func = new ArrayOfDoublesSketchesToPValueEstimates(); // Create the two sketches ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder() .setNumberOfValues(2) .setNominalEntries(128) .build(); ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder() .setNumberOfValues(2) .setNominalEntries(128) .build(); // Sample dataset (smoker/non-smoker brain size) double[] groupA = {7.3, 6.5, 5.2, 6.3, 7.0, 5.9, 5.2, 5.0, 4.7, 5.7, 5.7, 3.3, 5.0, 4.6, 4.8, 3.8, 4.6}; double[] groupB = {4.2, 4.0, 2.6, 4.9, 4.4, 4.4, 5.5, 5.1, 5.1, 3.2, 3.9, 3.2, 4.9, 4.3, 4.8, 2.4, 5.5, 5.5, 3.7}; // Add values to A sketch for (int i = 0; i < groupA.length; i++) { sketchA.update(i, new double[] {groupA[i], i}); } // Add values to B sketch for (int i = 0; i < groupB.length; i++) { sketchB.update(i, new double[] {groupB[i], i}); } // Convert to a tuple and execute the UDF Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketchA.compact().toByteArray()), new DataByteArray(sketchB.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); // Should get 2 p-values back Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 2); // Check expected p-value values, with a delta Assert.assertEquals((double) resultTuple.get(0), 0.0043, 0.0001); Assert.assertEquals((double) resultTuple.get(1), 0.58, 0.01); } /** * Check with sketch having only one input. * @throws IOException from EvalFunc<Tuple>.exec(...) */ @Test public void sketchWithSingleValue() throws IOException { EvalFunc<Tuple> func = new ArrayOfDoublesSketchesToPValueEstimates(); // Create the two sketches ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder() .setNumberOfValues(1) .setNominalEntries(128) .build(); ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder() .setNumberOfValues(1) .setNominalEntries(128) .build(); // Sample dataset double[] groupA = {7.3, 6.5, 5.2, 6.3, 7.0, 5.9, 5.2, 5.0, 4.7, 5.7, 5.7, 3.3, 5.0, 4.6, 4.8, 3.8, 4.6}; double[] groupB = {5.0}; // Add values to A sketch for (int i = 0; i < groupA.length; i++) { sketchA.update(i, new double[] {groupA[i]}); } // Add values to B sketch for (int i = 0; i < groupB.length; i++) { sketchB.update(i, new double[] {groupB[i]}); } // Convert to a tuple and execute the UDF Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketchA.compact().toByteArray()), new DataByteArray(sketchB.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); // Should get null back, as one of the sketches had fewer than 2 items Assert.assertNull(resultTuple); } }
5,712
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/DataToDoubleSummarySketchTest.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.pig.tuple; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.tuple.Sketch; import org.apache.datasketches.tuple.SketchIterator; 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; import org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer; import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; @SuppressWarnings("javadoc") public class DataToDoubleSummarySketchTest { @Test public void execNullInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToDoubleSummarySketch(); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToDoubleSummarySketch(); Tuple resultTuple = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(resultTuple); } @Test public void execEmptyBag() throws Exception { EvalFunc<Tuple> func = new DataToDoubleSummarySketch(); Tuple inputTuple = PigUtil.objectsToTuple(BagFactory.getInstance().newDefaultBag()); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test(expectedExceptions = IllegalArgumentException.class) public void execWrongSizeOfInnerTuple() throws Exception { EvalFunc<Tuple> func = new DataToDoubleSummarySketch(); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple(1)); Tuple inputTuple = PigUtil.objectsToTuple(bag); func.exec(inputTuple); } @Test(expectedExceptions = IllegalArgumentException.class) public void execWrongKeyType() throws Exception { EvalFunc<Tuple> func = new DataToDoubleSummarySketch(); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple(new Object(), 1.0)); // Object in place of key is not supported Tuple inputTuple = PigUtil.objectsToTuple(bag); func.exec(inputTuple); } @Test public void execAllInputTypes() throws Exception { EvalFunc<Tuple> func = new DataToDoubleSummarySketch(); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple("a", 1.0)); bag.add(PigUtil.objectsToTuple("b", 1.0)); bag.add(PigUtil.objectsToTuple("a", 2.0)); bag.add(PigUtil.objectsToTuple("b", 2.0)); bag.add(PigUtil.objectsToTuple(1, 3.0)); bag.add(PigUtil.objectsToTuple(2L, 3.0)); bag.add(PigUtil.objectsToTuple(1f, 3.0)); bag.add(PigUtil.objectsToTuple(2.0, 3.0)); bag.add(PigUtil.objectsToTuple((byte)3, 3.0)); bag.add(PigUtil.objectsToTuple(new DataByteArray("c".getBytes()), 3.0)); Tuple inputTuple = PigUtil.objectsToTuple(bag); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 8.0, 0.0); SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { Assert.assertEquals(it.getSummary().getValue(), 3.0); } } @Test public void execMinMode() throws Exception { EvalFunc<Tuple> func = new DataToDoubleSummarySketch("32", "Min"); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple("a", 1.0)); bag.add(PigUtil.objectsToTuple("b", 2.0)); bag.add(PigUtil.objectsToTuple("a", 2.0)); bag.add(PigUtil.objectsToTuple("b", 1.0)); Tuple inputTuple = PigUtil.objectsToTuple(bag); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { Assert.assertEquals(it.getSummary().getValue(), 1.0); } } @Test public void accumulator() throws Exception { Accumulator<Tuple> func = new DataToDoubleSummarySketch("32"); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple("a", 1.0)); inputTuple.set(0, bag); func.accumulate(inputTuple); inputTuple = TupleFactory.getInstance().newTuple(1); bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple("b", 1.0)); bag.add(PigUtil.objectsToTuple("a", 2.0)); bag.add(PigUtil.objectsToTuple("b", 2.0)); inputTuple.set(0, bag); func.accumulate(inputTuple); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { Assert.assertEquals(it.getSummary().getValue(), 3.0); } // after cleanup, the value should always be 0 func.cleanup(); resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch2 = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch2.getEstimate(), 0.0, 0.0); } @Test public void algebraicInitialOneParam() throws Exception { EvalFunc<Tuple> func = new DataToDoubleSummarySketch.Initial(null); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple(null, null)); bag.add(PigUtil.objectsToTuple(null, null)); bag.add(PigUtil.objectsToTuple(null, null)); inputTuple.set(0, bag); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataBag resultBag = (DataBag) resultTuple.get(0); Assert.assertEquals(resultBag.size(), 3); } @Test public void algebraicInitialTwoParams() throws Exception { EvalFunc<Tuple> func = new DataToDoubleSummarySketch.Initial(null, null); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple(null, null)); bag.add(PigUtil.objectsToTuple(null, null)); bag.add(PigUtil.objectsToTuple(null, null)); inputTuple.set(0, bag); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataBag resultBag = (DataBag) resultTuple.get(0); Assert.assertEquals(resultBag.size(), 3); } @Test public void algebraicIntermediateFinal() throws Exception { EvalFunc<Tuple> func = new DataToDoubleSummarySketch.IntermediateFinal("32"); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); // this is to simulate the output from Initial bag.add(PigUtil.objectsToTuple(PigUtil.tuplesToBag(PigUtil.objectsToTuple("a", 1.0)))); // this is to simulate the output from a prior call of IntermediateFinal UpdatableSketch<Double, DoubleSummary> ts = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); ts.update("b", 1.0); ts.update("a", 2.0); ts.update("b", 2.0); Sketch<DoubleSummary> cs = ts.compact(); bag.add(PigUtil.objectsToTuple(new DataByteArray(cs.toByteArray()))); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { Assert.assertEquals(it.getSummary().getValue(), 3.0); } } @Test public void algebraicIntermediateFinalMaxMode() throws Exception { EvalFunc<Tuple> func = new DataToDoubleSummarySketch.IntermediateFinal("32", "Max"); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); // this is to simulate the output from Initial bag.add(PigUtil.objectsToTuple(PigUtil.tuplesToBag(PigUtil.objectsToTuple("a", 1.0)))); bag.add(PigUtil.objectsToTuple(PigUtil.tuplesToBag(PigUtil.objectsToTuple("b", 1.0)))); bag.add(PigUtil.objectsToTuple(PigUtil.tuplesToBag(PigUtil.objectsToTuple("a", 2.0)))); bag.add(PigUtil.objectsToTuple(PigUtil.tuplesToBag(PigUtil.objectsToTuple("b", 2.0)))); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { Assert.assertEquals(it.getSummary().getValue(), 2.0); } } }
5,713
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/UnionArrayOfDoublesSketchTest.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.pig.tuple; import java.util.Random; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketches; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class UnionArrayOfDoublesSketchTest { @Test public void execNullInput() throws Exception { EvalFunc<Tuple> func = new UnionArrayOfDoublesSketch("32", "1"); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new UnionArrayOfDoublesSketch("32", "1"); Tuple resultTuple = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(resultTuple); } @Test public void exec() throws Exception { EvalFunc<Tuple> func = new UnionArrayOfDoublesSketch("4096", "1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); sketch.update(1, new double[] {1.0}); sketch.update(2, new double[] {1.0}); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); sketch.update(1, new double[] {1.0}); sketch.update(2, new double[] {1.0}); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); for (double[] values: sketch.getValues()) { Assert.assertEquals(values[0], 2.0, 0.0); } } @Test public void accumulatorNullInput() throws Exception { Accumulator<Tuple> func = new UnionArrayOfDoublesSketch(); func.accumulate(null); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorEmptyInputTuple() throws Exception { Accumulator<Tuple> func = new UnionArrayOfDoublesSketch(); func.accumulate(TupleFactory.getInstance().newTuple()); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorNotABag() throws Exception { Accumulator<Tuple> func = new UnionArrayOfDoublesSketch(); func.accumulate(PigUtil.objectsToTuple((Object) null)); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorEmptyBag() throws Exception { Accumulator<Tuple> func = new UnionArrayOfDoublesSketch(); func.accumulate(PigUtil.objectsToTuple(BagFactory.getInstance().newDefaultBag())); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorEmptyInnerTuple() throws Exception { Accumulator<Tuple> func = new UnionArrayOfDoublesSketch(); func.accumulate(PigUtil.objectsToTuple(PigUtil.tuplesToBag(TupleFactory.getInstance().newTuple()))); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorNullSketch() throws Exception { Accumulator<Tuple> func = new UnionArrayOfDoublesSketch(); func.accumulate(PigUtil.objectsToTuple(PigUtil.tuplesToBag(PigUtil.objectsToTuple((Object) null)))); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorEmptySketch() throws Exception { Accumulator<Tuple> func = new UnionArrayOfDoublesSketch("1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } func.accumulate(PigUtil.objectsToTuple(bag)); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulator() throws Exception { Accumulator<Tuple> func = new UnionArrayOfDoublesSketch("4096", "1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); sketch.update(1, new double[] {1.0}); sketch.update(2, new double[] {1.0}); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } func.accumulate(PigUtil.objectsToTuple(bag)); bag = BagFactory.getInstance().newDefaultBag(); { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); sketch.update(1, new double[] {1.0}); sketch.update(2, new double[] {1.0}); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } func.accumulate(PigUtil.objectsToTuple(bag)); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); for (double[] values: sketch.getValues()) { Assert.assertEquals(values[0], 2.0, 0.0); } } @Test public void algebraicInitial() throws Exception { EvalFunc<Tuple> func = new UnionArrayOfDoublesSketch.Initial(null); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(null); bag.add(null); bag.add(null); Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataBag resultBag = (DataBag) resultTuple.get(0); Assert.assertEquals(resultBag.size(), 3); } @Test public void algebraicIntemediateFinalExact() throws Exception { EvalFunc<Tuple> func = new UnionArrayOfDoublesSketch.IntermediateFinal("1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); // this is to simulate the output from Initial { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); sketch.update(1, new double[] {1.0}); sketch.update(2, new double[] {1.0}); DataBag innerBag = PigUtil.tuplesToBag(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); bag.add(PigUtil.objectsToTuple(innerBag)); } // this is to simulate the output from a prior call of IntermediateFinal { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); sketch.update(1, new double[] {1.0}); sketch.update(2, new double[] {1.0}); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); for (double[] values: sketch.getValues()) { Assert.assertEquals(values[0], 2.0, 0.0); } } @Test public void algebraicIntemediateFinalEstimation() throws Exception { EvalFunc<Tuple> func = new UnionArrayOfDoublesSketch.IntermediateFinal("16384", "1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); long value = 1; // this is to simulate the output from Initial { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(16384).build(); for (int i = 0; i < 20000; i++) { sketch.update(value++, new double[] {1.0}); } DataBag innerBag = PigUtil.tuplesToBag(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); bag.add(PigUtil.objectsToTuple(innerBag)); } // this is to simulate the output from a prior call of IntermediateFinal { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(16384).build(); for (int i = 0; i < 20000; i++) { sketch.update(value++, new double[] {1.0}); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 40000.0, 40000.0 * 0.01); for (double[] values: sketch.getValues()) { Assert.assertEquals(values[0], 1.0, 0.0); } } @Test public void algebraicIntemediateFinalSingleCall() throws Exception { EvalFunc<Tuple> func = new UnionArrayOfDoublesSketch.IntermediateFinal("1024", "1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); long value = 1; // this is to simulate the output from a prior call of IntermediateFinal { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(1024).build(); for (int i = 0; i < 10000; i++) { sketch.update(value++, new double[] {1.0}); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 10000.0, 10000.0 * 0.02); for (double[] values: sketch.getValues()) { Assert.assertEquals(values[0], 1.0, 0.0); } } @Test public void algebraicIntemediateFinalRandomized() throws Exception { EvalFunc<Tuple> func = new UnionArrayOfDoublesSketch.IntermediateFinal("16384", "1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); long key = 1; Random rnd = new Random(); long uniques = 0; long updates = 0; // this is to simulate the output from a prior call of IntermediateFinal { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(16384).build(); for (int i = 0; i < 40000; i++) { sketch.update(key++, new double[] {rnd.nextDouble() * 20}); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 40000; } key -= 20000; // overlap { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(16384).build(); for (int i = 0; i < 60000; i++) { sketch.update(key++, new double[] {rnd.nextDouble() * 20}); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 60000; } key -= 20000; // overlap { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(16384).build(); for (int i = 0; i < 60000; i++) { sketch.update(key++, new double[] {rnd.nextDouble() * 20}); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 60000; } key -= 20000; // overlap { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(16384).build(); for (int i = 0; i < 60000; i++) { sketch.update(key++, new double[] {rnd.nextDouble() * 20}); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 60000; } { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(16384).build(); for (int i = 0; i < 40000; i++) { sketch.update(key++, new double[] {rnd.nextDouble() * 20}); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 40000; } { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(16384).build(); for (int i = 0; i < 40000; i++) { sketch.update(key++, new double[] {rnd.nextDouble() * 20}); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 40000; } key -= 20000; // overlap { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(16384).build(); for (int i = 0; i < 60000; i++) { sketch.update(key++, new double[] {rnd.nextDouble() * 20}); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 60000; } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), uniques, uniques * 0.01); double sum = 0; for (double[] values: sketch.getValues()) { sum += values[0]; } // each update added 10 to the total on average Assert.assertEquals(sum / sketch.getTheta(), updates * 10.0, updates * 10.0 * 0.02); // there is a slight chance of failing here } }
5,714
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/DataToArrayOfDoublesSketchTest.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.pig.tuple; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketches; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class DataToArrayOfDoublesSketchTest { @Test public void execNullInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch(); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch(); Tuple resultTuple = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(resultTuple); } @Test public void execEmptyBag() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch("1"); Tuple inputTuple = PigUtil.objectsToTuple(BagFactory.getInstance().newDefaultBag()); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test(expectedExceptions = IllegalArgumentException.class) public void execWrongSizeOfInnerTuple() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch("32", "1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple(1)); Tuple inputTuple = PigUtil.objectsToTuple(bag); func.exec(inputTuple); } @Test(expectedExceptions = IllegalArgumentException.class) public void execWrongKeyType() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch("32", "1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple(new Object(), 1.0)); // Object in place of key is not supported Tuple inputTuple = PigUtil.objectsToTuple(bag); func.exec(inputTuple); } @Test public void execAllInputTypes() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch("32", "1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple("a", 1.0)); bag.add(PigUtil.objectsToTuple("b", 1.0)); bag.add(PigUtil.objectsToTuple("a", 2.0)); bag.add(PigUtil.objectsToTuple("b", 2.0)); bag.add(PigUtil.objectsToTuple(1, 3.0)); bag.add(PigUtil.objectsToTuple(2L, 3.0)); bag.add(PigUtil.objectsToTuple(1f, 3.0)); bag.add(PigUtil.objectsToTuple(2.0, 3.0)); bag.add(PigUtil.objectsToTuple((byte) 3, 3.0)); bag.add(PigUtil.objectsToTuple(new DataByteArray("c".getBytes()), 3.0)); Tuple inputTuple = PigUtil.objectsToTuple(bag); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 8.0, 0.0); for (double[] values: sketch.getValues()) { Assert.assertEquals(values[0], 3.0); } } @Test public void execWithSampling() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch("1024", "0.5", "1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); int uniques = 10000; for (int i = 0; i < uniques; i++) { bag.add(PigUtil.objectsToTuple(i, 1.0)); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), uniques, uniques * 0.01); } @Test public void accumulator() throws Exception { Accumulator<Tuple> func = new DataToArrayOfDoublesSketch("32", "1"); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple("a", 1.0)); inputTuple.set(0, bag); func.accumulate(inputTuple); inputTuple = TupleFactory.getInstance().newTuple(1); bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple("b", 1.0)); bag.add(PigUtil.objectsToTuple("a", 2.0)); bag.add(PigUtil.objectsToTuple("b", 2.0)); inputTuple.set(0, bag); func.accumulate(inputTuple); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); for (double[] values: sketch.getValues()) { Assert.assertEquals(values[0], 3.0); } // after cleanup, the value should always be 0 func.cleanup(); resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch2 = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch2.getEstimate(), 0.0, 0.0); } @Test public void algebraicInitial() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch.Initial(null); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple(null, null)); bag.add(PigUtil.objectsToTuple(null, null)); bag.add(PigUtil.objectsToTuple(null, null)); inputTuple.set(0, bag); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataBag resultBag = (DataBag) resultTuple.get(0); Assert.assertEquals(resultBag.size(), 3); } @Test public void algebraicIntermediateFinal() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch.IntermediateFinal("1"); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); // this is to simulate the output from Initial bag.add(PigUtil.objectsToTuple(PigUtil.tuplesToBag(PigUtil.objectsToTuple("a", 1.0)))); // this is to simulate the output from a prior call of IntermediateFinal { ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); sketch.update("b", new double[] {1.0}); sketch.update("a", new double[] {2.0}); sketch.update("b", new double[] {2.0}); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); for (double[] values: sketch.getValues()) { Assert.assertEquals(values[0], 3.0); } } @Test public void algebraicIntermediateFinalWithSampling() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch.IntermediateFinal("1024", "0.5", "1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); int uniques = 10000; for (int i = 0; i < uniques; i++) { bag.add(PigUtil.objectsToTuple(i, 1.0)); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(PigUtil.tuplesToBag(PigUtil.objectsToTuple(bag)))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.heapifySketch(Memory.wrap(bytes.get())); Assert.assertEquals(sketch.getEstimate(), uniques, uniques * 0.01); } @Test(expectedExceptions = IllegalArgumentException.class) public void algebraicIntermediateFinalNullBag() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch.IntermediateFinal("32", "1"); func.exec(TupleFactory.getInstance().newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void algebraicIntermediateFinalWrongType() throws Exception { EvalFunc<Tuple> func = new DataToArrayOfDoublesSketch.IntermediateFinal("32", "1"); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(TupleFactory.getInstance().newTuple(1.0)); func.exec(TupleFactory.getInstance().newTuple(bag)); } }
5,715
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/DoubleSummarySketchToEstimatesTest.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.pig.tuple; import org.testng.annotations.Test; import org.testng.Assert; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.datasketches.tuple.UpdatableSketch; import org.apache.datasketches.tuple.UpdatableSketchBuilder; import org.apache.datasketches.tuple.adouble.DoubleSummary; import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; @SuppressWarnings("javadoc") public class DoubleSummarySketchToEstimatesTest { @Test public void nullInput() throws Exception { EvalFunc<Tuple> func = new DoubleSummarySketchToEstimates(); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } @Test public void emptyInput() throws Exception { EvalFunc<Tuple> func = new DoubleSummarySketchToEstimates(); Tuple resultTuple = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(resultTuple); } @Test public void emptySketch() throws Exception { EvalFunc<Tuple> func = new DoubleSummarySketchToEstimates(); UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 2); Assert.assertEquals(resultTuple.get(0), 0.0); Assert.assertEquals(resultTuple.get(0), 0.0); } @Test public void normalCase() throws Exception { EvalFunc<Tuple> func = new DoubleSummarySketchToEstimates(); UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); int iterations = 100000; for (int i = 0; i < iterations; i++) { sketch.update(i, 1.0); } for (int i = 0; i < iterations; i++) { sketch.update(i, 1.0); } Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 2); Assert.assertEquals((double) resultTuple.get(0), iterations, iterations * 0.03); Assert.assertEquals((double) resultTuple.get(1), 2 * iterations, 2 * iterations * 0.03); } }
5,716
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/ArrayOfDoublesSketchToVariancesTest.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.pig.tuple; import java.util.Random; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class ArrayOfDoublesSketchToVariancesTest { @Test public void nullInput() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToVariances(); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } @Test public void emptyInputTuple() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToVariances(); Tuple resultTuple = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(resultTuple); } @Test public void emptyInputSketch() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToVariances(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNull(resultTuple); } @Test public void oneEntryInputSketch() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToVariances(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); sketch.update(1, new double[] {1}); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertEquals(resultTuple.get(0), 0.0); } @Test public void manyEntriesTwoValuesInputSketch() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToVariances(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(); Random rand = new Random(0); int numKeys = 10000; // to saturate the sketch with default number of nominal entries (4K) for (int i = 0; i < numKeys; i++ ) { // two random values normally distributed with standard deviations of 1 and 10 sketch.update(i, new double[] {rand.nextGaussian(), rand.nextGaussian() * 10.0}); } Assert.assertTrue(sketch.getRetainedEntries() >= 4096); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 2); Assert.assertEquals((double) resultTuple.get(0), 1.0, 0.04); Assert.assertEquals((double) resultTuple.get(1), 100.0, 100.0 * 0.04); // squared standard deviation within 4% } }
5,717
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/DoubleSummarySketchToPercentileTest.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.pig.tuple; import org.testng.annotations.Test; import org.testng.Assert; import java.util.Arrays; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.datasketches.tuple.UpdatableSketch; import org.apache.datasketches.tuple.UpdatableSketchBuilder; import org.apache.datasketches.tuple.adouble.DoubleSummary; import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; @SuppressWarnings("javadoc") public class DoubleSummarySketchToPercentileTest { @Test public void emptySketch() throws Exception { EvalFunc<Double> func = new DoubleSummarySketchToPercentile(); UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); Tuple inputTuple = TupleFactory.getInstance(). newTuple(Arrays.asList(new DataByteArray(sketch.compact().toByteArray()), 0.0)); double result = func.exec(inputTuple); Assert.assertEquals(result, Double.NaN); } @Test public void normalCase() throws Exception { EvalFunc<Double> func = new DoubleSummarySketchToPercentile(); UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); int iterations = 100000; for (int i = 0; i < iterations; i++) { sketch.update(i, (double) i); } for (int i = 0; i < iterations; i++) { sketch.update(i, (double) i); } Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()), 50.0); double result = func.exec(inputTuple); Assert.assertEquals(result, iterations, iterations * 0.02); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongNumberOfInputs() throws Exception { EvalFunc<Double> func = new DoubleSummarySketchToPercentile(); func.exec(PigUtil.objectsToTuple(1.0)); } @Test(expectedExceptions = IllegalArgumentException.class) public void percentileOutOfRange() throws Exception { EvalFunc<Double> func = new DoubleSummarySketchToPercentile(); UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); func.exec(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()), 200.0)); } }
5,718
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/ArrayOfDoublesSketchToQuantilesSketchTest.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.pig.tuple; import java.util.Arrays; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.quantiles.DoublesSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class ArrayOfDoublesSketchToQuantilesSketchTest { static final TupleFactory tupleFactory = TupleFactory.getInstance(); @Test public void nullInput() throws Exception { EvalFunc<DataByteArray> func = new ArrayOfDoublesSketchToQuantilesSketch(); DataByteArray result = func.exec(null); Assert.assertNull(result); } @Test public void emptyInputTuple() throws Exception { EvalFunc<DataByteArray> func = new ArrayOfDoublesSketchToQuantilesSketch(); DataByteArray result = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(result); } @Test public void emptyInputSketch() throws Exception { EvalFunc<DataByteArray> func = new ArrayOfDoublesSketchToQuantilesSketch(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); DataByteArray result = func.exec(tupleFactory.newTuple(new DataByteArray(sketch.compact().toByteArray()))); Assert.assertNotNull(result); DoublesSketch quantilesSketch = DoublesSketch.wrap(Memory.wrap(result.get())); Assert.assertTrue(quantilesSketch.isEmpty()); } @Test public void nonEmptyInputSketchWithTwoColumnsExplicitK() throws Exception { int k = 256; EvalFunc<DataByteArray> func = new ArrayOfDoublesSketchToQuantilesSketch(Integer.toString(k)); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(); sketch.update(1, new double[] {1.0, 2.0}); sketch.update(2, new double[] {10.0, 20.0}); DataByteArray result = func.exec(tupleFactory.newTuple(Arrays.asList( new DataByteArray(sketch.compact().toByteArray()), 2 ))); Assert.assertNotNull(result); DoublesSketch quantilesSketch = DoublesSketch.wrap(Memory.wrap(result.get())); Assert.assertFalse(quantilesSketch.isEmpty()); Assert.assertEquals(quantilesSketch.getK(), k); Assert.assertEquals(quantilesSketch.getMinValue(), 2.0); Assert.assertEquals(quantilesSketch.getMaxValue(), 20.0); } }
5,719
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/ArrayOfDoublesSketchToMeansTest.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.pig.tuple; import java.util.Random; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class ArrayOfDoublesSketchToMeansTest { @Test public void nullInput() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToMeans(); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } @Test public void emptyInputTuple() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToMeans(); Tuple resultTuple = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(resultTuple); } @Test public void emptyInputSketch() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToMeans(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNull(resultTuple); } @Test public void oneEntryInputSketch() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToMeans(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); sketch.update(1, new double[] {1}); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertEquals(resultTuple.get(0), 1.0); } @Test public void manyEntriesTwoValuesInputSketch() throws Exception { EvalFunc<Tuple> func = new ArrayOfDoublesSketchToMeans(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(); Random rand = new Random(0); int numKeys = 10000; // to saturate the sketch with default number of nominal entries (4K) for (int i = 0; i < numKeys; i++ ) { // two random values normally distributed with means of 0 and 1 sketch.update(i, new double[] {rand.nextGaussian(), rand.nextGaussian() + 1.0}); } Assert.assertTrue(sketch.getRetainedEntries() >= 4096); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray())); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 2); Assert.assertEquals((double) resultTuple.get(0), 0.0, 0.04); Assert.assertEquals((double) resultTuple.get(1), 1.0, 0.04); } }
5,720
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/ArrayOfDoublesSketchToNumberOfRetainedEntriesTest.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.pig.tuple; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.junit.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class ArrayOfDoublesSketchToNumberOfRetainedEntriesTest { static final TupleFactory tupleFactory = TupleFactory.getInstance(); @Test public void nullInput() throws Exception { EvalFunc<Integer> func = new ArrayOfDoublesSketchToNumberOfRetainedEntries(); Integer result = func.exec(null); Assert.assertNull(result); } @Test public void emptyInputTuple() throws Exception { EvalFunc<Integer> func = new ArrayOfDoublesSketchToNumberOfRetainedEntries(); Integer result = func.exec(tupleFactory.newTuple()); Assert.assertNull(result); } @Test public void emptyInputSketch() throws Exception { EvalFunc<Integer> func = new ArrayOfDoublesSketchToNumberOfRetainedEntries(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); Integer result = func.exec(tupleFactory.newTuple(new DataByteArray(sketch.compact().toByteArray()))); Assert.assertNotNull(result); Assert.assertEquals((int) result, 0); } @Test public void nonEmptyInputSketch() throws Exception { EvalFunc<Integer> func = new ArrayOfDoublesSketchToNumberOfRetainedEntries(); ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); sketch.update(1, new double[] {0}); Integer result = func.exec(tupleFactory.newTuple(new DataByteArray(sketch.compact().toByteArray()))); Assert.assertNotNull(result); Assert.assertEquals((int) result, 1); } }
5,721
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/PigUtil.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.pig.tuple; import java.util.List; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; @SuppressWarnings("javadoc") public class PigUtil { /** * Wraps input Objects in a Tuple * @param objects Objects intended to be wrapped * @return a Pig Tuple containing the input Objects */ public static Tuple objectsToTuple(final Object ... objects) { final Tuple tuple = TupleFactory.getInstance().newTuple(); for (final Object object: objects) { tuple.append(object); } return tuple; } /** * Wraps a set of Tuples in a DataBag * @param tuples Tuples to wrap * @return a Pig DataBag containing the input Tuples */ public static DataBag tuplesToBag(final Tuple ... tuples) { final DataBag bag = BagFactory.getInstance().newDefaultBag(); for (final Tuple tuple: tuples) { bag.add(tuple); } return bag; } /** * Wraps a List of objects into a DataBag of Tuples (one object per Tuple) * @param list List of items to wrap * @param <T> Type of objects in the List * @return a Pig DataBag containing Tuples populated with list items */ public static <T> DataBag listToBagOfTuples(final List<T> list) { final DataBag bag = BagFactory.getInstance().newDefaultBag(); for (final Object object: list) { final Tuple tuple = TupleFactory.getInstance().newTuple(); tuple.append(object); bag.add(tuple); } return bag; } }
5,722
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/tuple/UnionDoubleSummarySketchTest.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.pig.tuple; import java.util.Random; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.tuple.Sketch; import org.apache.datasketches.tuple.SketchIterator; 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; import org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer; import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; @SuppressWarnings("javadoc") public class UnionDoubleSummarySketchTest { @Test public void execNullInput() throws Exception { EvalFunc<Tuple> func = new UnionDoubleSummarySketch(); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new UnionDoubleSummarySketch(); Tuple resultTuple = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(resultTuple); } @Test public void exec() throws Exception { EvalFunc<Tuple> func = new UnionDoubleSummarySketch("4096"); DataBag bag = BagFactory.getInstance().newDefaultBag(); { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); sketch.update(1, 1.0); sketch.update(2, 1.0); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); sketch.update(1, 1.0); sketch.update(2, 1.0); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { Assert.assertEquals(it.getSummary().getValue(), 2.0, 0.0); } } @Test public void execMaxMode() throws Exception { EvalFunc<Tuple> func = new UnionDoubleSummarySketch("4096", "Max"); DataBag bag = BagFactory.getInstance().newDefaultBag(); { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); sketch.update(1, 1.0); sketch.update(2, 1.0); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); sketch.update(1, 3.0); sketch.update(2, 3.0); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { Assert.assertEquals(it.getSummary().getValue(), 3.0, 0.0); } } @Test public void accumulatorNullInput() throws Exception { Accumulator<Tuple> func = new UnionDoubleSummarySketch("32"); func.accumulate(null); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorEmptyInputTuple() throws Exception { Accumulator<Tuple> func = new UnionDoubleSummarySketch("32"); func.accumulate(TupleFactory.getInstance().newTuple()); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorNotABag() throws Exception { Accumulator<Tuple> func = new UnionDoubleSummarySketch("32"); func.accumulate(PigUtil.objectsToTuple((Object) null)); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorEmptyBag() throws Exception { Accumulator<Tuple> func = new UnionDoubleSummarySketch("32"); func.accumulate(PigUtil.objectsToTuple(BagFactory.getInstance().newDefaultBag())); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorEmptyInnerTuple() throws Exception { Accumulator<Tuple> func = new UnionDoubleSummarySketch("32"); func.accumulate(PigUtil.objectsToTuple(PigUtil.tuplesToBag(TupleFactory.getInstance().newTuple()))); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorNullSketch() throws Exception { Accumulator<Tuple> func = new UnionDoubleSummarySketch("32"); func.accumulate(PigUtil.objectsToTuple(PigUtil.tuplesToBag(PigUtil.objectsToTuple((Object) null)))); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulatorEmptySketch() throws Exception { Accumulator<Tuple> func = new UnionDoubleSummarySketch("4096"); DataBag bag = BagFactory.getInstance().newDefaultBag(); { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } func.accumulate(PigUtil.objectsToTuple(bag)); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 0.0); } @Test public void accumulator() throws Exception { Accumulator<Tuple> func = new UnionDoubleSummarySketch("4096"); DataBag bag = BagFactory.getInstance().newDefaultBag(); { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); sketch.update(1, 1.0); sketch.update(2, 1.0); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } func.accumulate(PigUtil.objectsToTuple(bag)); bag = BagFactory.getInstance().newDefaultBag(); { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); sketch.update(1, 1.0); sketch.update(2, 1.0); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } func.accumulate(PigUtil.objectsToTuple(bag)); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { Assert.assertEquals(it.getSummary().getValue(), 2.0, 0.0); } } @Test public void algebraicInitial() throws Exception { EvalFunc<Tuple> func = new UnionDoubleSummarySketch.Initial(null); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(null); bag.add(null); bag.add(null); Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataBag resultBag = (DataBag) resultTuple.get(0); Assert.assertEquals(resultBag.size(), 3); } @Test public void algebraicIntemediateFinalExactMinMode() throws Exception { EvalFunc<Tuple> func = new UnionDoubleSummarySketch.IntermediateFinal("4096", "Min"); DataBag bag = BagFactory.getInstance().newDefaultBag(); // this is to simulate the output from Initial { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); sketch.update(1, 1.0); sketch.update(2, 1.0); DataBag innerBag = PigUtil.tuplesToBag(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); bag.add(PigUtil.objectsToTuple(innerBag)); } // this is to simulate the output from a prior call of IntermediateFinal { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).build(); sketch.update(1, 3.0); sketch.update(2, 3.0); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.0); SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { Assert.assertEquals(it.getSummary().getValue(), 1.0, 0.0); } } @Test public void algebraicIntemediateFinalEstimation() throws Exception { EvalFunc<Tuple> func = new UnionDoubleSummarySketch.IntermediateFinal("16384"); DataBag bag = BagFactory.getInstance().newDefaultBag(); long value = 1; // this is to simulate the output from Initial { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>( new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).setNominalEntries(16384).build(); for (int i = 0; i < 20000; i++) { sketch.update(value++, 1.0); } DataBag innerBag = PigUtil.tuplesToBag(PigUtil.objectsToTuple( new DataByteArray(sketch.compact().toByteArray()))); bag.add(PigUtil.objectsToTuple(innerBag)); } // this is to simulate the output from a prior call of IntermediateFinal { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>( new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).setNominalEntries(16384).build(); for (int i = 0; i < 20000; i++) { sketch.update(value++, 1.0); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 40000.0, 40000.0 * 0.01); SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { Assert.assertEquals(it.getSummary().getValue(), 1.0, 0.0); } } @Test public void algebraicIntemediateFinalSingleCall() throws Exception { EvalFunc<Tuple> func = new UnionDoubleSummarySketch.IntermediateFinal("1024"); DataBag bag = BagFactory.getInstance().newDefaultBag(); long value = 1; // this is to simulate the output from a prior call of IntermediateFinal { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>( new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).setNominalEntries(1024).build(); for (int i = 0; i < 10000; i++) { sketch.update(value++, 1.0); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), 10000.0, 10000.0 * 0.02); SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { Assert.assertEquals(it.getSummary().getValue(), 1.0, 0.0); } } @Test public void algebraicIntemediateFinalRandomized() throws Exception { EvalFunc<Tuple> func = new UnionDoubleSummarySketch.IntermediateFinal("16384"); DataBag bag = BagFactory.getInstance().newDefaultBag(); long key = 1; Random rnd = new Random(); long uniques = 0; long updates = 0; // this is to simulate the output from a prior call of IntermediateFinal { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>( new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).setNominalEntries(16384).build(); for (int i = 0; i < 40000; i++) { sketch.update(key++, rnd.nextDouble() * 20); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 40000; } key -= 20000; // overlap { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>( new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).setNominalEntries(16384).build(); for (int i = 0; i < 60000; i++) { sketch.update(key++, rnd.nextDouble() * 20); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 60000; } key -= 20000; // overlap { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).setNominalEntries(16384).build(); for (int i = 0; i < 60000; i++) { sketch.update(key++, rnd.nextDouble() * 20); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 60000; } key -= 20000; // overlap { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>( new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).setNominalEntries(16384).build(); for (int i = 0; i < 60000; i++) { sketch.update(key++, rnd.nextDouble() * 20); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 60000; } { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>( new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).setNominalEntries(16384).build(); for (int i = 0; i < 40000; i++) { sketch.update(key++, rnd.nextDouble() * 20); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 40000; } { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>( new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).setNominalEntries(16384).build(); for (int i = 0; i < 40000; i++) { sketch.update(key++, rnd.nextDouble() * 20); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 40000; } key -= 20000; // overlap { UpdatableSketch<Double, DoubleSummary> sketch = new UpdatableSketchBuilder<>( new DoubleSummaryFactory(DoubleSummary.Mode.Sum)).setNominalEntries(16384).build(); for (int i = 0; i < 60000; i++) { sketch.update(key++, rnd.nextDouble() * 20); } bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.compact().toByteArray()))); uniques += 40000; updates += 60000; } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); Sketch<DoubleSummary> sketch = Sketches.heapifySketch(Memory.wrap(bytes.get()), new DoubleSummaryDeserializer()); Assert.assertEquals(sketch.getEstimate(), uniques, uniques * 0.01); double sum = 0; SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { sum += it.getSummary().getValue(); } // each update added 10 to the total on average // there is a slight chance of failing here Assert.assertEquals(sum / sketch.getTheta(), updates * 10.0, updates * 10.0 * 0.02); } }
5,723
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/frequencies/DataToFrequentStringsSketchTest.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.pig.frequencies; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.ArrayOfStringsSerDe; import org.apache.datasketches.frequencies.ItemsSketch; import org.apache.datasketches.pig.tuple.PigUtil; @SuppressWarnings("javadoc") public class DataToFrequentStringsSketchTest { @Test public void execNullInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToFrequentStringsSketch("8"); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToFrequentStringsSketch("8"); Tuple resultTuple = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(resultTuple); } @Test public void execEmptyBag() throws Exception { EvalFunc<Tuple> func = new DataToFrequentStringsSketch("8"); Tuple inputTuple = PigUtil.objectsToTuple(BagFactory.getInstance().newDefaultBag()); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertEquals(sketch.getNumActiveItems(), 0); } @Test(expectedExceptions = IllegalArgumentException.class) public void execWrongSizeOfInnerTuple() throws Exception { EvalFunc<Tuple> func = new DataToFrequentStringsSketch("8"); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple()); Tuple inputTuple = PigUtil.objectsToTuple(bag); func.exec(inputTuple); } @Test(expectedExceptions = ClassCastException.class) public void execWrongItemType() throws Exception { EvalFunc<Tuple> func = new DataToFrequentStringsSketch("8"); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple(new Object(), 1L)); // Object in place of String is not supported Tuple inputTuple = PigUtil.objectsToTuple(bag); func.exec(inputTuple); } @Test(expectedExceptions = ClassCastException.class) public void execWrongCountType() throws Exception { EvalFunc<Tuple> func = new DataToFrequentStringsSketch("8"); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple("a", 1)); // integer count is not supported Tuple inputTuple = PigUtil.objectsToTuple(bag); func.exec(inputTuple); } @Test public void exec() throws Exception { EvalFunc<Tuple> func = new DataToFrequentStringsSketch("8"); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple("a")); bag.add(PigUtil.objectsToTuple("b", 5L)); bag.add(PigUtil.objectsToTuple("a", 2L)); bag.add(PigUtil.objectsToTuple("b")); Tuple inputTuple = PigUtil.objectsToTuple(bag); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertEquals(sketch.getNumActiveItems(), 2); Assert.assertEquals(sketch.getEstimate("a"), 3); Assert.assertEquals(sketch.getEstimate("b"), 6); } @Test public void accumulator() throws Exception { Accumulator<Tuple> func = new DataToFrequentStringsSketch("8"); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple("a")); inputTuple.set(0, bag); func.accumulate(inputTuple); inputTuple = TupleFactory.getInstance().newTuple(1); bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple("b")); bag.add(PigUtil.objectsToTuple("a", 2L)); bag.add(PigUtil.objectsToTuple("b", 5L)); inputTuple.set(0, bag); func.accumulate(inputTuple); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertEquals(sketch.getNumActiveItems(), 2); Assert.assertEquals(sketch.getEstimate("a"), 3); Assert.assertEquals(sketch.getEstimate("b"), 6); // after cleanup, the value should always be 0 func.cleanup(); resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch2 = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertTrue(sketch2.isEmpty()); Assert.assertEquals(sketch2.getNumActiveItems(), 0); } @Test public void algebraicInitial() throws Exception { EvalFunc<Tuple> func = new DataToFrequentStringsSketch.Initial(null); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(PigUtil.objectsToTuple(null, null)); bag.add(PigUtil.objectsToTuple(null, null)); bag.add(PigUtil.objectsToTuple(null, null)); inputTuple.set(0, bag); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataBag resultBag = (DataBag) resultTuple.get(0); Assert.assertEquals(resultBag.size(), 3); } @Test(expectedExceptions = IllegalArgumentException.class) public void algebraicIntermediateFinalWrongType() throws Exception { EvalFunc<Tuple> func = new DataToFrequentStringsSketch.IntermediateFinal("8"); DataBag bag = BagFactory.getInstance().newDefaultBag(); // this bag must have tuples with either bags or data byte arrays bag.add(TupleFactory.getInstance().newTuple(1.0)); func.exec(TupleFactory.getInstance().newTuple(bag)); } @Test public void algebraicIntermediateFinal() throws Exception { EvalFunc<Tuple> func = new DataToFrequentStringsSketch.IntermediateFinal("8"); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); // this is to simulate the output from Initial bag.add(PigUtil.objectsToTuple(PigUtil.tuplesToBag(PigUtil.objectsToTuple("a")))); // this is to simulate the output from a prior call of IntermediateFinal ItemsSketch<String> s = new ItemsSketch<>(8); s.update("b", 1L); s.update("a", 2L); s.update("b", 3L); bag.add(PigUtil.objectsToTuple(new DataByteArray(s.toByteArray(new ArrayOfStringsSerDe())))); Tuple resultTuple = func.exec(inputTuple); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertEquals(sketch.getNumActiveItems(), 2); Assert.assertEquals(sketch.getEstimate("a"), 3); Assert.assertEquals(sketch.getEstimate("b"), 4); } }
5,724
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/frequencies/UnionFrequentStringsSketchTest.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.pig.frequencies; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.ArrayOfStringsSerDe; import org.apache.datasketches.frequencies.ErrorType; import org.apache.datasketches.frequencies.ItemsSketch; import org.apache.datasketches.pig.tuple.PigUtil; @SuppressWarnings("javadoc") public class UnionFrequentStringsSketchTest { @Test public void execNullInput() throws Exception { EvalFunc<Tuple> func = new UnionFrequentStringsSketch("8"); Tuple resultTuple = func.exec(null); Assert.assertNull(resultTuple); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new UnionFrequentStringsSketch("8"); Tuple resultTuple = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(resultTuple); } @Test public void exec() throws Exception { EvalFunc<Tuple> func = new UnionFrequentStringsSketch("8"); DataBag bag = BagFactory.getInstance().newDefaultBag(); { ItemsSketch<String> sketch = new ItemsSketch<>(8); sketch.update("a"); sketch.update("b"); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe())))); } { ItemsSketch<String> sketch = new ItemsSketch<>(8); sketch.update("a"); sketch.update("b"); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe())))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertEquals(sketch.getNumActiveItems(), 2); Assert.assertEquals(sketch.getEstimate("a"), 2); Assert.assertEquals(sketch.getEstimate("b"), 2); } @Test public void accumulatorNullInput() throws Exception { Accumulator<Tuple> func = new UnionFrequentStringsSketch("8"); func.accumulate(null); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getNumActiveItems(), 0); } @Test public void accumulatorEmptyInputTuple() throws Exception { Accumulator<Tuple> func = new UnionFrequentStringsSketch("8"); func.accumulate(TupleFactory.getInstance().newTuple()); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getNumActiveItems(), 0); } @Test public void accumulatorNotABag() throws Exception { Accumulator<Tuple> func = new UnionFrequentStringsSketch("8"); func.accumulate(PigUtil.objectsToTuple((Object) null)); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getNumActiveItems(), 0); } @Test public void accumulatorEmptyBag() throws Exception { Accumulator<Tuple> func = new UnionFrequentStringsSketch("8"); func.accumulate(PigUtil.objectsToTuple(BagFactory.getInstance().newDefaultBag())); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getNumActiveItems(), 0); } @Test public void accumulatorEmptyInnerTuple() throws Exception { Accumulator<Tuple> func = new UnionFrequentStringsSketch("8"); func.accumulate(PigUtil.objectsToTuple(PigUtil.tuplesToBag(TupleFactory.getInstance().newTuple()))); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getNumActiveItems(), 0); } @Test public void accumulatorNullSketch() throws Exception { Accumulator<Tuple> func = new UnionFrequentStringsSketch("8"); func.accumulate(PigUtil.objectsToTuple(PigUtil.tuplesToBag(PigUtil.objectsToTuple((Object) null)))); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getNumActiveItems(), 0); } @Test public void accumulatorEmptySketch() throws Exception { Accumulator<Tuple> func = new UnionFrequentStringsSketch("8"); DataBag bag = BagFactory.getInstance().newDefaultBag(); { ItemsSketch<String> sketch = new ItemsSketch<>(8); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe())))); } func.accumulate(PigUtil.objectsToTuple(bag)); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getNumActiveItems(), 0); } @Test public void accumulator() throws Exception { Accumulator<Tuple> func = new UnionFrequentStringsSketch("8"); DataBag bag = BagFactory.getInstance().newDefaultBag(); { ItemsSketch<String> sketch = new ItemsSketch<>(8); sketch.update("a"); sketch.update("b"); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe())))); } func.accumulate(PigUtil.objectsToTuple(bag)); bag = BagFactory.getInstance().newDefaultBag(); { ItemsSketch<String> sketch = new ItemsSketch<>(8); sketch.update("a"); sketch.update("b"); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe())))); } func.accumulate(PigUtil.objectsToTuple(bag)); Tuple resultTuple = func.getValue(); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getNumActiveItems(), 2); Assert.assertEquals(sketch.getEstimate("a"), 2); Assert.assertEquals(sketch.getEstimate("b"), 2); } @Test public void algebraicInitial() throws Exception { EvalFunc<Tuple> func = new UnionFrequentStringsSketch.Initial(null); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(null); bag.add(null); bag.add(null); Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataBag resultBag = (DataBag) resultTuple.get(0); Assert.assertEquals(resultBag.size(), 3); } @Test public void algebraicIntemediateFinalExact() throws Exception { EvalFunc<Tuple> func = new UnionFrequentStringsSketch.IntermediateFinal("8"); DataBag bag = BagFactory.getInstance().newDefaultBag(); // this is to simulate the output from Initial { ItemsSketch<String> sketch = new ItemsSketch<>(8); sketch.update("a"); sketch.update("b"); DataBag innerBag = PigUtil.tuplesToBag(PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe())))); bag.add(PigUtil.objectsToTuple(innerBag)); } // this is to simulate the output from a prior call of IntermediateFinal { ItemsSketch<String> sketch = new ItemsSketch<>(8); sketch.update("a", 2L); sketch.update("b", 3L); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe())))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getNumActiveItems(), 2); Assert.assertEquals(sketch.getEstimate("a"), 3); Assert.assertEquals(sketch.getEstimate("b"), 4); } @Test public void algebraicIntemediateFinalEstimation() throws Exception { EvalFunc<Tuple> func = new UnionFrequentStringsSketch.IntermediateFinal("8"); DataBag bag = BagFactory.getInstance().newDefaultBag(); // this is to simulate the output from Initial { ItemsSketch<String> sketch = new ItemsSketch<>(8); sketch.update("a", 10); sketch.update("b"); sketch.update("c"); sketch.update("d"); sketch.update("e"); sketch.update("f"); sketch.update("g"); sketch.update("g"); DataBag innerBag = PigUtil.tuplesToBag(PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe())))); bag.add(PigUtil.objectsToTuple(innerBag)); } // this is to simulate the output from a prior call of IntermediateFinal { ItemsSketch<String> sketch = new ItemsSketch<>(8); sketch.update("a"); sketch.update("a"); sketch.update("g", 5); sketch.update("h"); sketch.update("i"); sketch.update("j"); sketch.update("k"); sketch.update("l"); bag.add(PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe())))); } Tuple resultTuple = func.exec(PigUtil.objectsToTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); Assert.assertTrue(bytes.size() > 0); ItemsSketch<String> sketch = ItemsSketch.getInstance(Memory.wrap(bytes.get()), new ArrayOfStringsSerDe()); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getStreamLength(), 29); ItemsSketch.Row<String>[] items = sketch.getFrequentItems(ErrorType.NO_FALSE_POSITIVES); Assert.assertEquals(items.length, 2); // only 2 items ("a" and "g") should have counts more than 1 int count = 0; for (ItemsSketch.Row<String> item: items) { if (item.getLowerBound() > 1) { count++; } } Assert.assertEquals(count, 2); } }
5,725
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/frequencies/FrequentStringsSketchToEstimatesTest.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.pig.frequencies; import java.util.Iterator; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.ArrayOfStringsSerDe; import org.apache.datasketches.frequencies.ItemsSketch; import org.apache.datasketches.pig.tuple.PigUtil; @SuppressWarnings("javadoc") public class FrequentStringsSketchToEstimatesTest { @Test public void nullInput() throws Exception { EvalFunc<DataBag> func = new FrequentStringsSketchToEstimates(); DataBag bag = func.exec(null); Assert.assertNull(bag); } @Test public void emptyInput() throws Exception { EvalFunc<DataBag> func = new FrequentStringsSketchToEstimates(); DataBag bag = func.exec(TupleFactory.getInstance().newTuple()); Assert.assertNull(bag); } @Test public void emptySketch() throws Exception { EvalFunc<DataBag> func = new FrequentStringsSketchToEstimates(); ItemsSketch<String> sketch = new ItemsSketch<>(8); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe()))); DataBag bag = func.exec(inputTuple); Assert.assertNotNull(bag); Assert.assertEquals(bag.size(), 0); } @Test public void exact() throws Exception { EvalFunc<DataBag> func = new FrequentStringsSketchToEstimates(); ItemsSketch<String> sketch = new ItemsSketch<>(8); sketch.update("a"); sketch.update("a"); sketch.update("b"); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe()))); DataBag bag = func.exec(inputTuple); Assert.assertNotNull(bag); Assert.assertEquals(bag.size(), 2); Iterator<Tuple> it = bag.iterator(); Tuple tuple1 = it.next(); Assert.assertEquals(tuple1.size(), 4); Assert.assertEquals((String)tuple1.get(0), "a"); Assert.assertEquals((long)tuple1.get(1), 2L); Assert.assertEquals((long)tuple1.get(2), 2L); Assert.assertEquals((long)tuple1.get(3), 2L); Tuple tuple2 = it.next(); Assert.assertEquals(tuple2.size(), 4); Assert.assertEquals((String)tuple2.get(0), "b"); Assert.assertEquals((long)tuple2.get(1), 1L); Assert.assertEquals((long)tuple2.get(2), 1L); Assert.assertEquals((long)tuple2.get(3), 1L); } @Test public void estimation() throws Exception { ItemsSketch<String> sketch = new ItemsSketch<>(8); sketch.update("1", 1000); sketch.update("2", 500); sketch.update("3", 200); sketch.update("4", 100); sketch.update("5", 50); sketch.update("6", 20); sketch.update("7", 10); sketch.update("8", 5); sketch.update("9", 2); sketch.update("10"); Tuple inputTuple = PigUtil.objectsToTuple(new DataByteArray(sketch.toByteArray(new ArrayOfStringsSerDe()))); EvalFunc<DataBag> func1 = new FrequentStringsSketchToEstimates("NO_FALSE_POSITIVES"); DataBag bag1 = func1.exec(inputTuple); Assert.assertNotNull(bag1); Assert.assertTrue(bag1.size() < 10); EvalFunc<DataBag> func2 = new FrequentStringsSketchToEstimates("NO_FALSE_NEGATIVES"); DataBag bag2 = func2.exec(inputTuple); Assert.assertNotNull(bag2); Assert.assertTrue(bag2.size() < 10); Assert.assertTrue(bag1.size() < bag2.size()); } @Test public void schema() throws Exception { EvalFunc<DataBag> func = new FrequentStringsSketchToEstimates(); Schema schema = func.outputSchema(null); Assert.assertNotNull(schema); Assert.assertEquals(schema.size(), 1); Assert.assertEquals(schema.getField(0).type, DataType.BAG); Assert.assertEquals(schema.getField(0).schema.size(), 1); Assert.assertEquals(schema.getField(0).schema.getField(0).type, DataType.TUPLE); Assert.assertEquals(schema.getField(0).schema.getField(0).schema.size(), 4); Assert.assertEquals(schema.getField(0).schema.getField(0).schema.getField(0).type, DataType.CHARARRAY); Assert.assertEquals(schema.getField(0).schema.getField(0).schema.getField(1).type, DataType.LONG); Assert.assertEquals(schema.getField(0).schema.getField(0).schema.getField(2).type, DataType.LONG); Assert.assertEquals(schema.getField(0).schema.getField(0).schema.getField(3).type, DataType.LONG); } }
5,726
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/kll/GetQuantileTest.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.pig.kll; import java.util.Arrays; import org.apache.datasketches.kll.KllFloatsSketch; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class GetQuantileTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void emptySketch() throws Exception { final EvalFunc<Float> func = new GetQuantile(); final KllFloatsSketch sketch = new KllFloatsSketch(); Float result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.0))); Assert.assertEquals((float)result, Float.NaN); } @Test public void normalCase() throws Exception { final EvalFunc<Float> func = new GetQuantile(); final KllFloatsSketch sketch = new KllFloatsSketch(); sketch.update(1); final Float result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.5))); Assert.assertEquals((float)result, 1f); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongNumberOfInputs() throws Exception { final EvalFunc<Float> func = new GetQuantile(); func.exec(TUPLE_FACTORY.newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { final EvalFunc<Float> func = new GetQuantile(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0, 1.0))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForFraction() throws Exception { final EvalFunc<Float> func = new GetQuantile(); final KllFloatsSketch sketch = new KllFloatsSketch(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 1))); } }
5,727
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/kll/GetKTest.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.pig.kll; import java.util.Arrays; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.apache.datasketches.kll.KllFloatsSketch; import org.testng.Assert; @SuppressWarnings("javadoc") public class GetKTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void defalutK() throws Exception { final EvalFunc<Integer> func = new GetK(); final KllFloatsSketch sketch = new KllFloatsSketch(); final Integer result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray())))); Assert.assertNotNull(result); Assert.assertEquals(result, Integer.valueOf(KllFloatsSketch.DEFAULT_K)); } @Test public void customK() throws Exception { final EvalFunc<Integer> func = new GetK(); final KllFloatsSketch sketch = new KllFloatsSketch(400); final Integer result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray())))); Assert.assertNotNull(result); Assert.assertEquals(result, Integer.valueOf(400)); } @Test(expectedExceptions = IllegalArgumentException.class) public void noInputs() throws Exception { final EvalFunc<Integer> func = new GetK(); func.exec(TUPLE_FACTORY.newTuple()); } @Test(expectedExceptions = IllegalArgumentException.class) public void tooManyInputs() throws Exception { final EvalFunc<Integer> func = new GetK(); func.exec(TUPLE_FACTORY.newTuple(2)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { final EvalFunc<Integer> func = new GetK(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0))); } }
5,728
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/kll/SketchToStringTest.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.pig.kll; import java.util.Arrays; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.apache.datasketches.kll.KllFloatsSketch; import org.testng.Assert; @SuppressWarnings("javadoc") public class SketchToStringTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void normalCase() throws Exception { final EvalFunc<String> func = new SketchToString(); final KllFloatsSketch sketch = new KllFloatsSketch(); final String result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray())))); Assert.assertNotNull(result); } @Test(expectedExceptions = IllegalArgumentException.class) public void noInputs() throws Exception { final EvalFunc<String> func = new SketchToString(); func.exec(TUPLE_FACTORY.newTuple()); } @Test(expectedExceptions = IllegalArgumentException.class) public void tooManyInputs() throws Exception { final EvalFunc<String> func = new SketchToString(); func.exec(TUPLE_FACTORY.newTuple(2)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { final EvalFunc<String> func = new SketchToString(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0))); } }
5,729
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/kll/UnionSketchTest.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.pig.kll; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.kll.KllFloatsSketch; @SuppressWarnings("javadoc") public class UnionSketchTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); private static final BagFactory BAG_FACTORY = BagFactory.getInstance(); @Test public void execNullInputTuple() throws Exception { final EvalFunc<DataByteArray> func = new UnionSketch(); final DataByteArray result = func.exec(null); final KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyInputTuple() throws Exception { final EvalFunc<DataByteArray> func = new UnionSketch(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple()); final KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyBag() throws Exception { final EvalFunc<DataByteArray> func = new UnionSketch(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); final KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void execNormalCase() throws Exception { final EvalFunc<DataByteArray> func = new UnionSketch(); final DataBag bag = BAG_FACTORY.newDefaultBag(); final KllFloatsSketch inputSketch = new KllFloatsSketch(); inputSketch.update(1); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(bag)); final KllFloatsSketch sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 1); } @Test public void accumulator() throws Exception { final Accumulator<DataByteArray> func = new UnionSketch(); // no input yet DataByteArray result = func.getValue(); KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // null input tuple func.accumulate(null); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty input tuple func.accumulate(TUPLE_FACTORY.newTuple()); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty bag func.accumulate(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // normal case final DataBag bag = BAG_FACTORY.newDefaultBag(); final KllFloatsSketch inputSketch = new KllFloatsSketch(); inputSketch.update(1); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); func.accumulate(TUPLE_FACTORY.newTuple(bag)); func.accumulate(TUPLE_FACTORY.newTuple(bag)); result = func.getValue(); sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); // cleanup func.cleanup(); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void accumulatorCustomK() throws Exception { final Accumulator<DataByteArray> func = new UnionSketch("400"); final KllFloatsSketch sketch = getSketch(func.getValue()); Assert.assertEquals(sketch.getK(), 400); } @Test public void algebraicInitial() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getInitial()) .getConstructor(String.class).newInstance("400"); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple()); final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertTrue(resultTuple.get(0) instanceof DataBag); Assert.assertEquals(((DataBag) resultTuple.get(0)).size(), 1); } @Test public void algebraicIntermediateNullInputTupleCustomK() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()) .getConstructor(String.class).newInstance("400"); final Tuple resultTuple = func.exec(null); final KllFloatsSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getK(), 400); } @Test public void algebraicIntermediateEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()).newInstance(); final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple()); final KllFloatsSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateNormalCase() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()).newInstance(); final DataBag bag = BAG_FACTORY.newDefaultBag(); { // this is to simulate an output from Initial final DataBag innerBag = BAG_FACTORY.newDefaultBag(); final KllFloatsSketch qs = new KllFloatsSketch(); qs.update(1); innerBag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray()))); bag.add(TUPLE_FACTORY.newTuple(innerBag)); } { // this is to simulate an output from a prior call of Intermediate final KllFloatsSketch qs = new KllFloatsSketch(); qs.update(2); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray()))); } final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); final KllFloatsSketch sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test(expectedExceptions = IllegalArgumentException.class) public void algebraicIntermediateWrongType() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()).newInstance(); final DataBag bag = BAG_FACTORY.newDefaultBag(); // this bag must have tuples with either bags or data byte arrays bag.add(TUPLE_FACTORY.newTuple(1.0)); func.exec(TUPLE_FACTORY.newTuple(bag)); } @Test public void algebraicFinalNullInputTupleCustomK() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()) .getConstructor(String.class).newInstance("400"); final DataByteArray result = func.exec(null); final KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getK(), 400); } @Test public void algebraicFinalEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()).newInstance(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple()); final KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicFinalNormalCase() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()).newInstance(); final DataBag bag = BAG_FACTORY.newDefaultBag(); { // this is to simulate an output from Initial final DataBag innerBag = BAG_FACTORY.newDefaultBag(); final KllFloatsSketch qs = new KllFloatsSketch(); qs.update(1); innerBag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray()))); bag.add(TUPLE_FACTORY.newTuple(innerBag)); } { // this is to simulate an output from a prior call of Intermediate final KllFloatsSketch qs = new KllFloatsSketch(); qs.update(2); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray()))); } final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(bag)); final KllFloatsSketch sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test(expectedExceptions = IllegalArgumentException.class) public void algebraicIntermediateFinalWrongType() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()).newInstance(); DataBag bag = BAG_FACTORY.newDefaultBag(); // this bag must have tuples with either bags or data byte arrays bag.add(TUPLE_FACTORY.newTuple(1.0)); func.exec(TUPLE_FACTORY.newTuple(bag)); } // end of tests private static KllFloatsSketch getSketch(final Tuple tuple) throws Exception { Assert.assertNotNull(tuple); Assert.assertEquals(tuple.size(), 1); final DataByteArray bytes = (DataByteArray) tuple.get(0); return getSketch(bytes); } private static KllFloatsSketch getSketch(final DataByteArray bytes) throws Exception { Assert.assertTrue(bytes.size() > 0); return KllFloatsSketch.heapify(Memory.wrap(bytes.get())); } }
5,730
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/kll/GetQuantilesTest.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.pig.kll; import java.util.Arrays; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.apache.datasketches.kll.KllFloatsSketch; import org.testng.Assert; @SuppressWarnings("javadoc") public class GetQuantilesTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void emptySketch() throws Exception { final EvalFunc<Tuple> func = new GetQuantiles(); final KllFloatsSketch sketch = new KllFloatsSketch(); final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.5))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertEquals(((float) resultTuple.get(0)), Float.NaN); } @Test(expectedExceptions = IllegalArgumentException.class) public void tooFewInputs() throws Exception { final EvalFunc<Tuple> func = new GetQuantiles(); func.exec(TUPLE_FACTORY.newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { final EvalFunc<Tuple> func = new GetQuantiles(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0, 1.0))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForFractionOrNumberOfIntervals() throws Exception { final EvalFunc<Tuple> func = new GetQuantiles(); final KllFloatsSketch sketch = new KllFloatsSketch(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), ""))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeAmongFractions() throws Exception { final EvalFunc<Tuple> func = new GetQuantiles(); final KllFloatsSketch sketch = new KllFloatsSketch(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.0, 1))); } @Test public void oneFraction() throws Exception { final EvalFunc<Tuple> func = new GetQuantiles(); final KllFloatsSketch sketch = new KllFloatsSketch(); for (int i = 1; i <= 10; i++) { sketch.update(i); } final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.5))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertEquals(((float) resultTuple.get(0)), 6f); } @Test public void severalFractions() throws Exception { final EvalFunc<Tuple> func = new GetQuantiles(); final KllFloatsSketch sketch = new KllFloatsSketch(); for (int i = 1; i <= 10; i++) { sketch.update(i); } final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.0, 0.5, 1.0))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals(((float) resultTuple.get(0)), 1f); Assert.assertEquals(((float) resultTuple.get(1)), 6f); Assert.assertEquals(((float) resultTuple.get(2)), 10f); } @Test public void numberOfEvenlySpacedIntervals() throws Exception { final EvalFunc<Tuple> func = new GetQuantiles(); final KllFloatsSketch sketch = new KllFloatsSketch(); for (int i = 1; i <= 10; i++) { sketch.update(i); } final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 3))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals(((float) resultTuple.get(0)), 1f); Assert.assertEquals(((float) resultTuple.get(1)), 6f); Assert.assertEquals(((float) resultTuple.get(2)), 10f); } }
5,731
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/kll/GetPmfTest.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.pig.kll; import java.util.Arrays; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.apache.datasketches.kll.KllFloatsSketch; import org.testng.Assert; @SuppressWarnings("javadoc") public class GetPmfTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void emptySketch() throws Exception { final EvalFunc<Tuple> func = new GetPmf(); final KllFloatsSketch sketch = new KllFloatsSketch(); final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0f))); Assert.assertNull(resultTuple); } @Test public void normalCase() throws Exception { final EvalFunc<Tuple> func = new GetPmf(); final KllFloatsSketch sketch = new KllFloatsSketch(); for (int i = 1; i <= 10; i++) { sketch.update(i); } final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 2f, 7f))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals(((double) resultTuple.get(0)), 0.1); Assert.assertEquals(((double) resultTuple.get(1)), 0.5); Assert.assertEquals(((double) resultTuple.get(2)), 0.4); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongNumberOfInputs() throws Exception { final EvalFunc<Tuple> func = new GetPmf(); func.exec(TUPLE_FACTORY.newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { final EvalFunc<Tuple> func = new GetPmf(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0, 1.0))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeOfSplitPoint() throws Exception { final EvalFunc<Tuple> func = new GetPmf(); final KllFloatsSketch sketch = new KllFloatsSketch(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 1))); } }
5,732
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/kll/DataToSketchTest.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.pig.kll; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.kll.KllFloatsSketch; @SuppressWarnings("javadoc") public class DataToSketchTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); private static final BagFactory BAG_FACTORY = BagFactory.getInstance(); @Test public void execNullInputTuple() throws Exception { final EvalFunc<DataByteArray> func = new DataToSketch(); final DataByteArray result = func.exec(null); final KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyInputTuple() throws Exception { final EvalFunc<DataByteArray> func = new DataToSketch(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple()); final KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyBag() throws Exception { final EvalFunc<DataByteArray> func = new DataToSketch(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); final KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test(expectedExceptions = ClassCastException.class) public void execWrongValueType() throws Exception { final EvalFunc<DataByteArray> func = new DataToSketch(); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple("a")); func.exec(TUPLE_FACTORY.newTuple(bag)); } @Test public void execNormalCase() throws Exception { final EvalFunc<DataByteArray> func = new DataToSketch(); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(Float.valueOf(1))); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(bag)); final KllFloatsSketch sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 1); } @Test public void execMixedNullCase() throws Exception { final EvalFunc<DataByteArray> func = new DataToSketch(); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(Float.valueOf(1))); bag.add(null); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(bag)); final KllFloatsSketch sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 1); } @Test public void accumulator() throws Exception { final Accumulator<DataByteArray> func = new DataToSketch(); // no input yet DataByteArray result = func.getValue(); KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // null input tuple func.accumulate(null); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty input tuple func.accumulate(TUPLE_FACTORY.newTuple()); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty bag func.accumulate(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // normal case DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(Float.valueOf(1))); func.accumulate(TUPLE_FACTORY.newTuple(bag)); func.accumulate(TUPLE_FACTORY.newTuple(bag)); result = func.getValue(); sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); // mixed null case bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(Float.valueOf(1))); bag.add(null); func.accumulate(TUPLE_FACTORY.newTuple(bag)); func.accumulate(TUPLE_FACTORY.newTuple(bag)); result = func.getValue(); sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 4); // cleanup func.cleanup(); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void accumulatorCustomK() throws Exception { final Accumulator<DataByteArray> func = new DataToSketch("400"); final KllFloatsSketch sketch = getSketch(func.getValue()); Assert.assertEquals(sketch.getK(), 400); } @Test public void algebraicInitial() throws Exception { final EvalFunc<Tuple> func = new DataToSketch.Initial(); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple()); final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertTrue(resultTuple.get(0) instanceof DataBag); Assert.assertEquals(((DataBag) resultTuple.get(0)).size(), 1); } @Test public void algebraicIntermediateNullInputTupleCustomK() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()) .getConstructor(String.class).newInstance("400"); final Tuple resultTuple = func.exec(null); final KllFloatsSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getK(), 400); } @Test public void algebraicIntermediateEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple()); final KllFloatsSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateNormalCase() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); final DataBag bag = BAG_FACTORY.newDefaultBag(); { // this is to simulate an output from Initial final DataBag innerBag = BAG_FACTORY.newDefaultBag(); innerBag.add(TUPLE_FACTORY.newTuple(Float.valueOf(1))); bag.add(TUPLE_FACTORY.newTuple(innerBag)); } { // this is to simulate an output from a prior call of IntermediateFinal final KllFloatsSketch qs = new KllFloatsSketch(); qs.update(2); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray()))); } final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); final KllFloatsSketch sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test public void algebraicIntermediateMixedNullCase() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); final DataBag bag = BAG_FACTORY.newDefaultBag(); { // this is to simulate an output from Initial final DataBag innerBag = BAG_FACTORY.newDefaultBag(); innerBag.add(TUPLE_FACTORY.newTuple(Float.valueOf(1))); innerBag.add(null); bag.add(TUPLE_FACTORY.newTuple(innerBag)); } { // this is to simulate an output from a prior call of IntermediateFinal final KllFloatsSketch qs = new KllFloatsSketch(); qs.update(2); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray()))); } final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); final KllFloatsSketch sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test(expectedExceptions = IllegalArgumentException.class) public void algebraicIntermediateWrongType() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); final DataBag bag = BAG_FACTORY.newDefaultBag(); // this bag must have tuples with either bags or data byte arrays bag.add(TUPLE_FACTORY.newTuple(1.0)); func.exec(TUPLE_FACTORY.newTuple(bag)); } @Test public void algebraicFinalNullInputTupleCustomK() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()) .getConstructor(String.class).newInstance("400"); final DataByteArray result = func.exec(null); final KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getK(), 400); } @Test public void algebraicFinalEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple()); final KllFloatsSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicFinalNormalCase() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); final DataBag bag = BAG_FACTORY.newDefaultBag(); { // this is to simulate an output from Initial final DataBag innerBag = BAG_FACTORY.newDefaultBag(); innerBag.add(TUPLE_FACTORY.newTuple(Float.valueOf(1))); bag.add(TUPLE_FACTORY.newTuple(innerBag)); } { // this is to simulate an output from a prior call of Intermediate final KllFloatsSketch qs = new KllFloatsSketch(); qs.update(2); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray()))); } final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(bag)); final KllFloatsSketch sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test public void algebraicFinalMixedNullCase() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); final DataBag bag = BAG_FACTORY.newDefaultBag(); { // this is to simulate an output from Initial final DataBag innerBag = BAG_FACTORY.newDefaultBag(); innerBag.add(TUPLE_FACTORY.newTuple(Float.valueOf(1))); innerBag.add(null); bag.add(TUPLE_FACTORY.newTuple(innerBag)); } { // this is to simulate an output from a prior call of Intermediate final KllFloatsSketch qs = new KllFloatsSketch(); qs.update(2); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray()))); } final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(bag)); final KllFloatsSketch sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test(expectedExceptions = IllegalArgumentException.class) public void algebraicFinalWrongType() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); final DataBag bag = BAG_FACTORY.newDefaultBag(); // this bag must have tuples with either bags or data byte arrays bag.add(TUPLE_FACTORY.newTuple(1.0)); func.exec(TUPLE_FACTORY.newTuple(bag)); } // end of tests private static KllFloatsSketch getSketch(final Tuple tuple) throws Exception { Assert.assertNotNull(tuple); Assert.assertEquals(tuple.size(), 1); final DataByteArray bytes = (DataByteArray) tuple.get(0); return getSketch(bytes); } private static KllFloatsSketch getSketch(final DataByteArray bytes) throws Exception { Assert.assertTrue(bytes.size() > 0); return KllFloatsSketch.heapify(Memory.wrap(bytes.get())); } }
5,733
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/kll/GetRankTest.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.pig.kll; import java.util.Arrays; import org.apache.datasketches.kll.KllFloatsSketch; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class GetRankTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void emptySketch() throws Exception { final EvalFunc<Double> func = new GetRank(); final KllFloatsSketch sketch = new KllFloatsSketch(); final Double result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0f))); Assert.assertEquals((double)result, Double.NaN); } @Test public void normalCase() throws Exception { final EvalFunc<Double> func = new GetRank(); final KllFloatsSketch sketch = new KllFloatsSketch(); sketch.update(1); sketch.update(2); sketch.update(3); sketch.update(4); final Double result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 3f))); Assert.assertEquals((double)result, 0.5); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongNumberOfInputs() throws Exception { final EvalFunc<Double> func = new GetRank(); func.exec(TUPLE_FACTORY.newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { final EvalFunc<Double> func = new GetRank(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0, 1.0))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForValue() throws Exception { final EvalFunc<Double> func = new GetRank(); final KllFloatsSketch sketch = new KllFloatsSketch(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 1))); } }
5,734
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/kll/GetCdfTest.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.pig.kll; import java.util.Arrays; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.apache.datasketches.kll.KllFloatsSketch; import org.testng.Assert; @SuppressWarnings("javadoc") public class GetCdfTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void emptySketch() throws Exception { final EvalFunc<Tuple> func = new GetCdf(); final KllFloatsSketch sketch = new KllFloatsSketch(); final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0f))); Assert.assertNull(resultTuple); } @Test public void normalCase() throws Exception { final EvalFunc<Tuple> func = new GetCdf(); final KllFloatsSketch sketch = new KllFloatsSketch(); for (int i = 1; i <= 10; i++) { sketch.update(i); } final Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 2f, 7f))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals((resultTuple.get(0)), 0.1); Assert.assertEquals((resultTuple.get(1)), 0.6); Assert.assertEquals((resultTuple.get(2)), 1.0); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongNumberOfInputs() throws Exception { final EvalFunc<Tuple> func = new GetCdf(); func.exec(TUPLE_FACTORY.newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { final EvalFunc<Tuple> func = new GetCdf(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0, 1.0))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeOfSplitPoint() throws Exception { final EvalFunc<Tuple> func = new GetCdf(); final KllFloatsSketch sketch = new KllFloatsSketch(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 1))); } }
5,735
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/sampling/VarOptUnionTest.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.pig.sampling; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import java.io.IOException; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.sampling.VarOptItemsSketch; import org.apache.datasketches.sampling.VarOptItemsUnion; @SuppressWarnings("javadoc") public class VarOptUnionTest { @SuppressWarnings("unused") @Test public void checkConstructors() { // these three should work VarOptUnion udf = new VarOptUnion(); assertNotNull(udf); udf = new VarOptUnion("255"); assertNotNull(udf); try { new VarOptUnion("-1"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } } @SuppressWarnings("unused") @Test public void checkExecution() { final int k = 5; final VarOptUnion udf = new VarOptUnion(Integer.toString(k)); final DataBag inputBag = BagFactory.getInstance().newDefaultBag(); final Tuple inputTuple = TupleFactory.getInstance().newTuple(1); try { final VarOptItemsSketch<Tuple> sketch = VarOptItemsSketch.newInstance(k); final VarOptItemsUnion<Tuple> union = VarOptItemsUnion.newInstance(k); for (int i = 1; i < (k / 2); ++i) { sketch.reset(); final Tuple t = TupleFactory.getInstance().newTuple(3); t.set(0, 1.0 * i); t.set(1, i); t.set(2, -i); sketch.update(t, 1.0 * i); // serialize sketch and wrap in Tuple, add to both bag and union final Tuple sketchWrapper = TupleFactory.getInstance().newTuple(1); final DataByteArray dba = new DataByteArray(sketch.toByteArray(new ArrayOfTuplesSerDe())); sketchWrapper.set(0, dba); inputBag.add(sketchWrapper); union.update(sketch); union.update(sketch); // calling accumulate() twice later } inputTuple.set(0, inputBag); assertNull(udf.getValue()); udf.accumulate(inputTuple); udf.accumulate(inputTuple); final DataByteArray outBytes = udf.getValue(); udf.cleanup(); assertNull(udf.getValue()); final VarOptItemsSketch<Tuple> result = VarOptItemsSketch.heapify(Memory.wrap(outBytes.get()), new ArrayOfTuplesSerDe()); assertNotNull(result); VarOptCommonAlgebraicTest.compareResults(result, union.getResult()); } catch (final IOException e) { fail("Unexpected exception"); } } @SuppressWarnings("unused") @Test public void degenerateExecInput() { final VarOptUnion udf = new VarOptUnion(); try { assertNull(udf.exec(null)); assertNull(udf.exec(TupleFactory.getInstance().newTuple(0))); final Tuple in = TupleFactory.getInstance().newTuple(1); in.set(0, null); assertNull(udf.exec(in)); } catch (final IOException e) { fail("Unexpected exception"); } } @Test public void outputSchemaTest() throws IOException { final VarOptUnion udf = new VarOptUnion("5"); final Schema inputSchema = new Schema(); inputSchema.add(new Schema.FieldSchema("bytes", DataType.BYTEARRAY)); final Schema output = udf.outputSchema(inputSchema); assertEquals(output.size(), 1); assertEquals(output.getField(0).type, DataType.BYTEARRAY); } }
5,736
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/sampling/GetVarOptSamplesTest.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.pig.sampling; import static org.apache.datasketches.pig.sampling.VarOptCommonImpl.RECORD_ALIAS; import static org.apache.datasketches.pig.sampling.VarOptCommonImpl.WEIGHT_ALIAS; import static org.apache.datasketches.pig.sampling.VarOptSamplingTest.EPS; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.IOException; import java.util.List; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.annotations.Test; import org.apache.datasketches.sampling.VarOptItemsSketch; @SuppressWarnings("javadoc") public class GetVarOptSamplesTest { private static final ArrayOfTuplesSerDe serDe_ = new ArrayOfTuplesSerDe(); @SuppressWarnings("unused") @Test public void checkDegenerateInput() { final GetVarOptSamples udf = new GetVarOptSamples(); try { assertNull(udf.exec(null)); assertNull(udf.exec(TupleFactory.getInstance().newTuple(0))); assertNull(udf.exec(TupleFactory.getInstance().newTuple((Object) null))); } catch (final IOException e) { fail("Unexpected IOException"); } } @Test public void checkExec() { final int k = 10; final int n = 25; // exact mode final GetVarOptSamples udf = new GetVarOptSamples(); try { final VarOptItemsSketch<Tuple> vis = VarOptItemsSketch.newInstance(k); double cumWt = 0.0; for (int i = 1; i <= n; ++i) { final Tuple t = TupleFactory.getInstance().newTuple(2); final double wt = 1.0 * i; t.set(0, wt); t.set(1, i); vis.update(t, wt); cumWt += wt; } final DataByteArray dba = new DataByteArray(vis.toByteArray(serDe_)); final Tuple inputTuple = TupleFactory.getInstance().newTuple(dba); final DataBag result = udf.exec(inputTuple); double cumResultWt = 0.0; for (Tuple sample : result) { cumResultWt += (double) sample.get(0); final Tuple record = (Tuple) sample.get(1); final int id = (int) record.get(1); assertTrue((id >= 1) && (id <= n)); } assertEquals(cumResultWt, cumWt, EPS); } catch (final IOException e) { fail("Unexpected IOException" + e.getMessage()); } } @Test public void validOutputSchemaTest() { final GetVarOptSamples udf = new GetVarOptSamples(); try { final Schema serializedSketch = new Schema(); serializedSketch.add(new Schema.FieldSchema("field1", DataType.BYTEARRAY)); final Schema output = udf.outputSchema(serializedSketch); assertEquals(output.size(), 1); assertEquals(output.getField(0).type, DataType.BAG); final List<Schema.FieldSchema> outputFields = output.getField(0).schema.getFields(); assertEquals(outputFields.size(), 2); // check high-level structure assertEquals(outputFields.get(0).alias, WEIGHT_ALIAS); assertEquals(outputFields.get(0).type, DataType.DOUBLE); assertEquals(outputFields.get(1).alias, RECORD_ALIAS); assertEquals(outputFields.get(1).type, DataType.TUPLE); } catch (final IOException e) { fail("Unexpected IOException: " + e.getMessage()); } } @SuppressWarnings("unused") @Test public void badOutputSchemaTest() { final GetVarOptSamples udf = new GetVarOptSamples(); try { udf.outputSchema(null); fail("Accepted null schema"); } catch (final IllegalArgumentException e) { // expected } try { udf.outputSchema(new Schema()); fail("Accepted empty schema"); } catch (final IllegalArgumentException e) { // expected } try { final Schema wrongSchema = new Schema(); wrongSchema.add(new Schema.FieldSchema("field", DataType.BOOLEAN)); udf.outputSchema(wrongSchema); fail("Accepted schema with no DataByteArray"); } catch (final IllegalArgumentException e) { // expected } } }
5,737
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/sampling/VarOptCommonAlgebraicTest.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.pig.sampling; 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.io.IOException; import java.util.HashMap; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.sampling.VarOptItemsSamples; import org.apache.datasketches.sampling.VarOptItemsSketch; import org.apache.datasketches.sampling.VarOptItemsUnion; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class VarOptCommonAlgebraicTest { private static final ArrayOfTuplesSerDe serDe_ = new ArrayOfTuplesSerDe(); // constructors: just make sure result not null with valid args, throw exceptions if invalid @SuppressWarnings("unused") @Test public void rawTuplesToSketchConstructors() { VarOptCommonImpl.RawTuplesToSketchTuple udf; udf = new VarOptCommonImpl.RawTuplesToSketchTuple(); assertNotNull(udf); udf = new VarOptCommonImpl.RawTuplesToSketchTuple("5"); assertNotNull(udf); udf = new VarOptCommonImpl.RawTuplesToSketchTuple("5", "3"); assertNotNull(udf); try { new VarOptCommonImpl.RawTuplesToSketchTuple("-1"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new VarOptCommonImpl.RawTuplesToSketchTuple("-1", "3"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new VarOptCommonImpl.RawTuplesToSketchTuple("10", "-1"); fail("Accepted negative weight index"); } catch (final IllegalArgumentException e) { // expected } } @SuppressWarnings("unused") @Test public void unionSketchesAsSketchConstructors() { VarOptCommonImpl.UnionSketchesAsTuple udf; udf = new VarOptCommonImpl.UnionSketchesAsTuple(); assertNotNull(udf); udf = new VarOptCommonImpl.UnionSketchesAsTuple("5"); assertNotNull(udf); udf = new VarOptCommonImpl.UnionSketchesAsTuple("5", "3"); assertNotNull(udf); try { new VarOptCommonImpl.UnionSketchesAsTuple("-1"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new VarOptCommonImpl.UnionSketchesAsTuple("-1", "3"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new VarOptCommonImpl.UnionSketchesAsTuple("10", "-1"); fail("Accepted negative weight index"); } catch (final IllegalArgumentException e) { // expected } } @SuppressWarnings("unused") @Test public void unionSketchesAsByteArrayConstructors() { VarOptCommonImpl.UnionSketchesAsByteArray udf; udf = new VarOptCommonImpl.UnionSketchesAsByteArray(); assertNotNull(udf); udf = new VarOptCommonImpl.UnionSketchesAsByteArray("5"); assertNotNull(udf); udf = new VarOptCommonImpl.UnionSketchesAsByteArray("5", "3"); assertNotNull(udf); try { new VarOptCommonImpl.UnionSketchesAsByteArray("-1"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new VarOptCommonImpl.UnionSketchesAsByteArray("-1", "3"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new VarOptCommonImpl.UnionSketchesAsByteArray("10", "-1"); fail("Accepted negative weight index"); } catch (final IllegalArgumentException e) { // expected } } // exec: sketches generally in sampling mode @SuppressWarnings("unused") @Test public void rawTuplesToSketchTupleExec() { final int k = 5; final int wtIdx = 1; final VarOptCommonImpl.RawTuplesToSketchTuple udf; udf = new VarOptCommonImpl.RawTuplesToSketchTuple(Integer.toString(k), Integer.toString(wtIdx)); char id = 'a'; double wt = 1.0; final DataBag inputBag = BagFactory.getInstance().newDefaultBag(); try { for (int i = 0; i < k + 1; ++i) { final Tuple t = TupleFactory.getInstance().newTuple(2); t.set(0, Character.toString(id)); t.set(1, wt); inputBag.add(t); ++id; wt += 1.0; } } catch (final ExecException e) { fail("Unexpected ExecException creating input data"); } try { // degenerate input first Tuple result = udf.exec(null); assertNull(result); Tuple inputTuple = TupleFactory.getInstance().newTuple(0); result = udf.exec(inputTuple); assertNull(result); inputTuple = TupleFactory.getInstance().newTuple(1); inputTuple.set(0, null); result = udf.exec(inputTuple); assertNull(result); // now test real input inputTuple.set(0, inputBag); result = udf.exec(inputTuple); assertEquals(result.size(), 1); final DataByteArray dba = (DataByteArray) result.get(0); final VarOptItemsSketch<Tuple> vis; vis = VarOptItemsSketch.heapify(Memory.wrap(dba.get()), serDe_); assertEquals(vis.getN(), k + 1); assertEquals(vis.getK(), k); // just validating the original weights are within the expected range for (VarOptItemsSamples<Tuple>.WeightedSample ws : vis.getSketchSamples()) { final Tuple t = ws.getItem(); assertTrue((double) t.get(wtIdx) >= 1.0); assertTrue((double) t.get(wtIdx) <= k + 1.0); } } catch (final IOException e) { fail("Unexpected IOException calling exec()"); } } @SuppressWarnings("unused") @Test public void unionSketchesDegenerateInput() { try { // Tuple version final VarOptCommonImpl.UnionSketchesAsTuple udfTuple; udfTuple = new VarOptCommonImpl.UnionSketchesAsTuple("4"); Tuple result = udfTuple.exec(null); assertNull(result); Tuple inputTuple = TupleFactory.getInstance().newTuple(0); result = udfTuple.exec(inputTuple); assertNull(result); inputTuple = TupleFactory.getInstance().newTuple(1); inputTuple.set(0, null); result = udfTuple.exec(inputTuple); assertNull(result); // DataByteArray version final VarOptCommonImpl.UnionSketchesAsByteArray udfBA; udfBA = new VarOptCommonImpl.UnionSketchesAsByteArray("4"); DataByteArray output = udfBA.exec(null); assertNull(output); inputTuple = TupleFactory.getInstance().newTuple(0); output = udfBA.exec(inputTuple); assertNull(output); inputTuple = TupleFactory.getInstance().newTuple(1); inputTuple.set(0, null); output = udfBA.exec(inputTuple); assertNull(output); } catch (final IOException e) { fail("Unexpected IOException calling exec()"); } } @SuppressWarnings("unused") @Test public void unionSketchesExec() { // Only difference between UnionSketchesAsTuple and UnionSketchesAsByteArray is that one wraps // the resulting serialized sketch in a tuple. If the union result is still in exact mode, the // two sketches should be identical. final int numSketches = 3; final int numItemsPerSketch = 10; // numSketches * numItemsPerSketch should be < k here final int k = 100; final String kStr = Integer.toString(k); final VarOptCommonImpl.UnionSketchesAsTuple udfTuple; final VarOptCommonImpl.UnionSketchesAsByteArray udfBA; udfTuple = new VarOptCommonImpl.UnionSketchesAsTuple(kStr); udfBA = new VarOptCommonImpl.UnionSketchesAsByteArray(kStr); char id = 'a'; double wt = 1.0; final DataBag inputBag = BagFactory.getInstance().newDefaultBag(); final VarOptItemsUnion<Tuple> union = VarOptItemsUnion.newInstance(k); final VarOptItemsSketch<Tuple> vis = VarOptItemsSketch.newInstance(k); // Create numSketches VarOpt sketches and serialize them. Also create a standard union to // compare against at the end. try { for (int j = 0; j < numSketches; ++j) { vis.reset(); for (int i = 0; i < numItemsPerSketch; ++i) { final Tuple t = TupleFactory.getInstance().newTuple(2); t.set(0, Character.toString(id)); t.set(1, wt); vis.update(t, wt); ++id; wt += 1.0; } final Tuple wrapper = TupleFactory.getInstance().newTuple(1); wrapper.set(0, new DataByteArray(vis.toByteArray(serDe_))); inputBag.add(wrapper); union.update(vis); } } catch (final ExecException e) { fail("Unexpected ExecException creating input data"); } try { final Tuple inputTuple = TupleFactory.getInstance().newTuple(1); inputTuple.set(0, inputBag); final DataByteArray outArray = udfBA.exec(inputTuple); final VarOptItemsSketch<Tuple> sketch1 = VarOptItemsSketch.heapify(Memory.wrap(outArray.get()), serDe_); final Tuple outTuple = udfTuple.exec(inputTuple); final DataByteArray dba = (DataByteArray) outTuple.get(0); final VarOptItemsSketch<Tuple> sketch2 = VarOptItemsSketch.heapify(Memory.wrap(dba.get()), serDe_); final VarOptItemsSketch<Tuple> expectedResult = union.getResult(); compareResults(sketch1, expectedResult); compareResults(sketch2, expectedResult); } catch (final IOException e) { fail("Unexpected IOException calling exec()"); } } // checks N, K, and ensures the same weights and items exist (order may differ) static void compareResults(final VarOptItemsSketch<Tuple> s1, final VarOptItemsSketch<Tuple> s2) { assertEquals(s1.getN(), s2.getN()); assertEquals(s1.getK(), s2.getK()); final HashMap<Tuple, Double> items = new HashMap<>(s1.getNumSamples()); for (VarOptItemsSamples<Tuple>.WeightedSample ws : s1.getSketchSamples()) { items.put(ws.getItem(), ws.getWeight()); } for (VarOptItemsSamples<Tuple>.WeightedSample ws : s2.getSketchSamples()) { assertEquals((double)items.get(ws.getItem()), ws.getWeight()); } } }
5,738
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/sampling/ReservoirUnionTest.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.pig.sampling; import static org.apache.datasketches.pig.sampling.ReservoirSampling.K_ALIAS; import static org.apache.datasketches.pig.sampling.ReservoirSampling.N_ALIAS; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.IOException; import java.util.List; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class ReservoirUnionTest { @SuppressWarnings("unused") @Test public void invalidMaxKTest() { try { new ReservoirUnion("1"); fail(); } catch (final IllegalArgumentException e) { // expected } } @SuppressWarnings("unused") @Test public void accumulateTest() { try { final long n = 20; final int k = 64; final Tuple reservoir1 = TupleFactory.getInstance().newTuple(3); reservoir1.set(0, n); reservoir1.set(1, k); reservoir1.set(2, ReservoirSamplingTest.generateDataBag(n, 0)); final Tuple reservoir2 = TupleFactory.getInstance().newTuple(3); reservoir2.set(0, n); reservoir2.set(1, k); reservoir2.set(2, ReservoirSamplingTest.generateDataBag(n, (int) n)); final Tuple reservoir3 = TupleFactory.getInstance().newTuple(3); reservoir3.set(0, n); reservoir3.set(1, k); reservoir3.set(2, ReservoirSamplingTest.generateDataBag(n, (int) (2 * n))); final DataBag bag1 = BagFactory.getInstance().newDefaultBag(); bag1.add(reservoir1); bag1.add(reservoir2); final Tuple input1 = TupleFactory.getInstance().newTuple(bag1); final DataBag bag2 = BagFactory.getInstance().newDefaultBag(); bag2.add(reservoir3); final Tuple input2 = TupleFactory.getInstance().newTuple(bag2); final ReservoirUnion ru = new ReservoirUnion(Integer.toString(k)); ru.accumulate(input1); ru.accumulate(input2); final Tuple result = ru.getValue(); // assuming k >= 3n so all items still in reservoir, in order assertEquals(result.size(), 3, "Unexpected tuple size from UDF"); assertEquals((long) result.get(0), 3 * n, "Incorrect total number of items seen"); assertEquals((int) result.get(1), k, "Unexpected value of k"); final DataBag outputSamples = (DataBag) result.get(2); assertEquals(outputSamples.size(), (long) result.get(0), "Output reservoir size does not match reported number of items"); int i = 0; for (Tuple t : outputSamples) { // expected format: (i:int, -i:chararray) assertEquals((int) t.get(0), i); assertEquals((String) t.get(1), Integer.toString(-i)); ++i; } ru.cleanup(); assertNull(ru.getValue()); } catch (final IOException e) { fail("Unexpected exception"); } } @SuppressWarnings("unused") @Test public void checkMaxKLimit() { try { final int k = 64; final int maxK = 32; final Tuple reservoir = TupleFactory.getInstance().newTuple(3); reservoir.set(0, (long) k); reservoir.set(1, k); reservoir.set(2, ReservoirSamplingTest.generateDataBag(k, 0)); final DataBag inputBag = BagFactory.getInstance().newDefaultBag(); inputBag.add(reservoir); final Tuple inputTuple = TupleFactory.getInstance().newTuple(inputBag); final ReservoirUnion ru = new ReservoirUnion(Integer.toString(maxK)); final Tuple result = ru.exec(inputTuple); assertEquals(result.size(), 3, "Unexpected tuple size from UDF"); assertEquals((long) result.get(0), k, "Incorrect total number of items seen"); assertEquals((int) result.get(1), maxK, "Unexpected value of k"); final DataBag outputSamples = (DataBag) result.get(2); assertEquals(outputSamples.size(), maxK, "Output reservoir size does not match maxK"); for (Tuple t : outputSamples) { // expected format: (i:int, -i:chararray) final int i = (int) t.get(0); assertTrue((i >= 0) && (i < k)); assertEquals((String) t.get(1), Integer.toString(-i)); } } catch (final IOException e) { fail("Unexpected exception"); } } @SuppressWarnings("unused") @Test public void checkDegenerateInput() { // using default max k value final ReservoirUnion ru = new ReservoirUnion(); Tuple inputTuple; try { // input == null assertNull(ru.exec(null)); // input.size() < 1 inputTuple = TupleFactory.getInstance().newTuple(0); assertNull(ru.exec(inputTuple)); // input.isNull(0); inputTuple = TupleFactory.getInstance().newTuple(1); inputTuple.set(0, null); assertNull(ru.exec(inputTuple)); } catch (final IOException e) { fail("Unexpected exception"); } try { // reservoir tuple with only 2 entries final Tuple reservoir = TupleFactory.getInstance().newTuple(2); reservoir.set(0, 256L); reservoir.set(1, 256); final DataBag reservoirBag = BagFactory.getInstance().newDefaultBag(); reservoirBag.add(reservoir); inputTuple = TupleFactory.getInstance().newTuple(reservoirBag); ru.exec(inputTuple); fail("Did not catch expected ExecException"); } catch (final ExecException e) { // expected } catch (final IOException e) { fail("Unexpected exception"); } } @Test public void outputSchemaTest() throws FrontendException { final ReservoirUnion ru = new ReservoirUnion("5"); final Schema tupleSchema = new Schema(); tupleSchema.add(new Schema.FieldSchema("field1", DataType.CHARARRAY)); tupleSchema.add(new Schema.FieldSchema("field2", DataType.INTEGER)); final Schema recordSchema = new Schema(); recordSchema.add(new Schema.FieldSchema("record", tupleSchema, DataType.TUPLE)); final Schema sketchSchema = new Schema(); sketchSchema.add(new Schema.FieldSchema(N_ALIAS, DataType.LONG)); sketchSchema.add(new Schema.FieldSchema(K_ALIAS, DataType.INTEGER)); // intentionally not using named constant to test pass-through sketchSchema.add(new Schema.FieldSchema("reservoir", recordSchema, DataType.BAG)); final Schema sketchBagSchema = new Schema(new Schema.FieldSchema("sketch", sketchSchema, DataType.TUPLE)); final Schema inputSchema = new Schema(new Schema.FieldSchema("sketchSet", sketchBagSchema, DataType.BAG)); final Schema output = ru.outputSchema(inputSchema); assertEquals(output.size(), 1); final List<Schema.FieldSchema> outputFields = output.getField(0).schema.getFields(); assertEquals(outputFields.size(), 3); // check high-level structure assertEquals(outputFields.get(0).alias, N_ALIAS); assertEquals(outputFields.get(0).type, DataType.LONG); assertEquals(outputFields.get(1).alias, K_ALIAS); assertEquals(outputFields.get(1).type, DataType.INTEGER); assertEquals(outputFields.get(2).alias, "reservoir"); // should pass through assertEquals(outputFields.get(2).type, DataType.BAG); // validate sample bag final Schema sampleSchema = outputFields.get(2).schema; assertTrue(recordSchema.equals(sampleSchema)); } @Test public void degenerateSchemaTest() throws FrontendException { final ReservoirUnion ru = new ReservoirUnion("5"); Schema output = ru.outputSchema(null); assertNull(output); output = ru.outputSchema(new Schema()); assertNull(output); final Schema tupleSchema = new Schema(); tupleSchema.add(new Schema.FieldSchema("field1", DataType.CHARARRAY)); tupleSchema.add(new Schema.FieldSchema("field2", DataType.INTEGER)); final Schema recordSchema = new Schema(); recordSchema.add(new Schema.FieldSchema("record", tupleSchema, DataType.TUPLE)); output = ru.outputSchema(new Schema()); assertNull(output); } }
5,739
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/sampling/DataToVarOptSketchTest.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.pig.sampling; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import java.io.IOException; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.sampling.VarOptItemsSketch; @SuppressWarnings("javadoc") public class DataToVarOptSketchTest { @Test @SuppressWarnings("unused") public void checkConstructors() { // these three should work DataToVarOptSketch udf = new DataToVarOptSketch(); assertNotNull(udf); udf = new DataToVarOptSketch("255"); assertNotNull(udf); udf = new DataToVarOptSketch("123", "0"); assertNotNull(udf); try { new DataToVarOptSketch("-1"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new DataToVarOptSketch("-1", "3"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new DataToVarOptSketch("10", "-1"); fail("Accepted weight index"); } catch (final IllegalArgumentException e) { // expected } } @SuppressWarnings("unused") @Test public void checkExecution() { final int k = 10; final DataToVarOptSketch udf = new DataToVarOptSketch(Integer.toString(k), "0"); final DataBag inputBag = BagFactory.getInstance().newDefaultBag(); final Tuple inputTuple = TupleFactory.getInstance().newTuple(1); // calling accumulate() twice, but keep in exact mode so reference sketch has same values try { final VarOptItemsSketch<Tuple> sketch = VarOptItemsSketch.newInstance(k); for (int i = 1; i < (k / 2); ++i) { final Tuple t = TupleFactory.getInstance().newTuple(3); t.set(0, 1.0 * i); t.set(1, i); t.set(2, -i); inputBag.add(t); sketch.update(t, 1.0 * i); sketch.update(t, 1.0 * i); // since calling accumulate() twice later } inputTuple.set(0, inputBag); assertNull(udf.getValue()); udf.accumulate(inputTuple); udf.accumulate(inputTuple); final DataByteArray outBytes = udf.getValue(); udf.cleanup(); assertNull(udf.getValue()); final VarOptItemsSketch<Tuple> result = VarOptItemsSketch.heapify(Memory.wrap(outBytes.get()), new ArrayOfTuplesSerDe()); assertNotNull(result); VarOptCommonAlgebraicTest.compareResults(result, sketch); } catch (final IOException e) { fail("Unexpected exception"); } } @SuppressWarnings("unused") @Test public void degenerateExecInput() { final DataToVarOptSketch udf = new DataToVarOptSketch(); try { assertNull(udf.exec(null)); assertNull(udf.exec(TupleFactory.getInstance().newTuple(0))); final Tuple in = TupleFactory.getInstance().newTuple(1); in.set(0, null); assertNull(udf.exec(in)); } catch (final IOException e) { fail("Unexpected exception"); } } @Test public void validOutputSchemaTest() throws IOException { DataToVarOptSketch udf = new DataToVarOptSketch("5", "1"); final Schema recordSchema = new Schema(); recordSchema.add(new Schema.FieldSchema("field1", DataType.CHARARRAY)); recordSchema.add(new Schema.FieldSchema("field2", DataType.DOUBLE)); recordSchema.add(new Schema.FieldSchema("field3", DataType.FLOAT)); final Schema tupleSchema = new Schema(); tupleSchema.add(new Schema.FieldSchema("record", recordSchema, DataType.TUPLE)); final Schema inputSchema = new Schema(); inputSchema.add(new Schema.FieldSchema("data", tupleSchema, DataType.BAG)); Schema output = udf.outputSchema(inputSchema); assertEquals(output.size(), 1); assertEquals(output.getField(0).type, DataType.BYTEARRAY); // use the float as a weight instead udf = new DataToVarOptSketch("5", "2"); output = udf.outputSchema(inputSchema); assertEquals(output.size(), 1); assertEquals(output.getField(0).type, DataType.BYTEARRAY); } @SuppressWarnings("unused") @Test public void badOutputSchemaTest() throws IOException { final Schema recordSchema = new Schema(); recordSchema.add(new Schema.FieldSchema("field1", DataType.CHARARRAY)); recordSchema.add(new Schema.FieldSchema("field2", DataType.DOUBLE)); recordSchema.add(new Schema.FieldSchema("field3", DataType.INTEGER)); final Schema tupleSchema = new Schema(); tupleSchema.add(new Schema.FieldSchema("record", recordSchema, DataType.TUPLE)); final Schema inputSchema = new Schema(); inputSchema.add(new Schema.FieldSchema("data", tupleSchema, DataType.BAG)); final DataToVarOptSketch udf = new DataToVarOptSketch("5", "0"); // degenerate input schemas try { udf.outputSchema(null); fail("Accepted null schema"); } catch (final IllegalArgumentException e) { // expected } try { udf.outputSchema(new Schema()); fail("Accepted empty schema"); } catch (final IllegalArgumentException e) { // expected } // expecting weight in element 0 (based on constructor arg) try { udf.outputSchema(inputSchema); fail("Accepted non-weight value in weightIndex column"); } catch (final IllegalArgumentException e) { // expected } // passing in Tuple instead of DataBag try { udf.outputSchema(tupleSchema); fail("Accepted Tuple instead of DataBag"); } catch (final IllegalArgumentException e) { // expected } } }
5,740
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/sampling/VarOptSamplingTest.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.pig.sampling; import static org.apache.datasketches.pig.sampling.VarOptCommonImpl.RECORD_ALIAS; import static org.apache.datasketches.pig.sampling.VarOptCommonImpl.WEIGHT_ALIAS; 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.io.IOException; import java.util.List; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.annotations.Test; import org.apache.datasketches.sampling.VarOptItemsSketch; @SuppressWarnings("javadoc") public class VarOptSamplingTest { static final double EPS = 1e-10; private static final ArrayOfTuplesSerDe serDe_ = new ArrayOfTuplesSerDe(); @SuppressWarnings("unused") @Test public void baseConstructors() { // these three should work VarOptSampling udf = new VarOptSampling(); assertNotNull(udf); udf = new VarOptSampling("255"); assertNotNull(udf); udf = new VarOptSampling("123", "0"); assertNotNull(udf); try { new VarOptSampling("-1"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new VarOptSampling("-1", "3"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new VarOptSampling("10", "-1"); fail("Accepted negative weight index"); } catch (final IllegalArgumentException e) { // expected } } @SuppressWarnings("unused") @Test public void algebraicFinalConstructors() { // these there should work VarOptSampling.Final udf = new VarOptSampling.Final(); assertNotNull(udf); udf = new VarOptSampling.Final("1024"); assertNotNull(udf); udf = new VarOptSampling.Final("4239", "2"); assertNotNull(udf); try { new VarOptSampling.Final("-1"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new VarOptSampling.Final("-1", "3"); fail("Accepted negative k"); } catch (final IllegalArgumentException e) { // expected } try { new VarOptSampling.Final("10", "-1"); fail("Accepted negative weight index"); } catch (final IllegalArgumentException e) { // expected } } @SuppressWarnings("unused") @Test public void standardAccumulate() { final int k = 10; final VarOptSampling udf = new VarOptSampling(Integer.toString(k), "0"); final DataBag inputBag = BagFactory.getInstance().newDefaultBag(); double cumWeight = 0.0; try { for (int i = 1; i < k; ++i) { final Tuple t = TupleFactory.getInstance().newTuple(3); t.set(0, 1.0 * i); t.set(1, i); t.set(2, -i); inputBag.add(t); cumWeight += i; } final Tuple inputTuple = TupleFactory.getInstance().newTuple(inputBag); assertNull(udf.getValue()); udf.accumulate(inputTuple); udf.accumulate(inputTuple); final DataBag result = udf.getValue(); udf.cleanup(); assertNull(udf.getValue()); assertNotNull(result); assertEquals(result.size(), k); double cumResultWeight = 0.0; for (Tuple weightAndtuple : result) { cumResultWeight += (double) weightAndtuple.get(0); final Tuple sample = (Tuple) weightAndtuple.get(1); assertEquals(sample.size(), 3); final int id = (int) sample.get(1); assertTrue((id > 0) && (id < k)); } assertEquals(cumResultWeight, 2 * cumWeight, EPS); // called accumulate() twice } catch (final IOException e) { fail("Unexpected exception"); } } @SuppressWarnings("unused") @Test public void degenerateExecInput() { final VarOptSampling udf = new VarOptSampling(); try { assertNull(udf.exec(null)); assertNull(udf.exec(TupleFactory.getInstance().newTuple(0))); final Tuple in = TupleFactory.getInstance().newTuple(1); in.set(0, null); assertNull(udf.exec(in)); } catch (final IOException e) { fail("Unexpected exception"); } } @SuppressWarnings("unused") @Test public void algebraicDegenerateInput() { try { // Tuple version final VarOptSampling.Final udf; udf = new VarOptSampling.Final("4"); DataBag result = udf.exec(null); assertNull(result); Tuple inputTuple = TupleFactory.getInstance().newTuple(0); result = udf.exec(inputTuple); assertNull(result); inputTuple = TupleFactory.getInstance().newTuple(1); inputTuple.set(0, null); result = udf.exec(inputTuple); assertNull(result); } catch (final IOException e) { fail("Unexpected IOException"); } } @SuppressWarnings("unused") @Test public void algebraicFinal() { final int k = 87; final int wtIdx = 2; final VarOptSampling.Final udf = new VarOptSampling.Final(Integer.toString(k),Integer.toString(wtIdx)); final DataBag inputBag = BagFactory.getInstance().newDefaultBag(); final VarOptItemsSketch<Tuple> vis = VarOptItemsSketch.newInstance(k); inputBag.add(TupleFactory.getInstance().newTuple(new DataByteArray(vis.toByteArray(serDe_)))); final Tuple inputTuple = TupleFactory.getInstance().newTuple(inputBag); try { final DataBag result = udf.exec(inputTuple); assertNotNull(result); assertEquals(result.size(), 0); } catch (final IOException e) { fail("Unexpected IOException"); } } @Test public void validOutputSchemaTest() throws IOException { VarOptSampling udf = new VarOptSampling("5", "1"); final Schema recordSchema = new Schema(); recordSchema.add(new Schema.FieldSchema("field1", DataType.CHARARRAY)); recordSchema.add(new Schema.FieldSchema("field2", DataType.DOUBLE)); recordSchema.add(new Schema.FieldSchema("field3", DataType.FLOAT)); final Schema tupleSchema = new Schema(); tupleSchema.add(new Schema.FieldSchema("record", recordSchema, DataType.TUPLE)); final Schema inputSchema = new Schema(); inputSchema.add(new Schema.FieldSchema("data", tupleSchema, DataType.BAG)); Schema output = udf.outputSchema(inputSchema); assertEquals(output.size(), 1); assertEquals(output.getField(0).type, DataType.BAG); final List<Schema.FieldSchema> outputFields = output.getField(0).schema.getFields(); assertEquals(outputFields.size(), 2); // check high-level structure assertEquals(outputFields.get(0).alias, WEIGHT_ALIAS); assertEquals(outputFields.get(0).type, DataType.DOUBLE); assertEquals(outputFields.get(1).alias, RECORD_ALIAS); assertEquals(outputFields.get(1).type, DataType.TUPLE); // validate sample bag final Schema sampleSchema = outputFields.get(1).schema; assertTrue(sampleSchema.equals(tupleSchema)); // use the float as a weight instead udf = new VarOptSampling("5", "2"); output = udf.outputSchema(inputSchema); assertEquals(output.size(), 1); assertEquals(output.getField(0).type, DataType.BAG); } @SuppressWarnings("unused") @Test public void badOutputSchemaTest() throws IOException { final Schema recordSchema = new Schema(); recordSchema.add(new Schema.FieldSchema("field1", DataType.CHARARRAY)); recordSchema.add(new Schema.FieldSchema("field2", DataType.DOUBLE)); recordSchema.add(new Schema.FieldSchema("field3", DataType.INTEGER)); final Schema tupleSchema = new Schema(); tupleSchema.add(new Schema.FieldSchema("record", recordSchema, DataType.TUPLE)); final Schema inputSchema = new Schema(); inputSchema.add(new Schema.FieldSchema("data", tupleSchema, DataType.BAG)); final VarOptSampling udf = new VarOptSampling("5", "0"); // degenerate input schemas try { udf.outputSchema(null); fail("Accepted null schema"); } catch (final IllegalArgumentException e) { // expected } try { udf.outputSchema(new Schema()); fail("Accepted empty schema"); } catch (final IllegalArgumentException e) { // expected } // expecting weight in element 0 (based on constructor args) try { udf.outputSchema(inputSchema); fail("Accepted non-weight in weightIndex column"); } catch (final IllegalArgumentException e) { // expected } // passing in Tuple instead of DataBag try { udf.outputSchema(tupleSchema); fail("Accepted input Tuple instead of DataBag"); } catch (final IllegalArgumentException e) { // expected } } }
5,741
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/sampling/ReservoirSamplingTest.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.pig.sampling; import static org.apache.datasketches.pig.sampling.ReservoirSampling.K_ALIAS; import static org.apache.datasketches.pig.sampling.ReservoirSampling.N_ALIAS; import static org.apache.datasketches.pig.sampling.ReservoirSampling.SAMPLES_ALIAS; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.IOException; import java.util.List; import org.apache.pig.EvalFunc; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class ReservoirSamplingTest { @SuppressWarnings("unused") @Test public void invalidKTest() { try { new ReservoirSampling("1"); fail(); } catch (final IllegalArgumentException e) { // expected } try { new ReservoirSampling.Initial("1"); fail(); } catch (final IllegalArgumentException e) { // expected } try { new ReservoirSampling.IntermediateFinal("1"); fail(); } catch (final IllegalArgumentException e) { // expected } } @Test public void accumulateTest() throws IOException { // exec() is automatically composed by calling accumulate(), getValue(), and cleanup(), in order // since AccumulateEvalFunc, but includes a fast-return route so still need to test separately final int k = 32; final long n = 24; final DataBag inputBag = BagFactory.getInstance().newDefaultBag(); final TupleFactory tf = TupleFactory.getInstance(); for (long i = 0; i < n; ++i) { final Tuple t = tf.newTuple(2); t.set(0, i); t.set(1, Long.toString(-i)); inputBag.add(t); } final Tuple input = tf.newTuple(inputBag); final ReservoirSampling rs = new ReservoirSampling(Integer.toString(k)); rs.accumulate(input); Tuple result = rs.getValue(); assertEquals(result.size(), 3, "Incorrect output size"); assertEquals(result.get(0), n, "Incorrect number of samples seen"); assertEquals(result.get(1), k, "Incorrect value of k"); assertEquals(((DataBag) result.get(2)).size(), n); // run the same input through again rs.accumulate(input); result = rs.getValue(); assertEquals(result.get(0), 2 * n, "Incorrect number of samples seen"); assertEquals(result.get(1), k, "Incorrect value of k"); // unchanged assertEquals(((DataBag) result.get(2)).size(), Math.min(k, 2 * n)); // clean up, degenerate accumulate, then get value again rs.cleanup(); rs.accumulate(null); assertNull(rs.getValue()); } @Test public void execTest() throws IOException { // copies tests for accumulate() since that handles both data paths final int k = 32; final long n = 24; final DataBag inputBag = BagFactory.getInstance().newDefaultBag(); final TupleFactory tf = TupleFactory.getInstance(); for (long i = 0; i < n; ++i) { final Tuple t = tf.newTuple(2); t.set(0, i); t.set(1, Long.toString(-i)); inputBag.add(t); } final Tuple input = tf.newTuple(inputBag); final ReservoirSampling rs = new ReservoirSampling(Integer.toString(k)); Tuple result = rs.exec(input); assertEquals(result.size(), 3, "Incorrect output size"); assertEquals(result.get(0), n, "Incorrect number of samples seen"); assertEquals(result.get(1), k, "Incorrect value of k"); assertEquals(((DataBag) result.get(2)).size(), n); // add another n to the bag and repeat for (long i = n; i < (2 * n); ++i) { final Tuple t = tf.newTuple(2); t.set(0, i); t.set(1, Long.toString(-i)); inputBag.add(t); } result = rs.exec(input); assertEquals(result.get(0), 2 * n, "Incorrect number of samples seen"); assertEquals(result.get(1), k, "Incorrect value of k"); // unchanged assertEquals(((DataBag) result.get(2)).size(), Math.min(k, 2 * n)); } @Test public void initialExec() throws IOException { final int k = 32; final long n1 = 16; final long n2 = 64; final ReservoirSampling.Initial rs = new ReservoirSampling.Initial(Integer.toString(k)); // 2 cases: n <= k and n > k final DataBag inputBag = BagFactory.getInstance().newDefaultBag(); final TupleFactory tf = TupleFactory.getInstance(); for (long i = 0; i < n1; ++i) { final Tuple t = tf.newTuple(2); t.set(0, i); t.set(1, Long.toString(-i)); inputBag.add(t); } final Tuple input = tf.newTuple(inputBag); Tuple result = rs.exec(input); assertEquals(result.size(), 3, "Incorrect output size"); assertEquals(result.get(0), n1, "Incorrect number of samples seen"); assertEquals(result.get(1), k, "Incorrect value of k"); assertEquals(((DataBag) result.get(2)).size(), n1); // add so bag has n2 values for (long i = n1; i < n2; ++i) { final Tuple t = tf.newTuple(2); t.set(0, i); t.set(1, Long.toString(-i)); inputBag.add(t); } // inputBag should already be part of input tuple result = rs.exec(input); assertEquals(result.size(), 3, "Incorrect output size"); assertEquals(result.get(0), n2, "Incorrect number of samples seen"); assertEquals(result.get(1), k, "Incorrect value of k"); assertEquals(((DataBag) result.get(2)).size(), k); } @Test public void intermediateFinalExec() throws IOException { final int maxK = 128; final EvalFunc<Tuple> rs = new ReservoirSampling.IntermediateFinal(Integer.toString(maxK)); // need at least 3 conditions: // 1. n <= k <= maxK // 2. n <= k, k > maxK // 3. n > k final DataBag bagOfReservoirs = BagFactory.getInstance().newDefaultBag(); Tuple t = TupleFactory.getInstance().newTuple(3); t.set(0, 32L); t.set(1, maxK); t.set(2, generateDataBag(32, 0)); bagOfReservoirs.add(t); t = TupleFactory.getInstance().newTuple(3); t.set(0, 64L); t.set(1, 256); t.set(2, generateDataBag(64, 32)); bagOfReservoirs.add(t); t = TupleFactory.getInstance().newTuple(3); t.set(0, 256L); t.set(1, maxK); t.set(2, generateDataBag(maxK, 96)); bagOfReservoirs.add(t); final Tuple input = TupleFactory.getInstance().newTuple(1); input.set(0, bagOfReservoirs); final Tuple result = rs.exec(input); final long tgtN = 32 + 64 + 256; final int tgtMaxVal = 32 + 64 + maxK; // only added maxK to last bag assertEquals(result.size(), 3, "Incorrect output size"); assertEquals(result.get(0), tgtN, "Incorrect number of samples seen"); assertEquals(result.get(1), maxK, "Incorrect value of k"); assertEquals(((DataBag) result.get(2)).size(), maxK); // check that they're all in the target range for (Tuple sample : ((DataBag) result.get(2))) { final int val = (int) sample.get(0); if ((val < 0) || (val >= tgtMaxVal)) { fail("Found value (" + val + ") outside target range [0, " + tgtMaxVal + "]"); } } } @Test public void outputSchemaTest() throws IOException { final ReservoirSampling rs = new ReservoirSampling("5"); final Schema recordSchema = new Schema(); recordSchema.add(new Schema.FieldSchema("field1", DataType.CHARARRAY)); recordSchema.add(new Schema.FieldSchema("field2", DataType.INTEGER)); final Schema tupleSchema = new Schema(); tupleSchema.add(new Schema.FieldSchema("record", recordSchema, DataType.TUPLE)); final Schema inputSchema = new Schema(); inputSchema.add(new Schema.FieldSchema("data", tupleSchema, DataType.BAG)); final Schema output = rs.outputSchema(inputSchema); assertEquals(output.size(), 1); final List<Schema.FieldSchema> outputFields = output.getField(0).schema.getFields(); assertEquals(outputFields.size(), 3); // check high-level structure assertEquals(outputFields.get(0).alias, N_ALIAS); assertEquals(outputFields.get(0).type, DataType.LONG); assertEquals(outputFields.get(1).alias, K_ALIAS); assertEquals(outputFields.get(1).type, DataType.INTEGER); assertEquals(outputFields.get(2).alias, SAMPLES_ALIAS); assertEquals(outputFields.get(2).type, DataType.BAG); // validate sample bag final Schema sampleSchema = outputFields.get(2).schema; assertTrue(sampleSchema.equals(tupleSchema)); } @Test public void degenerateAccumulateInput() { final ReservoirSampling rs = new ReservoirSampling("256"); // all these tests should do nothing try { rs.accumulate(null); Tuple input = TupleFactory.getInstance().newTuple(0); rs.accumulate(input); input = TupleFactory.getInstance().newTuple(1); input.set(0, null); rs.accumulate(input); } catch (final IOException e) { fail("Unexpected IOException: " + e.getMessage()); } } @Test public void degenerateExecInput() { final ReservoirSampling rs = new ReservoirSampling("256"); // all these tests should do nothing try { rs.exec(null); Tuple input = TupleFactory.getInstance().newTuple(0); rs.exec(input); input = TupleFactory.getInstance().newTuple(1); input.set(0, null); rs.exec(input); } catch (final IOException e) { fail("Unexpected IOException: " + e.getMessage()); } } @Test public void degenerateInitialInput() { try { final ReservoirSampling.Initial rs = new ReservoirSampling.Initial("256"); rs.exec(null); Tuple input = TupleFactory.getInstance().newTuple(0); rs.exec(input); input = TupleFactory.getInstance().newTuple(1); input.set(0, null); rs.exec(input); } catch (final IOException e) { fail("Unexpected IOException: " + e.getMessage()); } } @Test public void degenerateIntermediateFinalInput() { try { final EvalFunc<Tuple> rs = new ReservoirSampling.IntermediateFinal("256"); rs.exec(null); Tuple input = TupleFactory.getInstance().newTuple(0); rs.exec(input); input = TupleFactory.getInstance().newTuple(1); input.set(0, null); rs.exec(input); } catch (final IOException e) { fail("Unexpected IOException: " + e.getMessage()); } } @Test public void degenerateSchemaTest() { final ReservoirSampling rs = new ReservoirSampling("5"); Schema output = rs.outputSchema(null); assertNull(output); output = rs.outputSchema(new Schema()); assertNull(output); } static DataBag generateDataBag(final long numItems, final int startIdx) { final DataBag output = BagFactory.getInstance().newDefaultBag(); try { for (int i = 0; i < numItems; ++i) { final Tuple t = TupleFactory.getInstance().newTuple(2); final int val = startIdx + i; t.set(0, val); t.set(1, Integer.toString(-val)); output.add(t); } } catch (final ExecException e) { fail(e.getMessage()); } return output; } }
5,742
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/cpc/SketchToStringTest.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.pig.cpc; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.cpc.CpcSketch; @SuppressWarnings("javadoc") public class SketchToStringTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void nullInputTuple() throws Exception { final EvalFunc<String> func = new SketchToString(); final String result = func.exec(null); Assert.assertNull(result); } @Test public void emptyInputTuple() throws Exception { final EvalFunc<String> func = new SketchToString(); final String result = func.exec(TUPLE_FACTORY.newTuple()); Assert.assertNull(result); } @Test public void normalCase() throws Exception { final EvalFunc<String> func = new SketchToString(); final CpcSketch sketch = new CpcSketch(); final String result = func.exec(TUPLE_FACTORY.newTuple(new DataByteArray(sketch.toByteArray()))); Assert.assertNotNull(result); Assert.assertTrue(result.length() > 0); } @Test public void normalCaseWithDetail() throws Exception { final EvalFunc<String> func = new SketchToString("true"); final CpcSketch sketch = new CpcSketch(); final String result = func.exec(TUPLE_FACTORY.newTuple(new DataByteArray(sketch.toByteArray()))); Assert.assertNotNull(result); Assert.assertTrue(result.length() > 0); } @Test public void normalCaseWithDetailAndSeed() throws Exception { final EvalFunc<String> func = new SketchToString("true", "123"); final CpcSketch sketch = new CpcSketch(12, 123); final String result = func.exec(TUPLE_FACTORY.newTuple(new DataByteArray(sketch.toByteArray()))); Assert.assertNotNull(result); Assert.assertTrue(result.length() > 0); } }
5,743
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/cpc/GetEstimateTest.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.pig.cpc; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.cpc.CpcSketch; @SuppressWarnings("javadoc") public class GetEstimateTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void nullInputTuple() throws Exception { final EvalFunc<Double> func = new GetEstimate(); final Double result = func.exec(null); Assert.assertNull(result); } @Test public void emptyInputTuple() throws Exception { final EvalFunc<Double> func = new GetEstimate(); final Double result = func.exec(TUPLE_FACTORY.newTuple()); Assert.assertNull(result); } @Test public void normalCase() throws Exception { final EvalFunc<Double> func = new GetEstimate(); final CpcSketch sketch = new CpcSketch(); sketch.update(1); sketch.update(2); Double result = func.exec(TUPLE_FACTORY.newTuple(new DataByteArray(sketch.toByteArray()))); Assert.assertNotNull(result); Assert.assertEquals(result, 2.0, 0.01); } @Test public void normalCaseCustomSeed() throws Exception { final EvalFunc<Double> func = new GetEstimate("123"); final CpcSketch sketch = new CpcSketch(12, 123); sketch.update(1); sketch.update(2); Double result = func.exec(TUPLE_FACTORY.newTuple(new DataByteArray(sketch.toByteArray()))); Assert.assertNotNull(result); Assert.assertEquals(result, 2.0, 0.01); } }
5,744
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/cpc/UnionSketchTest.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.pig.cpc; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.cpc.CpcSketch; @SuppressWarnings("javadoc") public class UnionSketchTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); private static final BagFactory BAG_FACTORY = BagFactory.getInstance(); @Test public void execNullInputTuple() throws Exception { final EvalFunc<DataByteArray> func = new UnionSketch(); final DataByteArray result = func.exec(null); final CpcSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyInputTuple() throws Exception { final EvalFunc<DataByteArray> func = new UnionSketch(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple()); final CpcSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyBag() throws Exception { final EvalFunc<DataByteArray> func = new UnionSketch(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); final CpcSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void execNormalCase() throws Exception { final EvalFunc<DataByteArray> func = new UnionSketch(); final CpcSketch inputSketch = new CpcSketch(); inputSketch.update(1); inputSketch.update(2); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(bag)); final CpcSketch sketch = DataToSketchTest.getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); } @Test public void execNormalCaseCustomLgKAndSeed() throws Exception { final EvalFunc<DataByteArray> func = new UnionSketch("10", "123"); final CpcSketch inputSketch = new CpcSketch(10, 123); inputSketch.update(1); inputSketch.update(2); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(bag)); final CpcSketch sketch = DataToSketchTest.getSketch(result, 123); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); Assert.assertEquals(sketch.getLgK(), 10); } @Test public void accumulator() throws Exception { final Accumulator<DataByteArray> func = new UnionSketch(); // no input yet DataByteArray result = func.getValue(); CpcSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); // null input tuple func.accumulate(null); result = func.getValue(); sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty input tuple func.accumulate(TUPLE_FACTORY.newTuple()); result = func.getValue(); sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty bag func.accumulate(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); result = func.getValue(); sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); // normal case CpcSketch inputSketch = new CpcSketch(); inputSketch.update(1); inputSketch.update(2); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); func.accumulate(TUPLE_FACTORY.newTuple(bag)); result = func.getValue(); sketch = DataToSketchTest.getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); // cleanup func.cleanup(); result = func.getValue(); sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicInitial() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getInitial()).newInstance(); final Tuple input = TUPLE_FACTORY.newTuple(); final Tuple result = func.exec(input); Assert.assertEquals(result, input); } @Test public void algebraicIntermediateNullInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()).newInstance(); final Tuple result = func.exec(null); final CpcSketch sketch = DataToSketchTest.getSketch((DataByteArray) result.get(0)); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()).newInstance(); final Tuple result = func.exec(TUPLE_FACTORY.newTuple()); final CpcSketch sketch = DataToSketchTest.getSketch((DataByteArray) result.get(0)); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateFromInitial() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()).newInstance(); final CpcSketch inputSketch = new CpcSketch(); inputSketch.update(1); inputSketch.update(2); inputSketch.update(3); final DataBag outerBag = BAG_FACTORY.newDefaultBag(); final DataBag innerBag = BAG_FACTORY.newDefaultBag(); innerBag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); outerBag.add(TUPLE_FACTORY.newTuple(innerBag)); final Tuple result = func.exec(TUPLE_FACTORY.newTuple(outerBag)); final CpcSketch sketch = DataToSketchTest.getSketch((DataByteArray) result.get(0)); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 3.0, 0.01); } @Test public void algebraicIntermediateFromIntermediate() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()).newInstance(); final CpcSketch inputSketch = new CpcSketch(); inputSketch.update("a"); inputSketch.update("b"); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); final Tuple result = func.exec(TUPLE_FACTORY.newTuple(bag)); final CpcSketch sketch = DataToSketchTest.getSketch((DataByteArray) result.get(0)); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); } @Test public void algebraicIntermediateFromIntermediateCustomLgKAndSeed() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionSketch().getIntermed()) .getConstructor(String.class, String.class).newInstance("10", "123"); final CpcSketch inputSketch = new CpcSketch(10, 123); inputSketch.update("a"); inputSketch.update("b"); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); final Tuple result = func.exec(TUPLE_FACTORY.newTuple(bag)); final CpcSketch sketch = DataToSketchTest.getSketch((DataByteArray) result.get(0), 123); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); Assert.assertEquals(sketch.getLgK(), 10); } @Test public void algebraicFinalNullInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()).newInstance(); final DataByteArray result = func.exec(null); final CpcSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicFinalEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()).newInstance(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple()); final CpcSketch sketch = DataToSketchTest.getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicFinalFromInitial() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()).newInstance(); final CpcSketch inputSketch = new CpcSketch(); inputSketch.update(1); inputSketch.update(2); inputSketch.update(3); final DataBag outerBag = BAG_FACTORY.newDefaultBag(); final DataBag innerBag = BAG_FACTORY.newDefaultBag(); innerBag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); outerBag.add(TUPLE_FACTORY.newTuple(innerBag)); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(outerBag)); final CpcSketch sketch = DataToSketchTest.getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 3.0, 0.01); } @Test public void algebraicFinalFromInitialCustomLgKAndSeed() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()) .getConstructor(String.class, String.class).newInstance("10", "123"); final CpcSketch inputSketch = new CpcSketch(10,123); inputSketch.update(1); inputSketch.update(2); inputSketch.update(3); final DataBag outerBag = BAG_FACTORY.newDefaultBag(); final DataBag innerBag = BAG_FACTORY.newDefaultBag(); innerBag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); outerBag.add(TUPLE_FACTORY.newTuple(innerBag)); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(outerBag)); final CpcSketch sketch = DataToSketchTest.getSketch(result, 123); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 3.0, 0.01); Assert.assertEquals(sketch.getLgK(), 10); } @Test public void algebraicFinalFromIntermediate() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new UnionSketch().getFinal()).newInstance(); final CpcSketch inputSketch = new CpcSketch(); inputSketch.update("a"); inputSketch.update("b"); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(bag)); final CpcSketch sketch = DataToSketchTest.getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); } }
5,745
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/cpc/DataToSketchTest.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.pig.cpc; import static org.apache.datasketches.Util.DEFAULT_UPDATE_SEED; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.cpc.CpcSketch; @SuppressWarnings("javadoc") public class DataToSketchTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); private static final BagFactory BAG_FACTORY = BagFactory.getInstance(); @Test public void execNullInputTuple() throws Exception { final EvalFunc<DataByteArray> func = new DataToSketch(); final DataByteArray result = func.exec(null); final CpcSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyInputTupleCustomLgK() throws Exception { final EvalFunc<DataByteArray> func = new DataToSketch("10"); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple()); final CpcSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); Assert.assertEquals(sketch.getLgK(), 10); } @Test public void execEmptyBag() throws Exception { final EvalFunc<DataByteArray> func = new DataToSketch(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); final CpcSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test(expectedExceptions = IllegalArgumentException.class) public void execUnsupportedType() throws Exception { final EvalFunc<DataByteArray> func = new DataToSketch(); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(new Object())); func.exec(TUPLE_FACTORY.newTuple(bag)); } @Test public void execVariousTypesOfInput() throws Exception { final EvalFunc<DataByteArray> func = new DataToSketch(); final DataBag bag = BAG_FACTORY.newDefaultBag(); final Tuple tupleWithNull = TUPLE_FACTORY.newTuple(1); tupleWithNull.set(0, null); bag.add(tupleWithNull); bag.add(TUPLE_FACTORY.newTuple(Byte.valueOf((byte) 1))); bag.add(TUPLE_FACTORY.newTuple(Integer.valueOf(2))); bag.add(TUPLE_FACTORY.newTuple(Long.valueOf(3L))); bag.add(TUPLE_FACTORY.newTuple(Float.valueOf(1.0f))); bag.add(TUPLE_FACTORY.newTuple(Double.valueOf(2.0))); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(new byte[] {(byte) 1}))); bag.add(TUPLE_FACTORY.newTuple("a")); final CpcSketch sketch = getSketch(func.exec(TUPLE_FACTORY.newTuple(bag))); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 7.0, 0.01); } @Test public void accumulator() throws Exception { final Accumulator<DataByteArray> func = new DataToSketch(); // no input yet DataByteArray result = func.getValue(); CpcSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // null input tuple func.accumulate(null); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty input tuple func.accumulate(TUPLE_FACTORY.newTuple()); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // empty bag func.accumulate(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); // normal case final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple("a")); bag.add(TUPLE_FACTORY.newTuple("b")); func.accumulate(TUPLE_FACTORY.newTuple(bag)); result = func.getValue(); sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); // cleanup func.cleanup(); result = func.getValue(); sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicInitial() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getInitial()).newInstance(); final Tuple input = TUPLE_FACTORY.newTuple(); final Tuple result = func.exec(input); Assert.assertEquals(result, input); } @Test public void algebraicInitialWithLgK() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getInitial()) .getConstructor(String.class).newInstance("10"); final Tuple input = TUPLE_FACTORY.newTuple(); final Tuple result = func.exec(input); Assert.assertEquals(result, input); } @Test public void algebraicInitialWithLgKAndSeed() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getInitial()) .getConstructor(String.class, String.class).newInstance("10", "123"); final Tuple input = TUPLE_FACTORY.newTuple(); final Tuple result = func.exec(input); Assert.assertEquals(result, input); } @Test public void algebraicIntermediateNullInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); final Tuple result = func.exec(null); final CpcSketch sketch = getSketch((DataByteArray) result.get(0)); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); final Tuple result = func.exec(TUPLE_FACTORY.newTuple()); final CpcSketch sketch = getSketch((DataByteArray) result.get(0)); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateEmptyBag() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); Tuple result = func.exec(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); CpcSketch sketch = getSketch((DataByteArray) result.get(0)); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateFromInitial() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); final DataBag outerBag = BAG_FACTORY.newDefaultBag(); final DataBag innerBag = BAG_FACTORY.newDefaultBag(); innerBag.add(TUPLE_FACTORY.newTuple("a")); innerBag.add(TUPLE_FACTORY.newTuple("b")); innerBag.add(TUPLE_FACTORY.newTuple("c")); outerBag.add(TUPLE_FACTORY.newTuple(innerBag)); final Tuple result = func.exec(TUPLE_FACTORY.newTuple(outerBag)); final CpcSketch sketch = getSketch((DataByteArray) result.get(0)); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 3.0, 0.01); } @Test public void algebraicIntermediateFromIntermediate() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()).newInstance(); final CpcSketch inputSketch = new CpcSketch(); inputSketch.update("a"); inputSketch.update("b"); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); final Tuple result = func.exec(TUPLE_FACTORY.newTuple(bag)); final CpcSketch sketch = getSketch((DataByteArray) result.get(0)); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); } @Test public void algebraicIntermediateFromIntermediateCustomLgKAndSeed() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToSketch().getIntermed()) .getConstructor(String.class, String.class).newInstance("10", "123"); final CpcSketch inputSketch = new CpcSketch(10, 123); inputSketch.update("a"); final DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); final Tuple result = func.exec(TUPLE_FACTORY.newTuple(bag)); final CpcSketch sketch = getSketch((DataByteArray) result.get(0), 123); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 1.0, 0.01); Assert.assertEquals(sketch.getLgK(), 10); } @Test public void algebraicFinalNullInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); final DataByteArray result = func.exec(null); final CpcSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicFinalEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple()); final CpcSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicFinalEmptyBag() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); final CpcSketch sketch = getSketch(result); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicFinalFromInitial() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); final DataBag outerBag = BAG_FACTORY.newDefaultBag(); final DataBag innerBag = BAG_FACTORY.newDefaultBag(); innerBag.add(TUPLE_FACTORY.newTuple("a")); innerBag.add(TUPLE_FACTORY.newTuple("b")); innerBag.add(TUPLE_FACTORY.newTuple("c")); outerBag.add(TUPLE_FACTORY.newTuple(innerBag)); final DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(outerBag)); final CpcSketch sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 3.0, 0.01); } @Test public void algebraicFinalFromIntermediate() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()).newInstance(); final CpcSketch inputSketch = new CpcSketch(); inputSketch.update("a"); inputSketch.update("b"); DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(bag)); final CpcSketch sketch = getSketch(result); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); } @Test public void algebraicFinalFromIntermediateCustomLgKAndSeed() throws Exception { @SuppressWarnings("unchecked") final EvalFunc<DataByteArray> func = (EvalFunc<DataByteArray>) Class.forName(new DataToSketch().getFinal()) .getConstructor(String.class, String.class).newInstance("10", "123"); final CpcSketch inputSketch = new CpcSketch(10, 123); inputSketch.update("a"); inputSketch.update("b"); DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray()))); DataByteArray result = func.exec(TUPLE_FACTORY.newTuple(bag)); final CpcSketch sketch = getSketch(result, 123); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getEstimate(), 2.0, 0.01); Assert.assertEquals(sketch.getLgK(), 10); } static CpcSketch getSketch(final DataByteArray dba) throws Exception { return getSketch(dba, DEFAULT_UPDATE_SEED); } static CpcSketch getSketch(final DataByteArray dba, final long seed) throws Exception { Assert.assertNotNull(dba); Assert.assertTrue(dba.size() > 0); return CpcSketch.heapify(dba.get(), seed); } }
5,746
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/cpc/GetEstimateAndErrorBoundsTest.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.pig.cpc; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.cpc.CpcSketch; @SuppressWarnings("javadoc") public class GetEstimateAndErrorBoundsTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void nullInputTuple() throws Exception { final EvalFunc<Tuple> func = new GetEstimateAndErrorBounds(); final Tuple result = func.exec(null); Assert.assertNull(result); } @Test public void emptyInputTuple() throws Exception { final EvalFunc<Tuple> func = new GetEstimateAndErrorBounds(); final Tuple result = func.exec(TUPLE_FACTORY.newTuple()); Assert.assertNull(result); } @Test public void normalCase() throws Exception { final EvalFunc<Tuple> func = new GetEstimateAndErrorBounds(); final CpcSketch sketch = new CpcSketch(); sketch.update(1); sketch.update(2); Tuple result = func.exec(TUPLE_FACTORY.newTuple(new DataByteArray(sketch.toByteArray()))); Assert.assertNotNull(result); Assert.assertEquals((Double) result.get(0), 2.0, 0.01); Assert.assertTrue((Double) result.get(1) <= 2.0); Assert.assertTrue((Double) result.get(2) >= 2.0); } @Test public void normalCaseWithKappa() throws Exception { final EvalFunc<Tuple> func = new GetEstimateAndErrorBounds("1"); final CpcSketch sketch = new CpcSketch(); sketch.update(1); sketch.update(2); Tuple result = func.exec(TUPLE_FACTORY.newTuple(new DataByteArray(sketch.toByteArray()))); Assert.assertNotNull(result); Assert.assertEquals((Double) result.get(0), 2.0, 0.01); Assert.assertTrue((Double) result.get(1) <= 2.0); Assert.assertTrue((Double) result.get(2) >= 2.0); } @Test public void normalCaseWithKappaAndSeed() throws Exception { final EvalFunc<Tuple> func = new GetEstimateAndErrorBounds("3", "123"); final CpcSketch sketch = new CpcSketch(12, 123); sketch.update(1); sketch.update(2); Tuple result = func.exec(TUPLE_FACTORY.newTuple(new DataByteArray(sketch.toByteArray()))); Assert.assertNotNull(result); Assert.assertEquals((Double) result.get(0), 2.0, 0.01); Assert.assertTrue((Double) result.get(1) <= 2.0); Assert.assertTrue((Double) result.get(2) >= 2.0); } @Test public void schema() throws Exception { EvalFunc<Tuple> func = new GetEstimateAndErrorBounds(); Schema inputSchema = new Schema(new Schema.FieldSchema("Sketch", DataType.BYTEARRAY)); Schema outputSchema = func.outputSchema(inputSchema); Assert.assertNotNull(outputSchema); Assert.assertEquals(outputSchema.size(), 1); Assert.assertEquals(DataType.findTypeName(outputSchema.getField(0).type), "tuple"); Schema innerSchema = outputSchema.getField(0).schema; Assert.assertEquals(innerSchema.size(), 3); Assert.assertEquals(DataType.findTypeName(innerSchema.getField(0).type), "double"); Assert.assertEquals(DataType.findTypeName(innerSchema.getField(1).type), "double"); Assert.assertEquals(DataType.findTypeName(innerSchema.getField(2).type), "double"); } }
5,747
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/theta/EstimateTest.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.pig.theta; import static org.apache.datasketches.Util.DEFAULT_UPDATE_SEED; import static org.apache.datasketches.pig.PigTestingUtil.createDbaFromQssRange; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class EstimateTest { @Test public void testNullEmpty() throws IOException { EvalFunc<Double> func = new Estimate(); Tuple inputTuple = null; Double returnValue = func.exec(inputTuple); assertNull(returnValue); inputTuple = TupleFactory.getInstance().newTuple(0); returnValue = func.exec(inputTuple); assertNull(returnValue); } @Test public void testExact() throws IOException { EvalFunc<Double> func = new Estimate(); Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(64, 0, 64)); Double result = func.exec(dataTuple); assertNotNull(result); assertEquals(result, 64.0, 0.0); } @Test public void testExactWithSeed() throws IOException { EvalFunc<Double> func = new Estimate(Long.toString(DEFAULT_UPDATE_SEED)); Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(64, 0, 64)); Double result = func.exec(dataTuple); assertNotNull(result); assertEquals(result, 64.0, 0.0); } @Test public void printlnTest() { println(this.getClass().getSimpleName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
5,748
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/theta/UnionTest.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.pig.theta; import static org.apache.datasketches.pig.PigTestingUtil.LS; import static org.apache.datasketches.pig.PigTestingUtil.createDbaFromQssRange; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.io.IOException; import org.apache.datasketches.SketchesArgumentException; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class UnionTest { // private String udfName = "org.apache.datasketches.pig.theta.SketchUnions"; // private long seed_ = Util.DEFAULT_UPDATE_SEED; @Test(expectedExceptions = SketchesArgumentException.class) public void checkConstructorExceptions1() { Union test = new Union("1023"); assertNotNull(test); } @Test(expectedExceptions = IllegalArgumentException.class) public void checkConstructorExceptions3() { Union test = new Union("8"); assertNotNull(test); } @Test(expectedExceptions = SketchesArgumentException.class) public void testConstructorExceptions4() { Union test = new Union("1024", "2.0"); assertNotNull(test); } @Test(expectedExceptions = IllegalArgumentException.class) public void checkNotDBAExcep() throws IOException { Union inter = new Union(); //create inputTuple and a bag, add bag to inputTuple Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); inter.accumulate(inputTuple); //add empty tuple innerTuple.set(0, new Double(1.0)); //not a DBA inter = new Union(); inter.accumulate(inputTuple); //add wrong type } @SuppressWarnings("unused") @Test public void checkConstructors() { Union inter = new Union(); inter = new Union("1024"); inter = new Union("1024", "1.0"); inter = new Union("1024", "1.0", "9001"); inter = new Union(1024, (float) 1.0, 9001); Union.Initial initial = new Union.Initial(); initial = new Union.Initial("1024"); initial = new Union.Initial("1024", "1.0"); initial = new Union.Initial("1024", "1.0", "9001"); Union.IntermediateFinal interFin = new Union.IntermediateFinal(); interFin = new Union.IntermediateFinal("1024"); interFin = new Union.IntermediateFinal("1024", "1.0"); interFin = new Union.IntermediateFinal("1024", "1.0", "9001"); interFin = new Union.IntermediateFinal(1024, (float) 1.0, 9001); } @Test public void checkNullInput() throws IOException { EvalFunc<Tuple> unionFunc = new Union(); //default 4096 EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); //null bag Tuple resultTuple = unionFunc.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); Double est = estFunc.exec(resultTuple); assertEquals(est, 0.0, 0.0); } @Test public void checkExactTopExec() throws IOException { EvalFunc<Tuple> unionFunc = new Union(); //default 4096 EvalFunc<Double> estFunc = new Estimate(); //create inputTuple and a bag, add bag to inputTuple Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //create 4 distinct sketches of 64 in a bag for (int i = 0; i < 4; i++ ) { Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(64, i*64, 64)); bag.add(dataTuple); } Tuple resultTuple = unionFunc.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); Double est = estFunc.exec(resultTuple); assertEquals(est, 256.0, 0.0); } @Test(expectedExceptions = ClassCastException.class) public void checkBadClassCast() throws IOException { Accumulator<Tuple> unionFunc = new Union("256"); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); //valid size, but null inputTuple.set(0, new Double(1.0)); //wrong type. Cannot Union datums. unionFunc.accumulate(inputTuple); //throws ClassCastException } @Test public void checkNullEmptyAccumulator() throws IOException { Accumulator<Tuple> unionFunc = new Union("256"); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = null; unionFunc.accumulate(inputTuple); //does nothing, just returns inputTuple = TupleFactory.getInstance().newTuple(0); //invalid size unionFunc.accumulate(inputTuple); //does nothing, just returns inputTuple = TupleFactory.getInstance().newTuple(1); //valid size, but null unionFunc.accumulate(inputTuple); //does nothing, just returns inputTuple = TupleFactory.getInstance().newTuple(1); //valid size DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //correct type, but empty unionFunc.accumulate(inputTuple); //does nothing, just returns Tuple innerTuple = TupleFactory.getInstance().newTuple(0); //empty bag.add(innerTuple); unionFunc.accumulate(inputTuple); //does nothing, just returns inputTuple = TupleFactory.getInstance().newTuple(1); //valid size bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //correct type innerTuple = TupleFactory.getInstance().newTuple(1); //correct size bag.add(innerTuple); //but innerTuple(0) is null unionFunc.accumulate(inputTuple); //ignores Tuple resultTuple = unionFunc.getValue(); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); Double est = estFunc.exec(resultTuple); assertEquals(est, 0.0, 0.0); } @Test public void checkEmptyGetValue() throws IOException { Accumulator<Tuple> unionFunc = new Union("256"); EvalFunc<Double> estFunc = new Estimate(); Tuple resultTuple = unionFunc.getValue(); DataByteArray dba = (DataByteArray) resultTuple.get(0); assertEquals(dba.size(), 8); Double est = estFunc.exec(resultTuple); assertEquals(est, 0.0, 0.0); } @Test public void checkExactAccumulator() throws IOException { Accumulator<Tuple> unionFunc = new Union("256"); EvalFunc<Double> estFunc = new Estimate(); //create inputTuple and a bag, add bag to inputTuple Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //create 4 distinct sketches of 32 in a bag for (int i = 0; i < 4; i++ ) { Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(256, i*64, 64)); bag.add(dataTuple); } unionFunc.accumulate(inputTuple); //A tuple, bag with 4 sketches Tuple resultTuple = unionFunc.getValue(); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataByteArray dba = (DataByteArray) resultTuple.get(0); assertTrue(dba.size() > 0); Double est = estFunc.exec(resultTuple); assertEquals(est, 256.0, 0.0); unionFunc.cleanup(); resultTuple = unionFunc.getValue(); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); dba = (DataByteArray) resultTuple.get(0); assertTrue(dba.size() > 0); est = estFunc.exec(resultTuple); assertEquals(est, 0.0, 0.0); } @Test public void checkExactAlgebraicInitial() throws IOException { EvalFunc<Tuple> unionFuncInit = new Union.Initial("256"); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); for (int i = 0; i < 4; i++ ) { //4 sketches with one value each Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(16, i, 1)); bag.add(dataTuple); } Tuple resultTuple = unionFuncInit.exec(inputTuple); assertTrue(resultTuple == inputTuple); //returns the inputTuple } @Test public void checkAlgFinalFromPriorIntermed() throws IOException { EvalFunc<Tuple> unionFuncIFinal = new Union.IntermediateFinal("256"); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null for (int i = 0; i < 4; i++ ) { Tuple sketchTuple = TupleFactory.getInstance().newTuple(1); sketchTuple.set(0, createDbaFromQssRange(64, i*64, 64)); bag.add(sketchTuple); //inputTuple.bag0:sketchTuple0.DBA0 //inputTuple.bag0:sketchTuple1.DBA1 //inputTuple.bag0:sketchTuple2.DBA2 //inputTuple.bag0:sketchTuple3.DBA3 } Tuple resultTuple = unionFuncIFinal.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); assertTrue(bytes.size() > 0); Double est = estFunc.exec(resultTuple); assertEquals(est, 256.0, 0.0); } @Test public void checkAlgFinalFromPriorInitial() throws IOException { EvalFunc<Tuple> unionFuncFinal = new Union.IntermediateFinal("256"); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null Tuple innerTuple = TupleFactory.getInstance().newTuple(1); DataBag innerBag = BagFactory.getInstance().newDefaultBag(); innerTuple.set(0, innerBag); //innerTuple.innerBag0:null bag.add(innerTuple); //inputTuple.bag0.innerTuple0.innerBag0:null for (int i = 0; i < 4; i++ ) { Tuple sketchTuple = TupleFactory.getInstance().newTuple(1); sketchTuple.set(0, createDbaFromQssRange(64, i*64, 64)); innerBag.add(sketchTuple); //inputTuple.bag0.innerTuple0.innerBag0.sketchTuple0.DBA0 //inputTuple.bag0.innerTuple0.innerBag0.sketchTuple1.DBA1 //inputTuple.bag0.innerTuple0.innerBag0.sketchTuple2.DBA2 //inputTuple.bag0.innerTuple0.innerBag0.sketchTuple3.DBA3 } Tuple resultTuple = unionFuncFinal.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); assertTrue(bytes.size() > 0); Double est = estFunc.exec(resultTuple); assertEquals(est, 256.0, 0.0); } @Test public void checkAlgFinalOuterBagEmptyTuples() throws IOException { EvalFunc<Tuple> interFuncFinal = new Union.IntermediateFinal("256"); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); Tuple resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); } @Test public void checkAlgFinalInnerBagEmpty() throws IOException { EvalFunc<Tuple> interFuncFinal = new Union.IntermediateFinal("256"); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); Tuple resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); DataBag bag2 = BagFactory.getInstance().newDefaultBag(); innerTuple.set(0, bag2); resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); } @Test(expectedExceptions = IllegalArgumentException.class) public void checkAlgFinalInnerNotDBA() throws IOException { EvalFunc<Tuple> interFuncFinal = new Union.IntermediateFinal("256"); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); Tuple resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); innerTuple.set(0, new Double(1.0)); //not a DBA resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); } @Test public void outputSchemaTest() throws IOException { EvalFunc<Tuple> udf = new Union("512"); Schema inputSchema = null; Schema nullOutputSchema = null; Schema outputSchema = null; Schema.FieldSchema outputOuterFs0 = null; Schema outputInnerSchema = null; Schema.FieldSchema outputInnerFs0 = null; inputSchema = Schema.generateNestedSchema(DataType.BAG, DataType.BYTEARRAY); nullOutputSchema = udf.outputSchema(null); outputSchema = udf.outputSchema(inputSchema); outputOuterFs0 = outputSchema.getField(0); outputInnerSchema = outputOuterFs0.schema; outputInnerFs0 = outputInnerSchema.getField(0); Assert.assertNull(nullOutputSchema, "Should be null"); Assert.assertNotNull(outputOuterFs0, "outputSchema.getField(0) schema may not be null"); String expected = "tuple"; String result = DataType.findTypeName(outputOuterFs0.type); Assert.assertEquals(result, expected); expected = "bytearray"; Assert.assertNotNull(outputInnerFs0, "innerSchema.getField(0) schema may not be null"); result = DataType.findTypeName(outputInnerFs0.type); Assert.assertEquals(result, expected); //print schemas //@formatter:off StringBuilder sb = new StringBuilder(); sb.append("input schema: ").append(inputSchema).append(LS) .append("output schema: ").append(outputSchema).append(LS) .append("outputOuterFs: ").append(outputOuterFs0) .append(", type: ").append(DataType.findTypeName(outputOuterFs0.type)).append(LS) .append("outputInnerSchema: ").append(outputInnerSchema).append(LS) .append("outputInnerFs0: ").append(outputInnerFs0) .append(", type: ").append(DataType.findTypeName(outputInnerFs0.type)).append(LS); println(sb.toString()); //@formatter:on //end print schemas } @Test public void printlnTest() { println(this.getClass().getSimpleName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
5,749
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/theta/SketchToStringTest.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.pig.theta; import static org.apache.datasketches.Util.DEFAULT_UPDATE_SEED; import static org.apache.datasketches.pig.PigTestingUtil.createDbaFromQssRange; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class SketchToStringTest { @Test public void testNullEmpty() throws IOException { EvalFunc<String> func = new SketchToString("false"); Tuple dataTuple = null; String result = func.exec(dataTuple); assertNull(result); dataTuple = TupleFactory.getInstance().newTuple(0); result = func.exec(dataTuple); assertNull(result); } @Test public void testExactNoDetail() throws IOException { EvalFunc<String> func = new SketchToString("false"); Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(64, 0, 64)); String result = func.exec(dataTuple); assertNotNull(result); assertTrue(result.contains("SUMMARY")); assertFalse(result.contains("SKETCH DATA DETAIL")); } @Test public void testExactNoDetailWithSeed() throws IOException { EvalFunc<String> func = new SketchToString("false", Long.toString(DEFAULT_UPDATE_SEED)); Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(64, 0, 64)); String result = func.exec(dataTuple); assertNotNull(result); assertTrue(result.contains("SUMMARY")); assertFalse(result.contains("SKETCH DATA DETAIL")); } @Test public void testExactWithDetail() throws IOException { EvalFunc<String> func = new SketchToString("true"); Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(64, 0, 64)); String result = func.exec(dataTuple); assertNotNull(result); assertTrue(result.contains("SUMMARY")); assertTrue(result.contains("SKETCH DATA DETAIL")); } @Test public void printlnTest() { println(this.getClass().getSimpleName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
5,750
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/theta/JaccardSimilarityTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.datasketches.pig.theta; import static org.apache.datasketches.pig.PigTestingUtil.createDbaFromQssRange; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class JaccardSimilarityTest { @Test public void checkNullCombinations() throws IOException { EvalFunc<Tuple> jaccardFunc = new JaccardSimilarity(); Tuple inputTuple, resultTuple; //Two nulls inputTuple = TupleFactory.getInstance().newTuple(2); resultTuple = jaccardFunc.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 3); for (Object d : resultTuple.getAll()) { assertEquals(d, 0.0); } //A is null inputTuple = TupleFactory.getInstance().newTuple(2); inputTuple.set(1, createDbaFromQssRange(256, 0, 128)); resultTuple = jaccardFunc.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 3); for (Object d : resultTuple.getAll()) { assertEquals(d, 0.0); } //A is valid, B is null inputTuple = TupleFactory.getInstance().newTuple(2); inputTuple.set(0, createDbaFromQssRange(256, 0, 256)); resultTuple = jaccardFunc.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 3); for (Object d : resultTuple.getAll()) { assertEquals(d, 0.0); } //Both valid inputTuple = TupleFactory.getInstance().newTuple(2); inputTuple.set(0, createDbaFromQssRange(256, 0, 256)); inputTuple.set(1, createDbaFromQssRange(256, 0, 128)); resultTuple = jaccardFunc.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 3); assertEquals(resultTuple.get(0), 0.5); assertEquals(resultTuple.get(1), 0.5); assertEquals(resultTuple.get(2), 0.5); } }
5,751
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/theta/DataToSketchTest.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.pig.theta; import static org.apache.datasketches.pig.PigTestingUtil.LS; import static org.apache.datasketches.pig.PigTestingUtil.createDbaFromQssRange; import static org.apache.datasketches.pig.theta.PigUtil.tupleToSketch; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.io.IOException; import org.apache.datasketches.SketchesArgumentException; import org.apache.datasketches.Util; import org.apache.datasketches.theta.Sketch; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.FuncSpec; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.PigContext; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class DataToSketchTest { private String udfName = "org.apache.datasketches.pig.theta.DataToSketch"; private long seed_ = Util.DEFAULT_UPDATE_SEED; @Test(expectedExceptions = SketchesArgumentException.class) public void testConstructorExceptions1() { DataToSketch test = new DataToSketch("1023"); assertNotNull(test); } @Test(expectedExceptions = IllegalArgumentException.class) public void testConstructorExceptions3() { DataToSketch test = new DataToSketch("8"); assertNotNull(test); } @Test(expectedExceptions = SketchesArgumentException.class) public void testConstructorExceptions4() { DataToSketch test = new DataToSketch("1024", "2.0"); assertNotNull(test); } @Test public void checkNotDBAExcep() throws IOException { DataToSketch inter = new DataToSketch(); //create inputTuple and a bag, add bag to inputTuple Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); inter.accumulate(inputTuple); //add empty tuple innerTuple.set(0, new Double(1.0)); //not a DBA inter = new DataToSketch(); inter.accumulate(inputTuple); //add wrong type } @SuppressWarnings("unused") @Test public void checkConstructors() { DataToSketch inter = new DataToSketch(); inter = new DataToSketch("1024"); inter = new DataToSketch("1024", "1.0"); inter = new DataToSketch("1024", "1.0", "9001"); inter = new DataToSketch(1024, (float) 1.0, 9001); DataToSketch.Initial initial = new DataToSketch.Initial(); initial = new DataToSketch.Initial("1024"); initial = new DataToSketch.Initial("1024", "1.0"); initial = new DataToSketch.Initial("1024", "1.0", "9001"); DataToSketch.IntermediateFinal interFin = new DataToSketch.IntermediateFinal(); interFin = new DataToSketch.IntermediateFinal("1024"); interFin = new DataToSketch.IntermediateFinal("1024", "1.0"); interFin = new DataToSketch.IntermediateFinal("1024", "1.0", "9001"); interFin = new DataToSketch.IntermediateFinal(1024, (float) 1.0, 9001); } @Test public void testTopExec() throws IOException { EvalFunc<Tuple> func = new DataToSketch(); //empty constructor, size 4096 Tuple inputTuple = null; Tuple resultTuple = func.exec(inputTuple); Sketch sketch = tupleToSketch(resultTuple, this.seed_); assertTrue(sketch.isEmpty()); inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); for (int ii = 0; ii < 64; ii++ ) { Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, ii); bag.add(dataTuple); } resultTuple = func.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); assertTrue(bytes.size() > 0); sketch = tupleToSketch(resultTuple, this.seed_); assertEquals(sketch.getEstimate(), 64.0, 0.0); } /* * DataToSketch <br> * Tests all possible data types: NULL, BYTE, INTEGER, LONG, FLOAT, DOUBLE, * BYTEARRAY, CHARARRAY. Tests rejection of a non-simple type. */ @SuppressWarnings("unchecked") //still triggers unchecked warning @Test public void textTopExec2() throws IOException { TupleFactory tupleFactory = TupleFactory.getInstance(); BagFactory bagFactory = BagFactory.getInstance(); String[] ctorArgs = { "128" }; EvalFunc<Tuple> dataUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.udfName, ctorArgs)); // EvalFunc<Tuple> resultUdf = (EvalFunc<Tuple>)PigContext. // instantiateFuncFromSpec(new FuncSpec(resultUdfName)); Tuple t; DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple()); //empty with a null bag.add(tupleFactory.newTuple(1)); //1 empty field t = tupleFactory.newTuple(1); //1 t.set(0, new Byte((byte) 1)); bag.add(t); t = tupleFactory.newTuple(1); //2 t.set(0, new Integer(2)); //int bag.add(t); t = tupleFactory.newTuple(1); //3 t.set(0, new Long(3)); bag.add(t); t = tupleFactory.newTuple(1); //4 t.set(0, new Float(4)); bag.add(t); t = tupleFactory.newTuple(1); //5 t.set(0, new Double(5)); bag.add(t); t = tupleFactory.newTuple(1); //6 byte[] bArr = { 1, 2, 3 }; t.set(0, new DataByteArray(bArr)); bag.add(t); t = tupleFactory.newTuple(1); //-ignore byte[] bArr2 = new byte[0]; //empty t.set(0, new DataByteArray(bArr2)); bag.add(t); t = tupleFactory.newTuple(1); //7 t.set(0, new Double( -0.0)); bag.add(t); t = tupleFactory.newTuple(1); //7 duplicate t.set(0, new Double(0.0)); bag.add(t); t = tupleFactory.newTuple(1); //8 String s = "abcde"; t.set(0, s); bag.add(t); t = tupleFactory.newTuple(1); //- ignore String s2 = ""; //empty t.set(0, s2); bag.add(t); Tuple in = tupleFactory.newTuple(1); in.set(0, bag); //should return a sketch Tuple resultTuple = dataUdf.exec(in); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); assertTrue(bytes.size() > 0); Sketch sketch = tupleToSketch(resultTuple, this.seed_); assertEquals(sketch.getEstimate(), 8.0, 0.0); } @SuppressWarnings("unchecked") //still triggers unchecked warning @Test(expectedExceptions = IllegalArgumentException.class) public void testRejectionOfNonSimpleType() throws IOException { TupleFactory mTupleFactory = TupleFactory.getInstance(); BagFactory bagFactory = BagFactory.getInstance(); Tuple outerTuple = mTupleFactory.newTuple(1); DataBag outerBag = bagFactory.newDefaultBag(); Tuple innerTuple = mTupleFactory.newTuple(1); DataBag innerBag = bagFactory.newDefaultBag(); innerTuple.set(0, innerBag); outerBag.add(innerTuple); outerTuple.set(0, outerBag); String[] ctorArgs = { "128" }; EvalFunc<Tuple> dataUdf = (EvalFunc<Tuple>) PigContext.instantiateFuncFromSpec(new FuncSpec(this.udfName, ctorArgs)); dataUdf.exec(outerTuple); } @Test public void testAccumulate() throws IOException { Accumulator<Tuple> func = new DataToSketch("128"); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); for (int ii = 0; ii < 64; ii++ ) { Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, ii); bag.add(dataTuple); } func.accumulate(inputTuple); inputTuple = TupleFactory.getInstance().newTuple(1); bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); for (int ii = 0; ii < 27; ii++ ) { Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, 64 + ii); bag.add(dataTuple); } func.accumulate(inputTuple); Tuple resultTuple = func.getValue(); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); assertTrue(bytes.size() > 0); Sketch sketch = tupleToSketch(resultTuple, this.seed_); assertEquals(sketch.getEstimate(), 91.0, 0.0); // after cleanup, the value should always be 0 func.cleanup(); resultTuple = func.getValue(); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); bytes = (DataByteArray) resultTuple.get(0); assertTrue(bytes.size() > 0); sketch = tupleToSketch(resultTuple, this.seed_); assertEquals(sketch.getEstimate(), 0.0, 0.0); } @Test public void testInitial() throws IOException { EvalFunc<Tuple> func = new DataToSketch.Initial("128"); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); for (int ii = 0; ii < 64; ii++ ) { Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, ii); bag.add(dataTuple); } Tuple resultTuple = func.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataBag resultBag = (DataBag) resultTuple.get(0); assertEquals(resultBag.size(), 64); } @Test public void testIntermediateFinal() throws IOException { EvalFunc<Tuple> func = new DataToSketch.IntermediateFinal("128"); Tuple inputTuple = null; Tuple resultTuple = func.exec(inputTuple); Sketch sketch = tupleToSketch(resultTuple, this.seed_); assertTrue(sketch.isEmpty()); inputTuple = TupleFactory.getInstance().newTuple(0); resultTuple = func.exec(inputTuple); sketch = tupleToSketch(resultTuple, this.seed_); assertTrue(sketch.isEmpty()); inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); Tuple contentsTuple = TupleFactory.getInstance().newTuple(1); DataBag contentsBag = BagFactory.getInstance().newDefaultBag(); contentsTuple.set(0, contentsBag); for (int ii = 0; ii < 40; ii++ ) { Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, ii); contentsBag.add(dataTuple); } Tuple intermediateTuple = TupleFactory.getInstance().newTuple(1); intermediateTuple.set(0, createDbaFromQssRange(64, 40, 60)); bag.add(contentsTuple); bag.add(intermediateTuple); resultTuple = func.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); assertTrue(bytes.size() > 0); sketch = tupleToSketch(resultTuple, this.seed_); assertEquals(sketch.getEstimate(), 100.0, 0.0); } @Test public void checkAlgFinalOuterBagEmptyTuples() throws IOException { EvalFunc<Tuple> interFuncFinal = new DataToSketch.IntermediateFinal("256"); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); Tuple resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); } @Test public void checkAlgFinalInnerBagEmpty() throws IOException { EvalFunc<Tuple> interFuncFinal = new DataToSketch.IntermediateFinal("256"); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); Tuple resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); DataBag bag2 = BagFactory.getInstance().newDefaultBag(); innerTuple.set(0, bag2); resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); } @Test(expectedExceptions = IllegalArgumentException.class) public void checkAlgFinalInnerNotDBA() throws IOException { EvalFunc<Tuple> interFuncFinal = new DataToSketch.IntermediateFinal("256"); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); Tuple resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); innerTuple.set(0, new Double(1.0)); //not a DBA resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); } @Test public void outputSchemaTest() throws IOException { EvalFunc<Tuple> udf = new DataToSketch("512"); Schema inputSchema = null; Schema nullOutputSchema = null; Schema outputSchema = null; Schema outputInnerSchema = null; Schema.FieldSchema outputOuterFs0 = null; Schema.FieldSchema outputInnerFs0 = null; //CHARARRAY is one of several possible inner types inputSchema = Schema.generateNestedSchema(DataType.BAG, DataType.CHARARRAY); nullOutputSchema = udf.outputSchema(null); outputSchema = udf.outputSchema(inputSchema); outputOuterFs0 = outputSchema.getField(0); outputInnerSchema = outputOuterFs0.schema; outputInnerFs0 = outputInnerSchema.getField(0); Assert.assertNull(nullOutputSchema, "Should be null"); Assert.assertNotNull(outputOuterFs0, "outputSchema.getField(0) may not be null"); String expected = "tuple"; String result = DataType.findTypeName(outputOuterFs0.type); Assert.assertEquals(result, expected); expected = "bytearray"; Assert.assertNotNull(outputInnerFs0, "innerSchema.getField(0) may not be null"); result = DataType.findTypeName(outputInnerFs0.type); Assert.assertEquals(result, expected); //print schemas //@formatter:off StringBuilder sb = new StringBuilder(); sb.append("input schema: ").append(inputSchema).append(LS) .append("output schema: ").append(outputSchema).append(LS) .append("outputOuterFs: ").append(outputOuterFs0) .append(", type: ").append(DataType.findTypeName(outputOuterFs0.type)).append(LS) .append("outputInnerSchema: ").append(outputInnerSchema).append(LS) .append("outputInnerFs0: ").append(outputInnerFs0) .append(", type: ").append(DataType.findTypeName(outputInnerFs0.type)).append(LS); println(sb.toString()); //@formatter:on //end print schemas } @Test public void checkMisc() throws IOException { DataToSketch dts = new DataToSketch("512", "1.0"); dts = new DataToSketch("512", "1.0", "9001"); DataToSketch.Initial dtsi = new DataToSketch.Initial("512", "1.0"); DataToSketch.IntermediateFinal dtsif = new DataToSketch.IntermediateFinal("512", "1.0"); assertNotNull(dtsi); assertNotNull(dtsif); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); //null bag dts.accumulate(inputTuple); Tuple resultTuple = dts.getValue(); Sketch sketch = tupleToSketch(resultTuple, this.seed_); assertTrue(sketch.isEmpty()); } @Test public void checkSmall() throws IOException { EvalFunc<Tuple> func = new DataToSketch("32"); Tuple inputTuple = null; Tuple resultTuple = func.exec(inputTuple); Sketch sketch = tupleToSketch(resultTuple, this.seed_); assertTrue(sketch.isEmpty()); inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); int u = 32; for (int ii = 0; ii < u; ii++ ) { Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, ii); bag.add(dataTuple); } resultTuple = func.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); assertTrue(bytes.size() > 0); sketch = tupleToSketch(resultTuple, this.seed_); assertEquals(sketch.getEstimate(), u, 0.0); } @Test public void printlnTest() { println(this.getClass().getSimpleName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
5,752
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/theta/IntersectTest.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.pig.theta; import static org.apache.datasketches.pig.PigTestingUtil.LS; import static org.apache.datasketches.pig.PigTestingUtil.createDbaFromQssRange; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.io.IOException; import org.apache.datasketches.SketchesStateException; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class IntersectTest { @Test(expectedExceptions = IllegalStateException.class) public void checkGetValueExcep() { Intersect inter = new Intersect(); inter.getValue(); } @Test(expectedExceptions = IllegalArgumentException.class) public void checkNotDBAExcep() throws IOException { Intersect inter = new Intersect(); //create inputTuple and a bag, add bag to inputTuple Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); inter.accumulate(inputTuple); //add empty tuple innerTuple.set(0, new Double(1.0)); //not a DBA inter = new Intersect(); inter.accumulate(inputTuple); //add wrong type } @Test public void checkConstructors() { Intersect inter = new Intersect(); inter = new Intersect(9001); Intersect.Initial initial = new Intersect.Initial(); initial = new Intersect.Initial("9001"); Intersect.IntermediateFinal interFin = new Intersect.IntermediateFinal(); interFin = new Intersect.IntermediateFinal("9001"); interFin = new Intersect.IntermediateFinal(9001); assertNotNull(initial); assertNotNull(interFin); inter.cleanup(); } @Test public void checkNullInput() throws IOException { EvalFunc<Tuple> interFunc = new Intersect(); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); //null bag Tuple resultTuple = interFunc.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); Double est = estFunc.exec(resultTuple); assertEquals(est, 0.0, 0.0); } @Test public void checkExactTopExec() throws IOException { EvalFunc<Tuple> interFunc = new Intersect(); EvalFunc<Double> estFunc = new Estimate(); //create inputTuple and a bag, add bag to inputTuple Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //create 4 overlapping sketches of 64 in a bag for (int i = 0; i < 4; i++ ) { Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(256, i*64, 256)); bag.add(dataTuple); } Tuple resultTuple = interFunc.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); Double est = estFunc.exec(resultTuple); assertEquals(est, 64.0, 0.0); } @Test(expectedExceptions = ClassCastException.class) public void checkBadClassCast() throws IOException { Accumulator<Tuple> interFunc = new Intersect(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); //valid size, but null inputTuple.set(0, new Double(1.0)); //wrong type. Cannot intersect datums. interFunc.accumulate(inputTuple); //throws ClassCastException } @Test public void checkNullEmptyAccumulator() throws IOException { Accumulator<Tuple> interFunc = new Intersect(); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = null; interFunc.accumulate(inputTuple); //does nothing inputTuple = TupleFactory.getInstance().newTuple(0); //invalid size interFunc.accumulate(inputTuple); //does nothing inputTuple = TupleFactory.getInstance().newTuple(1); //valid size, but null bag interFunc.accumulate(inputTuple); //does nothing inputTuple = TupleFactory.getInstance().newTuple(1); //valid size DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //correct type, but empty interFunc.accumulate(inputTuple); //does nothing Tuple innerTuple = TupleFactory.getInstance().newTuple(0); //empty bag.add(innerTuple); interFunc.accumulate(inputTuple); //does nothing inputTuple = TupleFactory.getInstance().newTuple(1); //valid size bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //correct type innerTuple = TupleFactory.getInstance().newTuple(1); //correct size bag.add(innerTuple); //but innerTuple(0) is null interFunc.accumulate(inputTuple); //does nothing //Must call accumulate at least once before calling getValue. //To prove that all the above stuff truely did nothing, // we call accumulate once with a valid sketch and affirm that // getValue() returns it unaltered. //create inputTuple and a bag, add bag to inputTuple inputTuple = TupleFactory.getInstance().newTuple(1); //valid size bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(256, 0, 64)); bag.add(dataTuple); interFunc.accumulate(inputTuple); Tuple resultTuple = interFunc.getValue(); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); Double est = estFunc.exec(resultTuple); assertEquals(est, 64.0, 0.0); } @Test public void checkExactAccumulator() throws IOException { Accumulator<Tuple> interFunc = new Intersect(); EvalFunc<Double> estFunc = new Estimate(); //create inputTuple and a bag, add bag to inputTuple Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //create 4 distinct sketches of 32 in a bag for (int i = 0; i < 4; i++ ) { Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(256, i*64, 256)); bag.add(dataTuple); } interFunc.accumulate(inputTuple); //A tuple, bag with 4 sketches Tuple resultTuple = interFunc.getValue(); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataByteArray dba = (DataByteArray) resultTuple.get(0); assertTrue(dba.size() > 0); Double est = estFunc.exec(resultTuple); assertEquals(est, 64.0, 0.0); } @Test public void checkExactAlgebraicInitial() throws IOException { EvalFunc<Tuple> interFuncInit = new Intersect.Initial(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); for (int i = 0; i < 4; i++ ) { //4 sketches with one value each Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(16, i, 1)); bag.add(dataTuple); } Tuple resultTuple = interFuncInit.exec(inputTuple); assertTrue(resultTuple == inputTuple); //returns the inputTuple } @Test public void checkAlgFinalFromPriorIntermed() throws IOException { EvalFunc<Tuple> interFuncIFinal = new Intersect.IntermediateFinal(); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null for (int i = 0; i < 4; i++ ) { Tuple sketchTuple = TupleFactory.getInstance().newTuple(1); sketchTuple.set(0, createDbaFromQssRange(256, i*64, 256)); bag.add(sketchTuple); //inputTuple.bag0:sketchTuple0.DBA0 //inputTuple.bag0:sketchTuple1.DBA1 //inputTuple.bag0:sketchTuple2.DBA2 //inputTuple.bag0:sketchTuple3.DBA3 } Tuple resultTuple = interFuncIFinal.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); assertTrue(bytes.size() > 0); Double est = estFunc.exec(resultTuple); assertEquals(est, 64.0, 0.0); } @Test public void checkAlgFinalFromPriorInitial() throws IOException { EvalFunc<Tuple> interFuncFinal = new Intersect.IntermediateFinal(); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null Tuple innerTuple = TupleFactory.getInstance().newTuple(1); DataBag innerBag = BagFactory.getInstance().newDefaultBag(); innerTuple.set(0, innerBag); //innerTuple.innerBag0:null bag.add(innerTuple); //inputTuple.bag0.innerTuple0.innerBag0:null for (int i = 0; i < 4; i++ ) { Tuple sketchTuple = TupleFactory.getInstance().newTuple(1); sketchTuple.set(0, createDbaFromQssRange(256, i*64, 256)); innerBag.add(sketchTuple); //inputTuple.bag0.innerTuple0.innerBag0.sketchTuple0.DBA0 //inputTuple.bag0.innerTuple0.innerBag0.sketchTuple1.DBA1 //inputTuple.bag0.innerTuple0.innerBag0.sketchTuple2.DBA2 //inputTuple.bag0.innerTuple0.innerBag0.sketchTuple3.DBA3 } Tuple resultTuple = interFuncFinal.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); DataByteArray bytes = (DataByteArray) resultTuple.get(0); assertTrue(bytes.size() > 0); Double est = estFunc.exec(resultTuple); assertEquals(est, 64.0, 0.0); } @Test(expectedExceptions = SketchesStateException.class) public void checkAlgFinalOuterBagEmptyTuples() throws IOException { EvalFunc<Tuple> interFuncFinal = new Intersect.IntermediateFinal(); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); Tuple resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); resultTuple = interFuncFinal.exec(inputTuple); //Throws Illegal Result from HeapIntersection //assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); } @Test(expectedExceptions = SketchesStateException.class) public void checkAlgFinalInnerBagEmpty() throws IOException { EvalFunc<Tuple> interFuncFinal = new Intersect.IntermediateFinal(); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); Tuple resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); DataBag bag2 = BagFactory.getInstance().newDefaultBag(); innerTuple.set(0, bag2); resultTuple = interFuncFinal.exec(inputTuple); //Throws Illegal Result from HeapIntersection //assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); } @Test(expectedExceptions = IllegalArgumentException.class) public void checkAlgFinalInnerNotDBA() throws IOException { EvalFunc<Tuple> interFuncFinal = new Intersect.IntermediateFinal(); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple = TupleFactory.getInstance().newTuple(1); Tuple resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); DataBag bag = BagFactory.getInstance().newDefaultBag(); inputTuple.set(0, bag); //inputTuple.bag0:null resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); Tuple innerTuple = TupleFactory.getInstance().newTuple(1); bag.add(innerTuple); innerTuple.set(0, new Double(1.0)); //not a DBA resultTuple = interFuncFinal.exec(inputTuple); assertEquals(estFunc.exec(resultTuple), 0.0, 0.0); } @Test public void outputSchemaTest() throws IOException { EvalFunc<Tuple> udf = new Intersect(); Schema inputSchema = null; Schema nullOutputSchema = null; Schema outputSchema = null; Schema.FieldSchema outputOuterFs0 = null; Schema outputInnerSchema = null; Schema.FieldSchema outputInnerFs0 = null; inputSchema = Schema.generateNestedSchema(DataType.BAG, DataType.BYTEARRAY); nullOutputSchema = udf.outputSchema(null); outputSchema = udf.outputSchema(inputSchema); outputOuterFs0 = outputSchema.getField(0); outputInnerSchema = outputOuterFs0.schema; outputInnerFs0 = outputInnerSchema.getField(0); Assert.assertNull(nullOutputSchema, "Should be null"); Assert.assertNotNull(outputOuterFs0, "outputSchema.getField(0) schema may not be null"); String expected = "tuple"; String result = DataType.findTypeName(outputOuterFs0.type); Assert.assertEquals(result, expected); expected = "bytearray"; Assert.assertNotNull(outputInnerFs0, "innerSchema.getField(0) schema may not be null"); result = DataType.findTypeName(outputInnerFs0.type); Assert.assertEquals(result, expected); //print schemas //@formatter:off StringBuilder sb = new StringBuilder(); sb.append("input schema: ").append(inputSchema).append(LS) .append("output schema: ").append(outputSchema).append(LS) .append("outputOuterFs: ").append(outputOuterFs0) .append(", type: ").append(DataType.findTypeName(outputOuterFs0.type)).append(LS) .append("outputInnerSchema: ").append(outputInnerSchema).append(LS) .append("outputInnerFs0: ").append(outputInnerFs0) .append(", type: ").append(DataType.findTypeName(outputInnerFs0.type)).append(LS); println(sb.toString()); //@formatter:on //end print schemas } @Test public void printlnTest() { println(this.getClass().getSimpleName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
5,753
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/theta/ErrorBoundsTest.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.pig.theta; import static org.apache.datasketches.Util.DEFAULT_UPDATE_SEED; import static org.apache.datasketches.pig.PigTestingUtil.LS; import static org.apache.datasketches.pig.PigTestingUtil.createDbaFromAlphaRange; import static org.apache.datasketches.pig.PigTestingUtil.createDbaFromQssRange; 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 java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class ErrorBoundsTest { @Test public void testNullEmpty() throws IOException { EvalFunc<Tuple> func = new ErrorBounds(); Tuple dataTuple = null; Tuple result = func.exec(dataTuple); assertNull(result); dataTuple = TupleFactory.getInstance().newTuple(0); result = func.exec(dataTuple); assertNull(result); } @Test public void testExactModeBounds() throws IOException { EvalFunc<Tuple> func = new ErrorBounds(); int nomEntries = 128; Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromQssRange(nomEntries, 0, 64)); Tuple result = func.exec(dataTuple); assertNotNull(result); assertEquals(result.size(), 3); assertEquals(((Double) result.get(0)).doubleValue(), 64.0, 0.0); assertEquals(((Double) result.get(1)).doubleValue(), 64.0, 0.0); assertEquals(((Double) result.get(2)).doubleValue(), 64.0, 0.0); } @Test public void testEstModeBounds() throws IOException { EvalFunc<Tuple> func = new ErrorBounds(); int nomEntries = 4096; Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromAlphaRange(nomEntries, 0, 2*nomEntries)); Tuple result = func.exec(dataTuple); assertNotNull(result); assertEquals(result.size(), 3); double est = ((Double) result.get(0)).doubleValue(); double ub = ((Double) result.get(1)).doubleValue(); double lb = ((Double) result.get(2)).doubleValue(); //The error of the QS sketch for this size: double epsilon2SD = 2.0 / Math.sqrt(2 * nomEntries); //System.out.println(lb+"\t"+est+"\t"+ub); assertTrue(2 * nomEntries < ub && 2 * nomEntries > lb); assertTrue(Math.abs(ub / (est + epsilon2SD * est) - 1) < .01); assertTrue(Math.abs(lb / (est - epsilon2SD * est) - 1) < .01); } @Test public void testEstModeBoundsWithSeed() throws IOException { EvalFunc<Tuple> func = new ErrorBounds(Long.toString(DEFAULT_UPDATE_SEED)); int nomEntries = 4096; Tuple dataTuple = TupleFactory.getInstance().newTuple(1); dataTuple.set(0, createDbaFromAlphaRange(nomEntries, 0, 2*nomEntries)); Tuple result = func.exec(dataTuple); assertNotNull(result); assertEquals(result.size(), 3); double est = ((Double) result.get(0)).doubleValue(); double ub = ((Double) result.get(1)).doubleValue(); double lb = ((Double) result.get(2)).doubleValue(); //The error of the QS sketch for this size: double epsilon2SD = 2.0 / Math.sqrt(2 * nomEntries); //System.out.println(lb+"\t"+est+"\t"+ub); assertTrue(2 * nomEntries < ub && 2 * nomEntries > lb); assertTrue(Math.abs(ub / (est + epsilon2SD * est) - 1) < .01); assertTrue(Math.abs(lb / (est - epsilon2SD * est) - 1) < .01); } @Test public void outputSchemaTest() throws IOException { EvalFunc<Tuple> udf = new ErrorBounds(); Schema inputSchema = null; Schema.FieldSchema inputFieldSchema = new Schema.FieldSchema("Sketch", DataType.BYTEARRAY); Schema nullOutputSchema = null; Schema outputSchema = null; Schema.FieldSchema outputOuterFs0 = null; Schema outputInnerSchema = null; Schema.FieldSchema outputInnerFs0 = null; Schema.FieldSchema outputInnerFs1 = null; Schema.FieldSchema outputInnerFs2 = null; inputSchema = new Schema(inputFieldSchema); nullOutputSchema = udf.outputSchema(null); outputSchema = udf.outputSchema(inputSchema); outputOuterFs0 = outputSchema.getField(0); outputInnerSchema = outputOuterFs0.schema; outputInnerFs0 = outputInnerSchema.getField(0); outputInnerFs1 = outputInnerSchema.getField(1); outputInnerFs2 = outputInnerSchema.getField(2); Assert.assertNull(nullOutputSchema, "Should be null"); Assert.assertNotNull(outputOuterFs0, "outputSchema.getField(0) schema may not be null"); String expected = "tuple"; String result = DataType.findTypeName(outputOuterFs0.type); Assert.assertEquals(result, expected); expected = "double"; Assert.assertNotNull(outputInnerFs0, "innerSchema.getField(0) schema may not be null"); result = DataType.findTypeName(outputInnerFs0.type); Assert.assertEquals(result, expected); Assert.assertNotNull(outputInnerFs1, "innerSchema.getField(1) schema may not be null"); result = DataType.findTypeName(outputInnerFs1.type); Assert.assertEquals(result, expected); Assert.assertNotNull(outputInnerFs2, "innerSchema.getField(2) schema may not be null"); result = DataType.findTypeName(outputInnerFs2.type); Assert.assertEquals(result, expected); //print schemas //@formatter:off StringBuilder sb = new StringBuilder(); sb.append("input schema: ").append(inputSchema).append(LS) .append("output schema: ").append(outputSchema).append(LS) .append("outputOuterFs: ").append(outputOuterFs0) .append(", type: ").append(DataType.findTypeName(outputOuterFs0.type)).append(LS) .append("outputInnerSchema: ").append(outputInnerSchema).append(LS) .append("outputInnerFs0: ").append(outputInnerFs0) .append(", type: ").append(DataType.findTypeName(outputInnerFs0.type)).append(LS) .append("outputInnerFs1: ").append(outputInnerFs1) .append(", type: ").append(DataType.findTypeName(outputInnerFs1.type)).append(LS) .append("outputInnerFs2: ").append(outputInnerFs2) .append(", type: ").append(DataType.findTypeName(outputInnerFs2.type)).append(LS); println(sb.toString()); //@formatter:on //end print schemas } @Test public void printlnTest() { println(this.getClass().getSimpleName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
5,754
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/theta/PigUtilTest.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.pig.theta; import static org.apache.datasketches.pig.theta.PigUtil.compactOrderedSketchToTuple; import static org.apache.datasketches.pig.theta.PigUtil.extractTypeAtIndex; import static org.testng.Assert.assertNull; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.apache.datasketches.theta.CompactSketch; import org.apache.datasketches.theta.UpdateSketch; @SuppressWarnings("javadoc") public class PigUtilTest { @Test(expectedExceptions = IllegalArgumentException.class) public void checkCompOrdSketchToTuple() { UpdateSketch usk = UpdateSketch.builder().setNominalEntries(16).build(); for (int i=0; i<16; i++) { usk.update(i); } CompactSketch csk = usk.compact(false, null); compactOrderedSketchToTuple(csk); } @Test public void checkExtractTypeAtIndex() { Tuple tuple = TupleFactory.getInstance().newTuple(0); assertNull(extractTypeAtIndex(tuple, 0)); } @Test public void printlnTest() { println(this.getClass().getSimpleName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
5,755
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/theta/AexcludeBTest.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.pig.theta; import static org.apache.datasketches.pig.PigTestingUtil.LS; import static org.apache.datasketches.pig.PigTestingUtil.createDbaFromQssRange; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.fail; import java.io.IOException; import org.apache.datasketches.SketchesArgumentException; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class AexcludeBTest { @Test public void checkConstructors() { AexcludeB aNOTb = new AexcludeB(); aNOTb = new AexcludeB("9001"); aNOTb = new AexcludeB(9001); assertNotNull(aNOTb); } @SuppressWarnings("unused") @Test public void checkNullCombinations() throws IOException { EvalFunc<Tuple> aNbFunc = new AexcludeB(); EvalFunc<Double> estFunc = new Estimate(); Tuple inputTuple, resultTuple; Double est; //Two nulls inputTuple = TupleFactory.getInstance().newTuple(2); try { resultTuple = aNbFunc.exec(inputTuple); fail(); } catch (SketchesArgumentException e) {} //A is null inputTuple = TupleFactory.getInstance().newTuple(2); inputTuple.set(1, createDbaFromQssRange(256, 0, 128)); try { resultTuple = aNbFunc.exec(inputTuple); fail(); } catch (SketchesArgumentException e) {} //A is valid, B is null inputTuple = TupleFactory.getInstance().newTuple(2); inputTuple.set(0, createDbaFromQssRange(256, 0, 256)); try { resultTuple = aNbFunc.exec(inputTuple); fail(); } catch (SketchesArgumentException e) {} //Both valid inputTuple = TupleFactory.getInstance().newTuple(2); inputTuple.set(0, createDbaFromQssRange(256, 0, 256)); inputTuple.set(1, createDbaFromQssRange(256, 0, 128)); resultTuple = aNbFunc.exec(inputTuple); assertNotNull(resultTuple); assertEquals(resultTuple.size(), 1); est = estFunc.exec(resultTuple); assertEquals(est, 128.0, 0.0); } @Test public void outputSchemaTest() throws IOException { EvalFunc<Tuple> udf = new AexcludeB("512"); Schema inputSchema = null; Schema nullOutputSchema = null; Schema outputSchema = null; Schema.FieldSchema outputOuterFs0 = null; Schema outputInnerSchema = null; Schema.FieldSchema outputInnerFs0 = null; inputSchema = Schema.generateNestedSchema(DataType.BAG, DataType.BYTEARRAY); nullOutputSchema = udf.outputSchema(null); outputSchema = udf.outputSchema(inputSchema); outputOuterFs0 = outputSchema.getField(0); outputInnerSchema = outputOuterFs0.schema; outputInnerFs0 = outputInnerSchema.getField(0); Assert.assertNull(nullOutputSchema, "Should be null"); Assert.assertNotNull(outputOuterFs0, "outputSchema.getField(0) schema may not be null"); String expected = "tuple"; String result = DataType.findTypeName(outputOuterFs0.type); Assert.assertEquals(result, expected); expected = "bytearray"; Assert.assertNotNull(outputInnerFs0, "innerSchema.getField(0) schema may not be null"); result = DataType.findTypeName(outputInnerFs0.type); Assert.assertEquals(result, expected); //print schemas //@formatter:off StringBuilder sb = new StringBuilder(); sb.append("input schema: ").append(inputSchema).append(LS) .append("output schema: ").append(outputSchema).append(LS) .append("outputOuterFs: ").append(outputOuterFs0) .append(", type: ").append(DataType.findTypeName(outputOuterFs0.type)).append(LS) .append("outputInnerSchema: ").append(outputInnerSchema).append(LS) .append("outputInnerFs0: ").append(outputInnerFs0) .append(", type: ").append(DataType.findTypeName(outputInnerFs0.type)).append(LS); println(sb.toString()); //@formatter:on //end print schemas } @Test public void printlnTest() { println(this.getClass().getSimpleName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
5,756
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/GetPmfFromDoublesSketchTest.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.pig.quantiles; import org.apache.datasketches.quantiles.DoublesSketch; import org.apache.datasketches.quantiles.UpdateDoublesSketch; import java.util.Arrays; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.testng.Assert; @SuppressWarnings("javadoc") public class GetPmfFromDoublesSketchTest { private static final TupleFactory tupleFactory = TupleFactory.getInstance(); @Test public void emptySketch() throws Exception { EvalFunc<Tuple> func = new GetPmfFromDoublesSketch(); DoublesSketch sketch = DoublesSketch.builder().build(); Tuple resultTuple = func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.5))); Assert.assertNull(resultTuple); } @Test public void normalCase() throws Exception { EvalFunc<Tuple> func = new GetPmfFromDoublesSketch(); UpdateDoublesSketch sketch = DoublesSketch.builder().build(); for (int i = 1; i <= 10; i++) { sketch.update(i); } Tuple resultTuple = func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 2.0, 7.0))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals(((double) resultTuple.get(0)), 0.1); Assert.assertEquals(((double) resultTuple.get(1)), 0.5); Assert.assertEquals(((double) resultTuple.get(2)), 0.4); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongNumberOfInputs() throws Exception { EvalFunc<Tuple> func = new GetPmfFromDoublesSketch(); func.exec(tupleFactory.newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { EvalFunc<Tuple> func = new GetPmfFromDoublesSketch(); func.exec(tupleFactory.newTuple(Arrays.asList(1.0, 1.0))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeOfSplitPoint() throws Exception { EvalFunc<Tuple> func = new GetPmfFromDoublesSketch(); DoublesSketch sketch = DoublesSketch.builder().build(); func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 1))); } }
5,757
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/GetQuantilesFromDoublesSketchTest.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.pig.quantiles; import org.apache.datasketches.quantiles.DoublesSketch; import org.apache.datasketches.quantiles.UpdateDoublesSketch; import java.util.Arrays; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.testng.Assert; @SuppressWarnings("javadoc") public class GetQuantilesFromDoublesSketchTest { private static final TupleFactory tupleFactory = TupleFactory.getInstance(); @Test public void emptySketch() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromDoublesSketch(); DoublesSketch sketch = DoublesSketch.builder().build(); Tuple resultTuple = func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.5))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertEquals(((double) resultTuple.get(0)), Double.NaN); } @Test(expectedExceptions = IllegalArgumentException.class) public void tooFewInputs() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromDoublesSketch(); func.exec(tupleFactory.newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromDoublesSketch(); func.exec(tupleFactory.newTuple(Arrays.asList(1.0, 1.0))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForFractionOrNumberOfIntervals() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromDoublesSketch(); DoublesSketch sketch = DoublesSketch.builder().build(); func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), ""))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeAmongFractions() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromDoublesSketch(); DoublesSketch sketch = DoublesSketch.builder().build(); func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.0, 1))); } @Test public void oneFraction() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromDoublesSketch(); UpdateDoublesSketch sketch = DoublesSketch.builder().build(); for (int i = 1; i <= 10; i++) { sketch.update(i); } Tuple resultTuple = func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.5))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertEquals(((double) resultTuple.get(0)), 6.0); } @Test public void severalFractions() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromDoublesSketch(); UpdateDoublesSketch sketch = DoublesSketch.builder().build(); for (int i = 1; i <= 10; i++) { sketch.update(i); } Tuple resultTuple = func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.0, 0.5, 1.0))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals(((double) resultTuple.get(0)), 1.0); Assert.assertEquals(((double) resultTuple.get(1)), 6.0); Assert.assertEquals(((double) resultTuple.get(2)), 10.0); } @Test public void numberOfEvenlySpacedIntervals() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromDoublesSketch(); UpdateDoublesSketch sketch = DoublesSketch.builder().build(); for (int i = 1; i <= 10; i++) { sketch.update(i); } Tuple resultTuple = func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 3))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals(((double) resultTuple.get(0)), 1.0); Assert.assertEquals(((double) resultTuple.get(1)), 6.0); Assert.assertEquals(((double) resultTuple.get(2)), 10.0); } }
5,758
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/UnionStringsSketchTest.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.pig.quantiles; import java.util.Comparator; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.ArrayOfItemsSerDe; import org.apache.datasketches.ArrayOfStringsSerDe; import org.apache.datasketches.quantiles.ItemsSketch; @SuppressWarnings("javadoc") public class UnionStringsSketchTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); private static final BagFactory BAG_FACTORY = BagFactory.getInstance(); private static final Comparator<String> COMPARATOR = Comparator.naturalOrder(); private static final ArrayOfItemsSerDe<String> SER_DE = new ArrayOfStringsSerDe(); @Test public void execNullInputTuple() throws Exception { EvalFunc<Tuple> func = new UnionStringsSketch(); Tuple resultTuple = func.exec(null); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new UnionStringsSketch(); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple()); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyBag() throws Exception { EvalFunc<Tuple> func = new UnionStringsSketch(); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void execNormalCase() throws Exception { EvalFunc<Tuple> func = new UnionStringsSketch(); DataBag bag = BAG_FACTORY.newDefaultBag(); ItemsSketch<String> inputSketch = ItemsSketch.getInstance(COMPARATOR); inputSketch.update("a"); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray(SER_DE)))); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 1); } @Test public void accumulator() throws Exception { Accumulator<Tuple> func = new UnionStringsSketch(); // no input yet Tuple resultTuple = func.getValue(); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // null input tuple func.accumulate(null); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // empty input tuple func.accumulate(TUPLE_FACTORY.newTuple()); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // empty bag func.accumulate(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // normal case DataBag bag = BAG_FACTORY.newDefaultBag(); ItemsSketch<String> inputSketch = ItemsSketch.getInstance(COMPARATOR); inputSketch.update("a"); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(inputSketch.toByteArray(SER_DE)))); func.accumulate(TUPLE_FACTORY.newTuple(bag)); func.accumulate(TUPLE_FACTORY.newTuple(bag)); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); // cleanup func.cleanup(); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicInitial() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionStringsSketch().getInitial()).newInstance(); DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple()); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertTrue(resultTuple.get(0) instanceof DataBag); Assert.assertEquals(((DataBag) resultTuple.get(0)).size(), 1); } @Test public void algebraicIntermediateIsSameAsFinal() { Assert.assertEquals(new UnionStringsSketch().getIntermed(), new UnionStringsSketch().getFinal()); } @Test public void algebraicIntermediateFinalNullInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionStringsSketch().getIntermed()).newInstance(); Tuple resultTuple = func.exec(null); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateFinalEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionStringsSketch().getIntermed()).newInstance(); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple()); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateFinalNormalCase() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionStringsSketch().getIntermed()).newInstance(); DataBag bag = BAG_FACTORY.newDefaultBag(); { // this is to simulate an output from Initial DataBag innerBag = BAG_FACTORY.newDefaultBag(); ItemsSketch<String> qs = ItemsSketch.getInstance(COMPARATOR); qs.update("a"); innerBag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray(SER_DE)))); bag.add(TUPLE_FACTORY.newTuple(innerBag)); } { // this is to simulate an output from a prior call of IntermediateFinal ItemsSketch<String> qs = ItemsSketch.getInstance(COMPARATOR); qs.update("b"); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray(SER_DE)))); } Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test(expectedExceptions = IllegalArgumentException.class) public void algebraicIntermediateFinalWrongType() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new UnionStringsSketch().getIntermed()).newInstance(); DataBag bag = BAG_FACTORY.newDefaultBag(); // this bag must have tuples with either bags or data byte arrays bag.add(TUPLE_FACTORY.newTuple(1.0)); func.exec(TUPLE_FACTORY.newTuple(bag)); } @Test public void schema() throws Exception { EvalFunc<Tuple> func = new UnionStringsSketch(); Schema schema = func.outputSchema(new Schema()); Assert.assertNotNull(schema); Assert.assertEquals(schema.size(), 1); Assert.assertEquals(schema.getField(0).type, DataType.TUPLE); Assert.assertEquals(schema.getField(0).schema.size(), 1); Assert.assertEquals(schema.getField(0).schema.getField(0).type, DataType.BYTEARRAY); } // end of tests private static ItemsSketch<String> getSketch(Tuple tuple) throws Exception { Assert.assertNotNull(tuple); Assert.assertEquals(tuple.size(), 1); DataByteArray bytes = (DataByteArray) tuple.get(0); Assert.assertTrue(bytes.size() > 0); return ItemsSketch.getInstance(Memory.wrap(bytes.get()), COMPARATOR, SER_DE); } }
5,759
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/GetKFromDoublesSketchTest.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.pig.quantiles; import org.apache.datasketches.quantiles.DoublesSketch; import java.util.Arrays; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.testng.Assert; @SuppressWarnings("javadoc") public class GetKFromDoublesSketchTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void defalutK() throws Exception { EvalFunc<Integer> func = new GetKFromDoublesSketch(); DoublesSketch sketch = DoublesSketch.builder().build(); Integer result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray())))); Assert.assertNotNull(result); Assert.assertEquals(result, Integer.valueOf(128)); } @Test public void customK() throws Exception { EvalFunc<Integer> func = new GetKFromDoublesSketch(); DoublesSketch sketch = DoublesSketch.builder().setK(1024).build(); Integer result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray())))); Assert.assertNotNull(result); Assert.assertEquals(result, Integer.valueOf(1024)); } @Test(expectedExceptions = IllegalArgumentException.class) public void tooFewInputs() throws Exception { EvalFunc<Integer> func = new GetKFromDoublesSketch(); func.exec(TUPLE_FACTORY.newTuple()); } @Test(expectedExceptions = IllegalArgumentException.class) public void tooManyInputs() throws Exception { EvalFunc<Integer> func = new GetKFromDoublesSketch(); func.exec(TUPLE_FACTORY.newTuple(2)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { EvalFunc<Integer> func = new GetKFromDoublesSketch(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0))); } }
5,760
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/DataToDoublesSketchTest.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.pig.quantiles; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.quantiles.DoublesSketch; import org.apache.datasketches.quantiles.UpdateDoublesSketch; @SuppressWarnings("javadoc") public class DataToDoublesSketchTest { private static final TupleFactory tupleFactory = TupleFactory.getInstance(); private static final BagFactory bagFactory = BagFactory.getInstance(); @Test public void execNullInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch(); Tuple resultTuple = func.exec(null); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch(); Tuple resultTuple = func.exec(tupleFactory.newTuple()); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyBag() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch(); Tuple resultTuple = func.exec(tupleFactory.newTuple(bagFactory.newDefaultBag())); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test(expectedExceptions = ClassCastException.class) public void execWrongValueType() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch(); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple("a")); func.exec(tupleFactory.newTuple(bag)); } @Test public void execNormalCase() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch(); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple(1.0)); Tuple resultTuple = func.exec(tupleFactory.newTuple(bag)); DoublesSketch sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 1); } @Test public void execMixedNullCase() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch(); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple(1.0)); bag.add(null); Tuple resultTuple = func.exec(tupleFactory.newTuple(bag)); DoublesSketch sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 1); } @Test public void accumulator() throws Exception { Accumulator<Tuple> func = new DataToDoublesSketch(); // no input yet Tuple resultTuple = func.getValue(); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // null input tuple func.accumulate(null); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // empty input tuple func.accumulate(tupleFactory.newTuple()); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // empty bag func.accumulate(tupleFactory.newTuple(bagFactory.newDefaultBag())); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // normal case DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple(1.0)); func.accumulate(tupleFactory.newTuple(bag)); func.accumulate(tupleFactory.newTuple(bag)); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); // mixed null case bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple(1.0)); bag.add(null); func.accumulate(tupleFactory.newTuple(bag)); func.accumulate(tupleFactory.newTuple(bag)); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); // cleanup func.cleanup(); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicInitial() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch.Initial(); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple()); Tuple resultTuple = func.exec(tupleFactory.newTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertTrue(resultTuple.get(0) instanceof DataBag); Assert.assertEquals(((DataBag) resultTuple.get(0)).size(), 1); } @Test public void algebraicIntermediateFinalNullInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch.IntermediateFinal(); Tuple resultTuple = func.exec(null); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateFinalEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch.IntermediateFinal(); Tuple resultTuple = func.exec(tupleFactory.newTuple()); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateFinalNormalCase() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch.IntermediateFinal(); DataBag bag = bagFactory.newDefaultBag(); { // this is to simulate an output from Initial DataBag innerBag = bagFactory.newDefaultBag(); innerBag.add(tupleFactory.newTuple(1.0)); bag.add(tupleFactory.newTuple(innerBag)); } { // this is to simulate an output from a prior call of IntermediateFinal UpdateDoublesSketch qs = DoublesSketch.builder().build(); qs.update(2.0); bag.add(tupleFactory.newTuple(new DataByteArray(qs.toByteArray()))); } Tuple resultTuple = func.exec(tupleFactory.newTuple(bag)); DoublesSketch sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test public void algebraicIntermediateFinalMixedNullCase() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch.IntermediateFinal(); DataBag bag = bagFactory.newDefaultBag(); { // this is to simulate an output from Initial DataBag innerBag = bagFactory.newDefaultBag(); innerBag.add(tupleFactory.newTuple(1.0)); innerBag.add(null); bag.add(tupleFactory.newTuple(innerBag)); } { // this is to simulate an output from a prior call of IntermediateFinal UpdateDoublesSketch qs = DoublesSketch.builder().build(); qs.update(2.0); bag.add(tupleFactory.newTuple(new DataByteArray(qs.toByteArray()))); } Tuple resultTuple = func.exec(tupleFactory.newTuple(bag)); DoublesSketch sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test(expectedExceptions = IllegalArgumentException.class) public void algebraicIntermediateFinalWrongType() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch.IntermediateFinal(); DataBag bag = bagFactory.newDefaultBag(); // this bag must have tuples with either bags or data byte arrays bag.add(tupleFactory.newTuple(1.0)); func.exec(tupleFactory.newTuple(bag)); } @Test public void schema() throws Exception { EvalFunc<Tuple> func = new DataToDoublesSketch(); Schema schema = func.outputSchema(new Schema()); Assert.assertNotNull(schema); Assert.assertEquals(schema.size(), 1); Assert.assertEquals(schema.getField(0).type, DataType.TUPLE); Assert.assertEquals(schema.getField(0).schema.size(), 1); Assert.assertEquals(schema.getField(0).schema.getField(0).type, DataType.BYTEARRAY); } // end of tests private static DoublesSketch getSketch(Tuple tuple) throws Exception { Assert.assertNotNull(tuple); Assert.assertEquals(tuple.size(), 1); DataByteArray bytes = (DataByteArray) tuple.get(0); Assert.assertTrue(bytes.size() > 0); return DoublesSketch.heapify(Memory.wrap(bytes.get())); } }
5,761
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/GetQuantileFromDoublesSketchTest.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.pig.quantiles; import java.util.Arrays; import org.apache.datasketches.quantiles.DoublesSketch; import org.apache.datasketches.quantiles.UpdateDoublesSketch; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.Assert; import org.testng.annotations.Test; @SuppressWarnings("javadoc") public class GetQuantileFromDoublesSketchTest { private static final TupleFactory tupleFactory = TupleFactory.getInstance(); @Test public void emptySketch() throws Exception { EvalFunc<Double> func = new GetQuantileFromDoublesSketch(); DoublesSketch sketch = DoublesSketch.builder().build(); Double result = func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.0))); Assert.assertEquals((double)result, Double.NaN); } @Test public void normalCase() throws Exception { EvalFunc<Double> func = new GetQuantileFromDoublesSketch(); UpdateDoublesSketch sketch = DoublesSketch.builder().build(); sketch.update(1.0); Double result = func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 0.5))); Assert.assertEquals((double)result, 1.0); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongNumberOfInputs() throws Exception { EvalFunc<Double> func = new GetQuantileFromDoublesSketch(); func.exec(tupleFactory.newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { EvalFunc<Double> func = new GetQuantileFromDoublesSketch(); func.exec(tupleFactory.newTuple(Arrays.asList(1.0, 1.0))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForFraction() throws Exception { EvalFunc<Double> func = new GetQuantileFromDoublesSketch(); DoublesSketch sketch = DoublesSketch.builder().build(); func.exec(tupleFactory.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray()), 1))); } }
5,762
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/GetQuantileFromStringsSketchTest.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.pig.quantiles; import org.apache.datasketches.ArrayOfItemsSerDe; import org.apache.datasketches.ArrayOfStringsSerDe; import org.apache.datasketches.quantiles.ItemsSketch; import java.util.Arrays; import java.util.Comparator; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.testng.Assert; @SuppressWarnings("javadoc") public class GetQuantileFromStringsSketchTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); private static final Comparator<String> COMPARATOR = Comparator.naturalOrder(); private static final ArrayOfItemsSerDe<String> SER_DE = new ArrayOfStringsSerDe(); @Test public void emptySketch() throws Exception { EvalFunc<String> func = new GetQuantileFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); String result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), 0.0))); Assert.assertNull(result); } @Test public void normalCase() throws Exception { EvalFunc<String> func = new GetQuantileFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); sketch.update("a"); String result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), 0.5))); Assert.assertEquals(result, "a"); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongNumberOfInputs() throws Exception { EvalFunc<String> func = new GetQuantileFromStringsSketch(); func.exec(TUPLE_FACTORY.newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { EvalFunc<String> func = new GetQuantileFromStringsSketch(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0, 1.0))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForFraction() throws Exception { EvalFunc<String> func = new GetQuantileFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), 1))); } }
5,763
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/DataToStringsSketchTest.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.pig.quantiles; import java.util.Comparator; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.ArrayOfItemsSerDe; import org.apache.datasketches.ArrayOfStringsSerDe; import org.apache.datasketches.quantiles.ItemsSketch; @SuppressWarnings("javadoc") public class DataToStringsSketchTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); private static final BagFactory BAG_FACTORY = BagFactory.getInstance(); private static final Comparator<String> COMPARATOR = Comparator.naturalOrder(); private static final ArrayOfItemsSerDe<String> SER_DE = new ArrayOfStringsSerDe(); @Test public void execNullInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToStringsSketch(); Tuple resultTuple = func.exec(null); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new DataToStringsSketch(); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple()); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyBag() throws Exception { EvalFunc<Tuple> func = new DataToStringsSketch(); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test(expectedExceptions = ClassCastException.class) public void execWrongValueType() throws Exception { EvalFunc<Tuple> func = new DataToStringsSketch(); DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple(1.0)); func.exec(TUPLE_FACTORY.newTuple(bag)); } @Test public void execNormalCase() throws Exception { EvalFunc<Tuple> func = new DataToStringsSketch(); DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple("a")); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 1); } @Test public void execMixedNormalCase() throws Exception { EvalFunc<Tuple> func = new DataToStringsSketch(); DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple("a")); bag.add(null); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 1); } @Test public void accumulator() throws Exception { Accumulator<Tuple> func = new DataToStringsSketch(); // no input yet Tuple resultTuple = func.getValue(); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // null input tuple func.accumulate(null); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // empty input tuple func.accumulate(TUPLE_FACTORY.newTuple()); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // empty bag func.accumulate(TUPLE_FACTORY.newTuple(BAG_FACTORY.newDefaultBag())); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // normal case DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple("a")); func.accumulate(TUPLE_FACTORY.newTuple(bag)); func.accumulate(TUPLE_FACTORY.newTuple(bag)); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); // mixed null case bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple("a")); bag.add(null); func.accumulate(TUPLE_FACTORY.newTuple(bag)); func.accumulate(TUPLE_FACTORY.newTuple(bag)); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); // cleanup func.cleanup(); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicInitial() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToStringsSketch().getInitial()).newInstance(); DataBag bag = BAG_FACTORY.newDefaultBag(); bag.add(TUPLE_FACTORY.newTuple()); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertTrue(resultTuple.get(0) instanceof DataBag); Assert.assertEquals(((DataBag) resultTuple.get(0)).size(), 1); } @Test public void algebraicIntermediateIsSameAsFinal() { Assert.assertEquals(new DataToStringsSketch().getIntermed(), new DataToStringsSketch().getFinal()); } @Test public void algebraicIntermediateFinalNullInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToStringsSketch().getIntermed()).newInstance(); Tuple resultTuple = func.exec(null); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateFinalEmptyInputTuple() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToStringsSketch().getIntermed()).newInstance(); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple()); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateFinalNormalCase() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToStringsSketch().getIntermed()).newInstance(); DataBag bag = BAG_FACTORY.newDefaultBag(); { // this is to simulate an output from Initial DataBag innerBag = BAG_FACTORY.newDefaultBag(); innerBag.add(TUPLE_FACTORY.newTuple("a")); bag.add(TUPLE_FACTORY.newTuple(innerBag)); } { // this is to simulate an output from a prior call of IntermediateFinal ItemsSketch<String> qs = ItemsSketch.getInstance(COMPARATOR); qs.update("b"); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray(SER_DE)))); } Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test public void algebraicIntermediateFinalMixedNullCase() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToStringsSketch().getIntermed()).newInstance(); DataBag bag = BAG_FACTORY.newDefaultBag(); { // this is to simulate an output from Initial DataBag innerBag = BAG_FACTORY.newDefaultBag(); innerBag.add(TUPLE_FACTORY.newTuple("a")); innerBag.add(null); bag.add(TUPLE_FACTORY.newTuple(innerBag)); } { // this is to simulate an output from a prior call of IntermediateFinal ItemsSketch<String> qs = ItemsSketch.getInstance(COMPARATOR); qs.update("b"); bag.add(TUPLE_FACTORY.newTuple(new DataByteArray(qs.toByteArray(SER_DE)))); } Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(bag)); ItemsSketch<String> sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test(expectedExceptions = IllegalArgumentException.class) public void algebraicIntermediateFinalWrongType() throws Exception { @SuppressWarnings("unchecked") EvalFunc<Tuple> func = (EvalFunc<Tuple>) Class.forName(new DataToStringsSketch().getIntermed()).newInstance(); DataBag bag = BAG_FACTORY.newDefaultBag(); // this bag must have tuples with either bags or data byte arrays bag.add(TUPLE_FACTORY.newTuple("a")); func.exec(TUPLE_FACTORY.newTuple(bag)); } @Test public void schema() throws Exception { EvalFunc<Tuple> func = new DataToStringsSketch(); Schema schema = func.outputSchema(new Schema()); Assert.assertNotNull(schema); Assert.assertEquals(schema.size(), 1); Assert.assertEquals(schema.getField(0).type, DataType.TUPLE); Assert.assertEquals(schema.getField(0).schema.size(), 1); Assert.assertEquals(schema.getField(0).schema.getField(0).type, DataType.BYTEARRAY); } // end of tests private static ItemsSketch<String> getSketch(Tuple tuple) throws Exception { Assert.assertNotNull(tuple); Assert.assertEquals(tuple.size(), 1); DataByteArray bytes = (DataByteArray) tuple.get(0); Assert.assertTrue(bytes.size() > 0); return ItemsSketch.getInstance(Memory.wrap(bytes.get()), COMPARATOR, SER_DE); } }
5,764
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/UnionDoublesSketchTest.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.pig.quantiles; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.quantiles.DoublesSketch; import org.apache.datasketches.quantiles.UpdateDoublesSketch; @SuppressWarnings("javadoc") public class UnionDoublesSketchTest { private static final TupleFactory tupleFactory = TupleFactory.getInstance(); private static final BagFactory bagFactory = BagFactory.getInstance(); @Test public void execNullInputTuple() throws Exception { EvalFunc<Tuple> func = new UnionDoublesSketch(); Tuple resultTuple = func.exec(null); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new UnionDoublesSketch(); Tuple resultTuple = func.exec(tupleFactory.newTuple()); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void execEmptyBag() throws Exception { EvalFunc<Tuple> func = new UnionDoublesSketch(); Tuple resultTuple = func.exec(tupleFactory.newTuple(bagFactory.newDefaultBag())); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void execNormalCase() throws Exception { EvalFunc<Tuple> func = new UnionDoublesSketch(); DataBag bag = bagFactory.newDefaultBag(); UpdateDoublesSketch inputSketch = DoublesSketch.builder().build(); inputSketch.update(1.0); bag.add(tupleFactory.newTuple(new DataByteArray(inputSketch.toByteArray()))); Tuple resultTuple = func.exec(tupleFactory.newTuple(bag)); DoublesSketch sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 1); } @Test public void accumulator() throws Exception { Accumulator<Tuple> func = new UnionDoublesSketch(); // no input yet Tuple resultTuple = func.getValue(); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // null input tuple func.accumulate(null); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // empty input tuple func.accumulate(tupleFactory.newTuple()); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // empty bag func.accumulate(tupleFactory.newTuple(bagFactory.newDefaultBag())); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); // normal case DataBag bag = bagFactory.newDefaultBag(); UpdateDoublesSketch inputSketch = DoublesSketch.builder().build(); inputSketch.update(1.0); bag.add(tupleFactory.newTuple(new DataByteArray(inputSketch.toByteArray()))); func.accumulate(tupleFactory.newTuple(bag)); func.accumulate(tupleFactory.newTuple(bag)); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); // cleanup func.cleanup(); resultTuple = func.getValue(); sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicInitial() throws Exception { EvalFunc<Tuple> func = new UnionDoublesSketch.Initial(); DataBag bag = bagFactory.newDefaultBag(); bag.add(tupleFactory.newTuple()); Tuple resultTuple = func.exec(tupleFactory.newTuple(bag)); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertTrue(resultTuple.get(0) instanceof DataBag); Assert.assertEquals(((DataBag) resultTuple.get(0)).size(), 1); } @Test public void algebraicIntermediateFinalNullInputTuple() throws Exception { EvalFunc<Tuple> func = new UnionDoublesSketch.IntermediateFinal(); Tuple resultTuple = func.exec(null); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateFinalEmptyInputTuple() throws Exception { EvalFunc<Tuple> func = new UnionDoublesSketch.IntermediateFinal(); Tuple resultTuple = func.exec(tupleFactory.newTuple()); DoublesSketch sketch = getSketch(resultTuple); Assert.assertTrue(sketch.isEmpty()); } @Test public void algebraicIntermediateFinalNormalCase() throws Exception { EvalFunc<Tuple> func = new UnionDoublesSketch.IntermediateFinal(); DataBag bag = bagFactory.newDefaultBag(); { // this is to simulate an output from Initial DataBag innerBag = bagFactory.newDefaultBag(); UpdateDoublesSketch qs = DoublesSketch.builder().build(); qs.update(1.0); innerBag.add(tupleFactory.newTuple(new DataByteArray(qs.toByteArray()))); bag.add(tupleFactory.newTuple(innerBag)); } { // this is to simulate an output from a prior call of IntermediateFinal UpdateDoublesSketch qs = DoublesSketch.builder().build(); qs.update(2.0); bag.add(tupleFactory.newTuple(new DataByteArray(qs.toByteArray()))); } Tuple resultTuple = func.exec(tupleFactory.newTuple(bag)); DoublesSketch sketch = getSketch(resultTuple); Assert.assertFalse(sketch.isEmpty()); Assert.assertEquals(sketch.getN(), 2); } @Test(expectedExceptions = IllegalArgumentException.class) public void algebraicIntermediateFinalWrongType() throws Exception { EvalFunc<Tuple> func = new UnionDoublesSketch.IntermediateFinal(); DataBag bag = bagFactory.newDefaultBag(); // this bag must have tuples with either bags or data byte arrays bag.add(tupleFactory.newTuple(1.0)); func.exec(tupleFactory.newTuple(bag)); } @Test public void schema() throws Exception { EvalFunc<Tuple> func = new UnionDoublesSketch(); Schema schema = func.outputSchema(new Schema()); Assert.assertNotNull(schema); Assert.assertEquals(schema.size(), 1); Assert.assertEquals(schema.getField(0).type, DataType.TUPLE); Assert.assertEquals(schema.getField(0).schema.size(), 1); Assert.assertEquals(schema.getField(0).schema.getField(0).type, DataType.BYTEARRAY); } // end of tests private static DoublesSketch getSketch(Tuple tuple) throws Exception { Assert.assertNotNull(tuple); Assert.assertEquals(tuple.size(), 1); DataByteArray bytes = (DataByteArray) tuple.get(0); Assert.assertTrue(bytes.size() > 0); return DoublesSketch.heapify(Memory.wrap(bytes.get())); } }
5,765
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/DoublesSketchToStringTest.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.pig.quantiles; import java.util.Arrays; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.apache.datasketches.quantiles.DoublesSketch; import org.testng.Assert; @SuppressWarnings("javadoc") public class DoublesSketchToStringTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); @Test public void nullInputTuple() throws Exception { final EvalFunc<String> func = new DoublesSketchToString(); final String result = func.exec(null); Assert.assertNull(result); } @Test(expectedExceptions = IllegalArgumentException.class) public void emptyInputTuple() throws Exception { final EvalFunc<String> func = new DoublesSketchToString(); final String result = func.exec(TUPLE_FACTORY.newTuple()); Assert.assertNull(result); } @Test(expectedExceptions = IllegalArgumentException.class) public void tooManyInputs() throws Exception { final EvalFunc<String> func = new DoublesSketchToString(); func.exec(TUPLE_FACTORY.newTuple(2)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { final EvalFunc<String> func = new DoublesSketchToString(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0))); } @Test public void normalCase() throws Exception { final EvalFunc<String> func = new DoublesSketchToString(); final DoublesSketch sketch = DoublesSketch.builder().build(); final String result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray())))); Assert.assertNotNull(result); } }
5,766
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/GetQuantilesFromStringsSketchTest.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.pig.quantiles; import org.apache.datasketches.ArrayOfItemsSerDe; import org.apache.datasketches.ArrayOfStringsSerDe; import org.apache.datasketches.quantiles.ItemsSketch; import java.util.Arrays; import java.util.Comparator; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.testng.Assert; @SuppressWarnings("javadoc") public class GetQuantilesFromStringsSketchTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); private static final Comparator<String> COMPARATOR = Comparator.naturalOrder(); private static final ArrayOfItemsSerDe<String> SER_DE = new ArrayOfStringsSerDe(); @Test public void emptySketch() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), 0.5))); Assert.assertNull(resultTuple); } @Test(expectedExceptions = IllegalArgumentException.class) public void tooFewInputs() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromStringsSketch(); func.exec(TUPLE_FACTORY.newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromStringsSketch(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0, 1.0))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForFractionOrNumberOfIntervals() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); sketch.update("a"); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), ""))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeAmongFractions() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); sketch.update("a"); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), 0.0, 1))); } @Test public void oneFraction() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); for (int i = 1; i <= 10; i++) { sketch.update(String.format("%02d", i)); } Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), 0.5))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 1); Assert.assertEquals(((String) resultTuple.get(0)), "06"); } @Test public void severalFractions() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); for (int i = 1; i <= 10; i++) { sketch.update(String.format("%02d", i)); } Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), 0.0, 0.5, 1.0))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals(((String) resultTuple.get(0)), "01"); Assert.assertEquals(((String) resultTuple.get(1)), "06"); Assert.assertEquals(((String) resultTuple.get(2)), "10"); } @Test public void numberOfEvenlySpacedIntervals() throws Exception { EvalFunc<Tuple> func = new GetQuantilesFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); for (int i = 1; i <= 10; i++) { sketch.update(String.format("%02d", i)); } Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), 3))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals(((String) resultTuple.get(0)), "01"); Assert.assertEquals(((String) resultTuple.get(1)), "06"); Assert.assertEquals(((String) resultTuple.get(2)), "10"); } }
5,767
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/GetKFromStringsSketchTest.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.pig.quantiles; import org.apache.datasketches.ArrayOfItemsSerDe; import org.apache.datasketches.ArrayOfStringsSerDe; import org.apache.datasketches.quantiles.ItemsSketch; import java.util.Arrays; import java.util.Comparator; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.testng.Assert; @SuppressWarnings("javadoc") public class GetKFromStringsSketchTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); private static final Comparator<String> COMPARATOR = Comparator.naturalOrder(); private static final ArrayOfItemsSerDe<String> SER_DE = new ArrayOfStringsSerDe(); @Test public void defalutK() throws Exception { EvalFunc<Integer> func = new GetKFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); Integer result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE))))); Assert.assertNotNull(result); Assert.assertEquals(result, Integer.valueOf(128)); } @Test public void customK() throws Exception { EvalFunc<Integer> func = new GetKFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(1024, COMPARATOR); Integer result = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE))))); Assert.assertNotNull(result); Assert.assertEquals(result, Integer.valueOf(1024)); } @Test(expectedExceptions = IllegalArgumentException.class) public void tooFewInputs() throws Exception { EvalFunc<Integer> func = new GetKFromStringsSketch(); func.exec(TUPLE_FACTORY.newTuple()); } @Test(expectedExceptions = IllegalArgumentException.class) public void tooManyInputs() throws Exception { EvalFunc<Integer> func = new GetKFromStringsSketch(); func.exec(TUPLE_FACTORY.newTuple(2)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { EvalFunc<Integer> func = new GetKFromStringsSketch(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0))); } }
5,768
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/StringsSketchToStringTest.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.pig.quantiles; import java.util.Arrays; import java.util.Comparator; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.apache.datasketches.ArrayOfItemsSerDe; import org.apache.datasketches.ArrayOfStringsSerDe; import org.apache.datasketches.quantiles.ItemsSketch; import org.testng.Assert; @SuppressWarnings("javadoc") public class StringsSketchToStringTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); private static final Comparator<String> COMPARATOR = Comparator.naturalOrder(); private static final ArrayOfItemsSerDe<String> SER_DE = new ArrayOfStringsSerDe(); @Test public void nullInputTuple() throws Exception { final EvalFunc<String> func = new StringsSketchToString(); final String result = func.exec(null); Assert.assertNull(result); } @Test(expectedExceptions = IllegalArgumentException.class) public void emptyInputTuple() throws Exception { final EvalFunc<String> func = new StringsSketchToString(); final String result = func.exec(TUPLE_FACTORY.newTuple()); Assert.assertNull(result); } @Test(expectedExceptions = IllegalArgumentException.class) public void tooManyInputs() throws Exception { final EvalFunc<String> func = new StringsSketchToString(); func.exec(TUPLE_FACTORY.newTuple(2)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { final EvalFunc<String> func = new StringsSketchToString(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0))); } @Test public void normalCase() throws Exception { final EvalFunc<String> func = new DoublesSketchToString(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); final String result = func.exec(TUPLE_FACTORY.newTuple(new DataByteArray(sketch.toByteArray(SER_DE)))); Assert.assertNotNull(result); } }
5,769
0
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/test/java/org/apache/datasketches/pig/quantiles/GetPmfFromStringsSketchTest.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.pig.quantiles; import org.apache.datasketches.ArrayOfItemsSerDe; import org.apache.datasketches.ArrayOfStringsSerDe; import org.apache.datasketches.quantiles.ItemsSketch; import java.util.Arrays; import java.util.Comparator; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.testng.annotations.Test; import org.testng.Assert; @SuppressWarnings("javadoc") public class GetPmfFromStringsSketchTest { private static final TupleFactory TUPLE_FACTORY = TupleFactory.getInstance(); private static final Comparator<String> COMPARATOR = Comparator.naturalOrder(); private static final ArrayOfItemsSerDe<String> SER_DE = new ArrayOfStringsSerDe(); @Test public void emptySketch() throws Exception { EvalFunc<Tuple> func = new GetPmfFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), "a"))); Assert.assertNull(resultTuple); } @Test public void normalCase() throws Exception { EvalFunc<Tuple> func = new GetPmfFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); for (int i = 1; i <= 10; i++) { sketch.update(String.format("%02d", i)); } Tuple resultTuple = func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), "02", "07"))); Assert.assertNotNull(resultTuple); Assert.assertEquals(resultTuple.size(), 3); Assert.assertEquals(((double) resultTuple.get(0)), 0.1); Assert.assertEquals(((double) resultTuple.get(1)), 0.5); Assert.assertEquals(((double) resultTuple.get(2)), 0.4); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongNumberOfInputs() throws Exception { EvalFunc<Tuple> func = new GetPmfFromStringsSketch(); func.exec(TUPLE_FACTORY.newTuple(1)); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeForSketch() throws Exception { EvalFunc<Tuple> func = new GetPmfFromStringsSketch(); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(1.0, 1.0))); } @Test(expectedExceptions = IllegalArgumentException.class) public void wrongTypeOfSplitPoint() throws Exception { EvalFunc<Tuple> func = new GetPmfFromStringsSketch(); ItemsSketch<String> sketch = ItemsSketch.getInstance(COMPARATOR); func.exec(TUPLE_FACTORY.newTuple(Arrays.asList(new DataByteArray(sketch.toByteArray(SER_DE)), 1))); } }
5,770
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/UnionSketchAlgebraicIntermediate.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.pig.hll; import static org.apache.datasketches.pig.hll.DataToSketch.DEFAULT_HLL_TYPE; import static org.apache.datasketches.pig.hll.DataToSketch.DEFAULT_LG_K; import org.apache.datasketches.hll.TgtHllType; import org.apache.datasketches.hll.Union; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; @SuppressWarnings("javadoc") public class UnionSketchAlgebraicIntermediate extends AlgebraicIntermediate { /** * Default constructor of the intermediate pass of an Algebraic function. * Assumes default lgK and target HLL type. */ public UnionSketchAlgebraicIntermediate() { super(DEFAULT_LG_K, DEFAULT_HLL_TYPE); } /** * Constructor for the intermediate pass of an Algebraic function. Pig will call * this and pass the same constructor arguments as the base UDF. * Assumes default HLL target type. * * @param lgK in a form of a String */ public UnionSketchAlgebraicIntermediate(final String lgK) { super(Integer.parseInt(lgK), DEFAULT_HLL_TYPE); } /** * Constructor for the intermediate pass of an Algebraic function. Pig will call * this and pass the same constructor arguments as the base UDF. * * @param lgK parameter controlling the sketch size and accuracy * @param tgtHllType HLL type of the resulting sketch */ public UnionSketchAlgebraicIntermediate(final String lgK, final String tgtHllType) { super(Integer.parseInt(lgK), TgtHllType.valueOf(tgtHllType)); } @Override void updateUnion(final DataBag bag, final Union union) throws ExecException { UnionSketch.updateUnion(bag, union); } }
5,771
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/UnionSketch.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.pig.hll; import static org.apache.datasketches.pig.hll.DataToSketch.DEFAULT_HLL_TYPE; import static org.apache.datasketches.pig.hll.DataToSketch.DEFAULT_LG_K; import java.io.IOException; import org.apache.datasketches.hll.HllSketch; import org.apache.datasketches.hll.TgtHllType; import org.apache.datasketches.hll.Union; import org.apache.datasketches.memory.Memory; import org.apache.log4j.Logger; import org.apache.pig.Accumulator; import org.apache.pig.Algebraic; import org.apache.pig.EvalFunc; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; /** * This is a Pig UDF that performs the Union operation on HllSketches. * This class implements both the <i>Accumulator</i> and <i>Algebraic</i> interfaces. * * @author Alexander Saydakov */ public class UnionSketch extends EvalFunc<DataByteArray> implements Accumulator<DataByteArray>, Algebraic { private DataByteArray emptySketch_; // this is to cash an empty sketch private final int lgK_; private final TgtHllType tgtHllType_; private Union accumUnion_; private boolean isFirstCall_; /** * Constructor with default lgK and target HLL type */ public UnionSketch() { this(DEFAULT_LG_K, DEFAULT_HLL_TYPE); } /** * Constructor with given lgK as string and default target HLL type. * * @param lgK in a form of a String */ public UnionSketch(final String lgK) { this(Integer.parseInt(lgK), DEFAULT_HLL_TYPE); } /** * Constructor with given lgK and target HLL type as strings * * @param lgK in a form of a String * @param tgtHllType in a form of a String */ public UnionSketch(final String lgK, final String tgtHllType) { this(Integer.parseInt(lgK), TgtHllType.valueOf(tgtHllType)); } /** * Base constructor. * * @param lgK parameter controlling the sketch size and accuracy * @param tgtHllType HLL type of the resulting sketch */ public UnionSketch(final int lgK, final TgtHllType tgtHllType) { super(); this.lgK_ = lgK; this.tgtHllType_ = tgtHllType; } /** * Top-level exec function. * This method accepts an input Tuple containing a Bag of one or more inner <b>Sketch Tuples</b> * and returns a single serialized HllSketch as a DataByteArray. * * <b>Sketch Tuple</b> is a Tuple containing a single DataByteArray (BYTEARRAY in Pig), which * is a serialized HllSketch. * * @param inputTuple A tuple containing a single bag, containing Sketch Tuples. * @return serialized HllSketch * @see "org.apache.pig.EvalFunc.exec(org.apache.pig.data.Tuple)" * @throws IOException from Pig. */ @Override public DataByteArray exec(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { Logger.getLogger(getClass()).info("Exec was used"); this.isFirstCall_ = false; } if (inputTuple == null || inputTuple.size() == 0) { if (this.emptySketch_ == null) { this.emptySketch_ = new DataByteArray(new HllSketch(this.lgK_, this.tgtHllType_).toCompactByteArray()); } return this.emptySketch_; } final Union union = new Union(this.lgK_); final DataBag bag = (DataBag) inputTuple.get(0); updateUnion(bag, union); return new DataByteArray(union.getResult(this.tgtHllType_).toCompactByteArray()); } /** * An <i>Accumulator</i> version of the standard <i>exec()</i> method. Like <i>exec()</i>, * accumulator is called with a bag of Sketch Tuples. Unlike <i>exec()</i>, it doesn't serialize the * result at the end. Instead, it can be called multiple times, each time with another bag of * Sketch Tuples to be input to the union. * * @param inputTuple A tuple containing a single bag, containing Sketch Tuples. * @see #exec * @see "org.apache.pig.Accumulator.accumulate(org.apache.pig.data.Tuple)" * @throws IOException by Pig */ @Override public void accumulate(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { Logger.getLogger(getClass()).info("Accumulator was used"); this.isFirstCall_ = false; } if (inputTuple == null || inputTuple.size() == 0) { return; } final DataBag bag = (DataBag) inputTuple.get(0); if (bag == null) { return; } if (this.accumUnion_ == null) { this.accumUnion_ = new Union(this.lgK_); } updateUnion(bag, this.accumUnion_); } /** * Returns the sketch that has been built up by multiple calls to {@link #accumulate}. * * @return Sketch Tuple. (see {@link #exec} for return tuple format) * @see "org.apache.pig.Accumulator.getValue()" */ @Override public DataByteArray getValue() { if (this.accumUnion_ == null) { if (this.emptySketch_ == null) { this.emptySketch_ = new DataByteArray( new HllSketch(this.lgK_, this.tgtHllType_).toCompactByteArray()); } return this.emptySketch_; } return new DataByteArray( this.accumUnion_.getResult(this.tgtHllType_).toCompactByteArray()); } /** * Cleans up the UDF state after being called using the {@link Accumulator} interface. * * @see "org.apache.pig.Accumulator.cleanup()" */ @Override public void cleanup() { this.accumUnion_ = null; } @Override public String getInitial() { return AlgebraicInitial.class.getName(); } @Override public String getIntermed() { return UnionSketchAlgebraicIntermediate.class.getName(); } @Override public String getFinal() { return UnionSketchAlgebraicFinal.class.getName(); } static void updateUnion(final DataBag bag, final Union union) throws ExecException { // Bag is not empty. process each innerTuple in the bag for (final Tuple innerTuple : bag) { final Object f0 = innerTuple.get(0); // consider only field 0 if (f0 == null) { continue; } final byte type = innerTuple.getType(0); if (type == DataType.BYTEARRAY) { final DataByteArray dba = (DataByteArray) f0; union.update(HllSketch.wrap(Memory.wrap(dba.get()))); } else { throw new IllegalArgumentException("Field type was not DataType.BYTEARRAY: " + type); } } } }
5,772
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/AlgebraicInitial.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.pig.hll; import java.io.IOException; import org.apache.log4j.Logger; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; /** * Class used to calculate the initial pass of an Algebraic sketch operation. * * <p>The Initial class simply passes through all records unchanged so that they can be * processed by the intermediate processor instead. * * @author Alexander Saydakov */ public class AlgebraicInitial extends EvalFunc<Tuple> { private boolean isFirstCall_ = true; /** * Default constructor for the initial pass of an Algebraic function. */ public AlgebraicInitial() {} /** * Constructor for the initial pass of an Algebraic function. Pig will call this and pass the * same constructor arguments as the original UDF. In this case the arguments are ignored. * * @param lgK in a form of a String */ public AlgebraicInitial(final String lgK) {} /** * Constructor for the initial pass of an Algebraic function. Pig will call this and pass the * same constructor arguments as the original UDF. In this case the arguments are ignored. * * @param lgK in a form of a String * @param tgtHllType in a form of a String */ public AlgebraicInitial(final String lgK, final String tgtHllType) {} @Override public Tuple exec(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { Logger.getLogger(getClass()).info("Algebraic was used"); this.isFirstCall_ = false; } return inputTuple; } }
5,773
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/AlgebraicFinal.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.pig.hll; import java.io.IOException; import org.apache.datasketches.hll.HllSketch; import org.apache.datasketches.hll.TgtHllType; import org.apache.datasketches.hll.Union; import org.apache.datasketches.memory.Memory; import org.apache.log4j.Logger; import org.apache.pig.EvalFunc; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; /** * Class used to calculate the final pass of an <i>Algebraic</i> sketch * operation. It will receive a bag of values returned by either the <i>Intermediate</i> * stage or the <i>Initial</i> stages, so it needs to be able to differentiate between and * interpret both types. * * @author Alexander Saydakov */ abstract class AlgebraicFinal extends EvalFunc<DataByteArray> { private final int lgK_; private final TgtHllType tgtHllType_; private DataByteArray emptySketch_; // this is to cash an empty sketch tuple private boolean isFirstCall_ = true; // for logging /** * Constructor with primitives for the final passes of an Algebraic function. * * @param lgK parameter controlling the sketch size and accuracy * @param tgtHllType HLL type of the resulting sketch */ public AlgebraicFinal(final int lgK, final TgtHllType tgtHllType) { this.lgK_ = lgK; this.tgtHllType_ = tgtHllType; } @Override public DataByteArray exec(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { Logger.getLogger(getClass()).info("Algebraic was used"); this.isFirstCall_ = false; } if (inputTuple == null || inputTuple.size() == 0) { return getEmptySketch(); } final Union union = new Union(this.lgK_); final DataBag outerBag = (DataBag) inputTuple.get(0); if (outerBag == null) { return getEmptySketch(); } for (final Tuple dataTuple: outerBag) { final Object f0 = dataTuple.get(0); // inputTuple.bag0.dataTupleN.f0 if (f0 == null) { continue; } if (f0 instanceof DataBag) { final DataBag innerBag = (DataBag) f0; // inputTuple.bag0.dataTupleN.f0:bag if (innerBag.size() == 0) { continue; } // If field 0 of a dataTuple is a Bag, all innerTuples of this inner bag // will be passed into the union. // It is due to system bagged outputs from multiple mapper Initial functions. // The Intermediate stage was bypassed. updateUnion(innerBag, union); } else if (f0 instanceof DataByteArray) { // inputTuple.bag0.dataTupleN.f0:DBA // If field 0 of a dataTuple is a DataByteArray, we assume it is a sketch // due to system bagged outputs from multiple mapper Intermediate functions. // Each dataTuple.DBA:sketch will merged into the union. final DataByteArray dba = (DataByteArray) f0; union.update(HllSketch.wrap(Memory.wrap(dba.get()))); } else { // we should never get here throw new IllegalArgumentException("dataTuple.Field0 is not a DataBag or DataByteArray: " + f0.getClass().getName()); } } return new DataByteArray(union.getResult(this.tgtHllType_).toCompactByteArray()); } abstract void updateUnion(DataBag bag, Union union) throws ExecException; private DataByteArray getEmptySketch() { if (this.emptySketch_ == null) { this.emptySketch_ = new DataByteArray( new HllSketch(this.lgK_, this.tgtHllType_).toCompactByteArray()); } return this.emptySketch_; } }
5,774
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/DataToSketch.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.pig.hll; import java.io.IOException; import org.apache.datasketches.hll.HllSketch; import org.apache.datasketches.hll.TgtHllType; import org.apache.datasketches.hll.Union; import org.apache.log4j.Logger; import org.apache.pig.Accumulator; import org.apache.pig.Algebraic; import org.apache.pig.EvalFunc; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; /** * This is a Pig UDF that builds Sketches from data. * This class implements both the <i>Accumulator</i> and <i>Algebraic</i> interfaces. * * @author Alexander Saydakov */ public class DataToSketch extends EvalFunc<DataByteArray> implements Accumulator<DataByteArray>, Algebraic { static final int DEFAULT_LG_K = 12; static final TgtHllType DEFAULT_HLL_TYPE = TgtHllType.HLL_4; private DataByteArray emptySketch_; // this is to cash an empty sketch private final int lgK_; private final TgtHllType tgtHllType_; private Union accumUnion_; private boolean isFirstCall_; /** * Constructor with default lgK and target HLL type */ public DataToSketch() { this(DEFAULT_LG_K, DEFAULT_HLL_TYPE); } /** * Constructor with given lgK as string and default target HLL type. * * @param lgK in a form of a String */ public DataToSketch(final String lgK) { this(Integer.parseInt(lgK), DEFAULT_HLL_TYPE); } /** * Constructor with given lgK and target HLL type as strings * * @param lgK in a form of a String * @param tgtHllType in a form of a String */ public DataToSketch(final String lgK, final String tgtHllType) { this(Integer.parseInt(lgK), TgtHllType.valueOf(tgtHllType)); } /** * Base constructor. * * @param lgK parameter controlling the sketch size and accuracy * @param tgtHllType HLL type of the resulting sketch */ public DataToSketch(final int lgK, final TgtHllType tgtHllType) { super(); this.lgK_ = lgK; this.tgtHllType_ = tgtHllType; } /** * Top-level exec function. * This method accepts an input Tuple containing a Bag of one or more inner <b>Datum Tuples</b> * and returns a single serialized HllSketch as a DataByteArray. * * <b>Datum Tuple</b> is a Tuple containing a single field, which can be one of the following * (Java type: Pig type): * <ul> * <li>Byte: BYTE</li> * <li>Integer: INTEGER</li> * <li>Long: LONG</li> * <li>Float: FLOAT</li> * <li>Double: DOUBLE</li> * <li>String: CHARARRAY</li> * <li>DataByteArray: BYTEARRAY</li> * </ul> * * <p><b>Note</b> Strings as values are normally typed as DataType.CHARARRAY, which will be * encoded as UTF-8 prior to being submitted to the sketch. If the user requires a different * encoding for cross-platform compatibility, it is recommended that these values be encoded prior * to being submitted and then typed as a DataType.BYTEARRAY.</p> * * @param inputTuple A tuple containing a single bag, containing Datum Tuples. * @return serialized HllSketch * @see "org.apache.pig.EvalFunc.exec(org.apache.pig.data.Tuple)" * @throws IOException from Pig. */ @Override public DataByteArray exec(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { Logger.getLogger(getClass()).info("Exec was used"); this.isFirstCall_ = false; } if (inputTuple == null || inputTuple.size() == 0) { if (this.emptySketch_ == null) { this.emptySketch_ = new DataByteArray(new HllSketch(this.lgK_, this.tgtHllType_).toCompactByteArray()); } return this.emptySketch_; } final Union union = new Union(this.lgK_); final DataBag bag = (DataBag) inputTuple.get(0); updateUnion(bag, union); return new DataByteArray(union.getResult(this.tgtHllType_).toCompactByteArray()); } /** * An <i>Accumulator</i> version of the standard <i>exec()</i> method. Like <i>exec()</i>, * accumulator is called with a bag of Datum Tuples. Unlike <i>exec()</i>, it doesn't serialize the * result at the end. Instead, it can be called multiple times, each time with another bag of * Datum Tuples to be input to the sketch. * * @param inputTuple A tuple containing a single bag, containing Datum Tuples. * @see #exec * @see "org.apache.pig.Accumulator.accumulate(org.apache.pig.data.Tuple)" * @throws IOException by Pig */ @Override public void accumulate(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { Logger.getLogger(getClass()).info("Accumulator was used"); this.isFirstCall_ = false; } if (inputTuple == null || inputTuple.size() == 0) { return; } final DataBag bag = (DataBag) inputTuple.get(0); if (bag == null) { return; } if (this.accumUnion_ == null) { this.accumUnion_ = new Union(this.lgK_); } updateUnion(bag, this.accumUnion_); } /** * Returns the sketch that has been built up by multiple calls to {@link #accumulate}. * * @return serialized HllSketch * @see "org.apache.pig.Accumulator.getValue()" */ @Override public DataByteArray getValue() { if (this.accumUnion_ == null) { if (this.emptySketch_ == null) { this.emptySketch_ = new DataByteArray(new HllSketch(this.lgK_, this.tgtHllType_).toCompactByteArray()); } return this.emptySketch_; } return new DataByteArray(this.accumUnion_.getResult(this.tgtHllType_).toCompactByteArray()); } /** * Cleans up the UDF state after being called using the {@link Accumulator} interface. * * @see "org.apache.pig.Accumulator.cleanup()" */ @Override public void cleanup() { this.accumUnion_ = null; } @Override public String getInitial() { return AlgebraicInitial.class.getName(); } @Override public String getIntermed() { return DataToSketchAlgebraicIntermediate.class.getName(); } @Override public String getFinal() { return DataToSketchAlgebraicFinal.class.getName(); } static void updateUnion(final DataBag bag, final Union union) throws ExecException { //Bag is not empty. process each innerTuple in the bag for (final Tuple innerTuple: bag) { final Object f0 = innerTuple.get(0); // consider only field 0 if (f0 == null) { continue; } final byte type = innerTuple.getType(0); switch (type) { case DataType.NULL: break; case DataType.BYTE: union.update((byte) f0); break; case DataType.INTEGER: union.update((int) f0); break; case DataType.LONG: union.update((long) f0); break; case DataType.FLOAT: union.update((float) f0); break; case DataType.DOUBLE: union.update((double) f0); break; case DataType.BYTEARRAY: { final DataByteArray dba = (DataByteArray) f0; union.update(dba.get()); break; } case DataType.CHARARRAY: { final String str = (String) f0; // conversion to char[] avoids costly UTF-8 encoding union.update(str.toCharArray()); break; } default: throw new IllegalArgumentException("Field 0 of innerTuple must be one of " + "NULL, BYTE, INTEGER, LONG, FLOAT, DOUBLE, BYTEARRAY or CHARARRAY. " + "Given Type = " + DataType.findTypeName(type) + ", Object = " + f0.toString()); } } } }
5,775
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/SketchToEstimateAndErrorBounds.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.pig.hll; import java.io.IOException; import org.apache.datasketches.hll.HllSketch; import org.apache.datasketches.memory.Memory; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; /** * This is a User Defined Function (UDF) for obtaining the unique count estimate * along with a lower and upper bound from an HllSketch. * * <p>The result is a tuple with three double values: estimate, lower bound and upper bound. * The bounds are given at 95.5% confidence. * * @author Alexander Saydakov */ public class SketchToEstimateAndErrorBounds extends EvalFunc<Tuple> { @Override public Tuple exec(final Tuple sketchTuple) throws IOException { if ((sketchTuple == null) || (sketchTuple.size() == 0)) { return null; } final DataByteArray dba = (DataByteArray) sketchTuple.get(0); final HllSketch sketch = HllSketch.wrap(Memory.wrap(dba.get())); final Tuple outputTuple = TupleFactory.getInstance().newTuple(3); outputTuple.set(0, Double.valueOf(sketch.getEstimate())); outputTuple.set(1, Double.valueOf(sketch.getLowerBound(2))); outputTuple.set(2, Double.valueOf(sketch.getUpperBound(2))); return outputTuple; } /** * The output is a Sketch Result Tuple Schema. */ @Override public Schema outputSchema(final Schema input) { if (input == null) { return null; } try { final Schema tupleSchema = new Schema(); tupleSchema.add(new Schema.FieldSchema("Estimate", DataType.DOUBLE)); tupleSchema.add(new Schema.FieldSchema("LowerBound", DataType.DOUBLE)); tupleSchema.add(new Schema.FieldSchema("UpperBound", DataType.DOUBLE)); return new Schema(new Schema.FieldSchema(getSchemaName(this .getClass().getName().toLowerCase(), input), tupleSchema, DataType.TUPLE)); } catch (final FrontendException e) { throw new RuntimeException(e); } } }
5,776
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/UnionSketchAlgebraicFinal.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.pig.hll; import static org.apache.datasketches.pig.hll.DataToSketch.DEFAULT_HLL_TYPE; import static org.apache.datasketches.pig.hll.DataToSketch.DEFAULT_LG_K; import org.apache.datasketches.hll.TgtHllType; import org.apache.datasketches.hll.Union; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; @SuppressWarnings("javadoc") public class UnionSketchAlgebraicFinal extends AlgebraicFinal { /** * Default constructor for the final pass of an Algebraic function. * Assumes default lgK and target HLL type. */ public UnionSketchAlgebraicFinal() { super(DEFAULT_LG_K, DEFAULT_HLL_TYPE); } /** * Constructor for the final pass of an Algebraic function. Pig will call * this and pass the same constructor arguments as the base UDF. * Assumes default HLL target type. * * @param lgK in a form of a String */ public UnionSketchAlgebraicFinal(final String lgK) { super(Integer.parseInt(lgK), DEFAULT_HLL_TYPE); } /** * Constructor for the final pass of an Algebraic function. Pig will call * this and pass the same constructor arguments as the base UDF. * * @param lgK parameter controlling the sketch size and accuracy * @param tgtHllType HLL type of the resulting sketch */ public UnionSketchAlgebraicFinal(final String lgK, final String tgtHllType) { super(Integer.parseInt(lgK), TgtHllType.valueOf(tgtHllType)); } @Override void updateUnion(final DataBag bag, final Union union) throws ExecException { UnionSketch.updateUnion(bag, union); } }
5,777
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/SketchToEstimate.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.pig.hll; import java.io.IOException; import org.apache.datasketches.hll.HllSketch; import org.apache.datasketches.memory.Memory; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; /** * This is a User Defined Function (UDF) for getting a unique count estimate from an HllSketch * * @author Alexander Saydakov */ public class SketchToEstimate extends EvalFunc<Double> { @Override public Double exec(final Tuple sketchTuple) throws IOException { if ((sketchTuple == null) || (sketchTuple.size() == 0)) { return null; } final DataByteArray dba = (DataByteArray) sketchTuple.get(0); final HllSketch sketch = HllSketch.wrap(Memory.wrap(dba.get())); return sketch.getEstimate(); } }
5,778
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/DataToSketchAlgebraicFinal.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.pig.hll; import static org.apache.datasketches.pig.hll.DataToSketch.DEFAULT_HLL_TYPE; import static org.apache.datasketches.pig.hll.DataToSketch.DEFAULT_LG_K; import org.apache.datasketches.hll.TgtHllType; import org.apache.datasketches.hll.Union; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; @SuppressWarnings("javadoc") public class DataToSketchAlgebraicFinal extends AlgebraicFinal { /** * Default constructor for the final pass of an Algebraic function. * Assumes default lgK and target HLL type. */ public DataToSketchAlgebraicFinal() { super(DEFAULT_LG_K, DEFAULT_HLL_TYPE); } /** * Constructor for the final pass of an Algebraic function. Pig will call * this and pass the same constructor arguments as the base UDF. * Assumes default HLL target type. * * @param lgK in a form of a String */ public DataToSketchAlgebraicFinal(final String lgK) { super(Integer.parseInt(lgK), DEFAULT_HLL_TYPE); } /** * Constructor for the final pass of an Algebraic function. Pig will call * this and pass the same constructor arguments as the base UDF. * * @param lgK parameter controlling the sketch size and accuracy * @param tgtHllType HLL type of the resulting sketch */ public DataToSketchAlgebraicFinal(final String lgK, final String tgtHllType) { super(Integer.parseInt(lgK), TgtHllType.valueOf(tgtHllType)); } @Override void updateUnion(final DataBag bag, final Union union) throws ExecException { DataToSketch.updateUnion(bag, union); } }
5,779
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/package-info.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. */ /** * Pig UDFs for HLL sketches. * * <p>These UDFs can be used as a replacement of corresponding Theta sketch UDFs. * Notice that intersections and A-not-B operations are not supported by the HLL sketch. * Also notice a small difference in the output type of DataToSketch and UnionSketch: * HLL sketch UDFs return DataByteArray (BYTEARRAY in Pig), but corresponding Theta sketch * UDFs return a Tuple with single DataByteArray inside. This was a historical accident, * and we are reluctant to break the compatibility with existing scripts. HLL sketch UDFs * don't have to keep this compatibility. As a result, HLL sketch UDFs don't need * flatten() around them to remove the Tuple, and internally they don't have to spend extra * resources to wrap every output DataByteArray into a Tuple.</p> * * @author Alexander Saydakov */ package org.apache.datasketches.pig.hll;
5,780
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/DataToSketchAlgebraicIntermediate.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.pig.hll; import static org.apache.datasketches.pig.hll.DataToSketch.DEFAULT_HLL_TYPE; import static org.apache.datasketches.pig.hll.DataToSketch.DEFAULT_LG_K; import org.apache.datasketches.hll.TgtHllType; import org.apache.datasketches.hll.Union; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; @SuppressWarnings("javadoc") public class DataToSketchAlgebraicIntermediate extends AlgebraicIntermediate { /** * Default constructor for the intermediate pass of an Algebraic function. * Assumes default lgK and target HLL type. */ public DataToSketchAlgebraicIntermediate() { super(DEFAULT_LG_K, DEFAULT_HLL_TYPE); } /** * Constructor for the intermediate pass of an Algebraic function. Pig will call * this and pass the same constructor arguments as the base UDF. * Assumes default HLL target type. * * @param lgK in a form of a String */ public DataToSketchAlgebraicIntermediate(final String lgK) { super(Integer.parseInt(lgK), DEFAULT_HLL_TYPE); } /** * Constructor for the intermediate pass of an Algebraic function. Pig will call * this and pass the same constructor arguments as the base UDF. * * @param lgK parameter controlling the sketch size and accuracy * @param tgtHllType HLL type of the resulting sketch */ public DataToSketchAlgebraicIntermediate(final String lgK, final String tgtHllType) { super(Integer.parseInt(lgK), TgtHllType.valueOf(tgtHllType)); } @Override void updateUnion(final DataBag bag, final Union union) throws ExecException { DataToSketch.updateUnion(bag, union); } }
5,781
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/AlgebraicIntermediate.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.pig.hll; import java.io.IOException; import org.apache.datasketches.hll.HllSketch; import org.apache.datasketches.hll.TgtHllType; import org.apache.datasketches.hll.Union; import org.apache.datasketches.memory.Memory; import org.apache.log4j.Logger; import org.apache.pig.EvalFunc; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; /** * Class used to calculate the intermediate combiner pass of an <i>Algebraic</i> sketch * operation. This is called from the combiner, and may be called multiple times (from a mapper * and from a reducer). It will receive a bag of values returned by either the <i>Intermediate</i> * stage or the <i>Initial</i> stages, so it needs to be able to differentiate between and * interpret both types. * * @author Alexander Saydakov */ abstract class AlgebraicIntermediate extends EvalFunc<Tuple> { private static final TupleFactory tupleFactory_ = TupleFactory.getInstance(); private final int lgK_; private final TgtHllType tgtHllType_; private Tuple emptySketchTuple_; // this is to cash an empty sketch tuple private boolean isFirstCall_ = true; // for logging /** * Constructor with primitives for the intermediate pass of an Algebraic function. * * @param lgK parameter controlling the sketch size and accuracy * @param tgtHllType HLL type of the resulting sketch */ public AlgebraicIntermediate(final int lgK, final TgtHllType tgtHllType) { this.lgK_ = lgK; this.tgtHllType_ = tgtHllType; } @Override public Tuple exec(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { Logger.getLogger(getClass()).info("Algebraic was used"); this.isFirstCall_ = false; } if (inputTuple == null || inputTuple.size() == 0) { return getEmptySketchTuple(); } final DataBag outerBag = (DataBag) inputTuple.get(0); if (outerBag == null) { return getEmptySketchTuple(); } final Union union = new Union(this.lgK_); for (final Tuple dataTuple: outerBag) { final Object f0 = dataTuple.get(0); // inputTuple.bag0.dataTupleN.f0 if (f0 == null) { continue; } if (f0 instanceof DataBag) { final DataBag innerBag = (DataBag) f0; // inputTuple.bag0.dataTupleN.f0:bag if (innerBag.size() == 0) { continue; } // If field 0 of a dataTuple is a Bag, all innerTuples of this inner bag // will be passed into the union. // It is due to system bagged outputs from multiple mapper Initial functions. // The Intermediate stage was bypassed. updateUnion(innerBag, union); } else if (f0 instanceof DataByteArray) { // inputTuple.bag0.dataTupleN.f0:DBA // If field 0 of a dataTuple is a DataByteArray, we assume it is a sketch // due to system bagged outputs from multiple mapper Intermediate functions. // Each dataTuple.DBA:sketch will merged into the union. final DataByteArray dba = (DataByteArray) f0; union.update(HllSketch.wrap(Memory.wrap(dba.get()))); } else { // we should never get here throw new IllegalArgumentException("dataTuple.Field0 is not a DataBag or DataByteArray: " + f0.getClass().getName()); } } return tupleFactory_.newTuple(new DataByteArray(union.getResult(this.tgtHllType_).toCompactByteArray())); } abstract void updateUnion(DataBag bag, Union union) throws ExecException; private Tuple getEmptySketchTuple() { if (this.emptySketchTuple_ == null) { this.emptySketchTuple_ = tupleFactory_.newTuple(new DataByteArray( new HllSketch(this.lgK_, this.tgtHllType_).toCompactByteArray())); } return this.emptySketchTuple_; } }
5,782
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hll/SketchToString.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.pig.hll; import java.io.IOException; import org.apache.datasketches.hll.HllSketch; import org.apache.datasketches.memory.Memory; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; /** * This is a User Defined Function (UDF) for "pretty printing" the summary of an HllSketch * * @author Alexander Saydakov */ public class SketchToString extends EvalFunc<String> { private final boolean hllDetail_; private final boolean auxDetail_; /** * Prints only the sketch summary. */ public SketchToString() { this(false, false); } /** * Prints the summary and details based on given input parameters. * * @param hllDetail flag to print the HLL sketch detail * @param auxDetail flag to print the auxiliary detail */ public SketchToString(final String hllDetail, final String auxDetail) { this(Boolean.parseBoolean(hllDetail), Boolean.parseBoolean(auxDetail)); } /** * Internal constructor with primitive parameters. * * @param hllDetail flag to print the HLL sketch detail * @param auxDetail flag to print the auxiliary detail */ private SketchToString(final boolean hllDetail, final boolean auxDetail) { super(); this.hllDetail_ = hllDetail; this.auxDetail_ = auxDetail; } @Override public String exec(final Tuple sketchTuple) throws IOException { if ((sketchTuple == null) || (sketchTuple.size() == 0)) { return null; } final DataByteArray dba = (DataByteArray) sketchTuple.get(0); final HllSketch sketch = HllSketch.wrap(Memory.wrap(dba.get())); return sketch.toString(true, this.hllDetail_, this.auxDetail_); } }
5,783
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hash/MurmurHash3.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.pig.hash; import static java.lang.Math.min; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.datasketches.hash.MurmurHash3.hash; import static org.apache.datasketches.hash.MurmurHash3Adaptor.hashToLongs; import static org.apache.datasketches.hash.MurmurHash3Adaptor.modulo; import java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; /** * Computes a 128-bit MurmurHash3 hash of data input types: String, DataByteArray, Long, Integer, * Double, and Float. The 2nd optional parameter can be a Long or Integer seed. The 3rd optional * parameter can be a positive Integer modulus divisor. If the divisor is provided, the Integer * modulus remainder is computed on the entire 128-bit hash output treated as if it were a 128-bit * positive value. */ public class MurmurHash3 extends EvalFunc<Tuple> { private static final TupleFactory mTupleFactory = TupleFactory.getInstance(); private int divisor_ = 0; /** * Top Level Exec Function. * <p> * This method accepts an object to be hashed and returns a <i>Hash Result Tuple</i>. * </p> * * <b>Hash Input Tuple</b> * <ul> * <li>Tuple: TUPLE (Must contain 1 field and may contain 2 or 3): <br> * <ul> * <li>index 0: Object to be hashed: one of String, DataByteArray, Long, Integer, Double, * Float.</li> * <li>index 1: Seed: Long or Integer</li> * <li>index 2: Modulus divisor: Integer; must be positive.</li> * </ul> * </li> * </ul> * * <p> * Any other input tuple will throw an exception! * </p> * * <b>Hash Result Tuple</b> * <ul> * <li>Tuple: TUPLE (Contains 3 fields) * <ul> * <li>index 0: Long: LONG: The 1st 64 bits of the hash.</li> * <li>index 1: Long: LONG: The 2nd 64 bits of the hash.</li> * <li>index 2: Integer: INTEGER: Result of modulo operation, -1 if not computed. * </ul> * </li> * </ul> * * @param input Hash Input Tuple. If null or empty exec returns null. */ @Override public Tuple exec(final Tuple input) throws IOException { if ((input == null) || (input.size() == 0)) { return null; } final Tuple out = mTupleFactory.newTuple(3); final long[] hashOut = extractInputs(input); if (hashOut == null) { return out; //contains 3 nulls } final long h0 = hashOut[0]; final long h1 = hashOut[1]; final int modResult = (this.divisor_ > 0L) ? modulo(h0, h1, this.divisor_) : -1; out.set(0, Long.valueOf(h0)); out.set(1, Long.valueOf(h1)); out.set(2, Integer.valueOf(modResult)); return out; } private long[] extractInputs(final Tuple input) throws IOException { //may return null final int sw = min(input.size(), 3); long seed = 0L; Object obj = null; long[] hashOut = null; switch (sw) { case 3: { //modulus divisor obj = input.get(2); if (obj != null) { if (obj instanceof Integer) { this.divisor_ = (Integer) obj; } else { throw new IllegalArgumentException("Modulus divisor must be an Integer."); } if (this.divisor_ <= 0) { throw new IllegalArgumentException("Modulus divisor must be greater than zero. " + this.divisor_); } } //divisor may be null. If so it will not be used. } //$FALL-THROUGH$ case 2: { //seed obj = input.get(1); if (obj != null) { if (obj instanceof Long) { seed = (Long) obj; } else if (obj instanceof Integer) { seed = (Integer) obj; } else { throw new IllegalArgumentException("Seed must be an Integer or Long"); } } } //$FALL-THROUGH$ case 1: { obj = input.get(0); final int type = input.getType(0); switch (type) { case 1: { //Null type, returns null break; } case 10: { //Integer final long[] data = { (Integer) obj }; hashOut = hash(data, seed); break; } case 15: { //Long final long[] data = { (Long) obj }; hashOut = hash(data, seed); break; } case 20: { //Float hashOut = hashToLongs((Float) obj, seed); break; } case 25: { //Double hashOut = hashToLongs((Double) obj, seed); break; } case 50: { //BYTEARRAY = DataByteArray final DataByteArray dba = (DataByteArray) obj; if (dba.size() == 0) { break; //Empty return null } hashOut = hash(dba.get(), seed); break; } case 55: { //CHARARRAY = String final String datum = (String) obj; if (datum.isEmpty()) { break; //Empty return null } hashOut = hash(datum.getBytes(UTF_8), seed); break; } default: { throw new IllegalArgumentException("Cannot use this DataType: " + type); } } } } return hashOut; } /** * The output consists of two longs, or 128 bits, plus the result of the modulo division if * specified. */ @SuppressWarnings("unused") @Override public Schema outputSchema(final Schema input) { if (input != null) { try { final Schema tupleSchema = new Schema(); tupleSchema.add(new Schema.FieldSchema("Hash0", DataType.LONG)); tupleSchema.add(new Schema.FieldSchema("Hash1", DataType.LONG)); tupleSchema.add(new Schema.FieldSchema("ModuloResult", DataType.INTEGER)); return new Schema(new Schema.FieldSchema(getSchemaName(this .getClass().getName().toLowerCase(), input), tupleSchema, DataType.TUPLE)); } catch (final FrontendException e) { //fall through } } return null; } }
5,784
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/hash/package-info.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. */ /** * <p>The hash package contains a high-performing and extended Java implementation * of Austin Appleby's 128-bit MurmurHash3 hash function originally coded in C. * This core MurmurHash3.java class is used throughout all the sketch classes for consistentancy * and as long as the user specifies the same seed will result in coordinated hash operations. * This package also contains an adaptor class that extends the basic class with more functions * commonly associated with hashing. * </p> */ package org.apache.datasketches.pig.hash;
5,785
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/DataToArrayOfDoublesSketch.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.pig.tuple; import org.apache.pig.Algebraic; /** * This UDF creates an ArrayOfDoublesSketch from raw data. * It supports all three ways: exec(), Accumulator and Algebraic. */ @SuppressWarnings("javadoc") public class DataToArrayOfDoublesSketch extends DataToArrayOfDoublesSketchBase implements Algebraic { /** * Constructor with default sketch size, default sampling probability of 1 * and default number of values per key, which is 1. */ public DataToArrayOfDoublesSketch() { super(); } /** * Constructor with default sketch size and default sampling probability of 1. * @param numValues Number of double values to keep for each key */ public DataToArrayOfDoublesSketch(final String numValues) { super(Integer.parseInt(numValues)); } /** * Constructor with given sketch size, number of values and default sampling probability of 1. * @param sketchSize String representation of sketch size * @param numValues Number of double values to keep for each key */ public DataToArrayOfDoublesSketch(final String sketchSize, final String numValues) { super(Integer.parseInt(sketchSize), Integer.parseInt(numValues)); } /** * Constructor with given sketch size, sampling probability and number of values. * @param sketchSize String representation of sketch size * @param samplingProbability probability from 0 to 1 * @param numValues Number of double values to keep for each key */ public DataToArrayOfDoublesSketch( final String sketchSize, final String samplingProbability, final String numValues) { super(Integer.parseInt(sketchSize), Float.parseFloat(samplingProbability), Integer.parseInt(numValues)); } @Override public String getInitial() { return Initial.class.getName(); } @Override public String getIntermed() { return IntermediateFinal.class.getName(); } @Override public String getFinal() { return IntermediateFinal.class.getName(); } public static class Initial extends AlgebraicInitial { /** * Constructor for the initial pass of an Algebraic function. * Using default parameters. */ public Initial() {} /** * Constructor for the initial pass of an Algebraic function. This will be passed the same * constructor arguments as the original UDF. * @param numValues Number of double values to keep for each key */ public Initial(final String numValues) {} /** * Constructor for the initial pass of an Algebraic function. This will be passed the same * constructor arguments as the original UDF. * @param sketchSize String representation of sketch size * @param numValues Number of double values to keep for each key */ public Initial(final String sketchSize, final String numValues) {} /** * Constructor for the initial pass of an Algebraic function. This will be passed the same * constructor arguments as the original UDF. * @param sketchSize String representation of sketch size * @param samplingProbability probability from 0 to 1 * @param numValues Number of double values to keep for each key */ public Initial(final String sketchSize, final String samplingProbability, final String numValues) {} } public static class IntermediateFinal extends DataToArrayOfDoublesSketchAlgebraicIntermediateFinal { /** * Constructor for the intermediate and final passes of an Algebraic function. * Using default parameters. */ public IntermediateFinal() { super(); } /** * Constructor for the intermediate and final passes of an Algebraic function. This will be * passed the same constructor arguments as the original UDF. * @param numValues Number of double values to keep for each key */ public IntermediateFinal(final String numValues) { super(Integer.parseInt(numValues)); } /** * Constructor for the intermediate and final passes of an Algebraic function. This will be * passed the same constructor arguments as the original UDF. * @param sketchSize String representation of sketch size * @param numValues Number of double values to keep for each key */ public IntermediateFinal(final String sketchSize, final String numValues) { super(Integer.parseInt(sketchSize), Integer.parseInt(numValues)); } /** * Constructor for the intermediate and final passes of an Algebraic function. This will be * passed the same constructor arguments as the original UDF. * @param sketchSize String representation of sketch size * @param samplingProbability probability from 0 to 1 * @param numValues Number of double values to keep for each key */ public IntermediateFinal( final String sketchSize, final String samplingProbability, final String numValues) { super(Integer.parseInt(sketchSize), Float.parseFloat(samplingProbability), Integer.parseInt(numValues)); } } }
5,786
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/DataToArrayOfDoublesSketchAlgebraicIntermediateFinal.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.pig.tuple; import static org.apache.datasketches.Util.DEFAULT_NOMINAL_ENTRIES; import java.io.IOException; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder; 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.apache.log4j.Logger; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; /** * Class used to calculate the intermediate pass (combiner) or the final pass * (reducer) of an Algebraic sketch operation. This may be called multiple times * (from the mapper and from the reducer). It will receive a bag of values * returned by either the Intermediate stage or the Initial stages, so * it needs to be able to differentiate between and interpret both types. */ abstract class DataToArrayOfDoublesSketchAlgebraicIntermediateFinal extends EvalFunc<Tuple> { private final int sketchSize_; private final float samplingProbability_; private final int numValues_; private boolean isFirstCall_ = true; DataToArrayOfDoublesSketchAlgebraicIntermediateFinal() { this(DEFAULT_NOMINAL_ENTRIES, 1); } DataToArrayOfDoublesSketchAlgebraicIntermediateFinal(final int numValues) { this(DEFAULT_NOMINAL_ENTRIES, numValues); } DataToArrayOfDoublesSketchAlgebraicIntermediateFinal(final int sketchSize, final int numValues) { this(sketchSize, 1f, numValues); } DataToArrayOfDoublesSketchAlgebraicIntermediateFinal( final int sketchSize, final float samplingProbability, final int numValues) { this.sketchSize_ = sketchSize; this.samplingProbability_ = samplingProbability; this.numValues_ = numValues; } @Override public Tuple exec(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { // this is to see in the log which way was used by Pig Logger.getLogger(getClass()).info("algebraic is used"); this.isFirstCall_ = false; } final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().setNominalEntries(this.sketchSize_) .setNumberOfValues(this.numValues_).buildUnion(); final DataBag bag = (DataBag) inputTuple.get(0); if (bag == null) { throw new IllegalArgumentException("InputTuple.Field0: Bag may not be null"); } for (final Tuple dataTuple: bag) { final Object item = dataTuple.get(0); if (item instanceof DataBag) { // this is a bag from the Initial function. // just insert each item of the tuple into the sketch final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(this.sketchSize_) .setSamplingProbability(this.samplingProbability_).setNumberOfValues(this.numValues_).build(); DataToArrayOfDoublesSketchBase.updateSketch((DataBag) item, sketch, this.numValues_); union.union(sketch); } else if (item instanceof DataByteArray) { // This is a sketch from a prior call to the // Intermediate function. merge it with the // current sketch. final DataByteArray dba = (DataByteArray) item; union.union(ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dba.get()))); } else { // we should never get here. throw new IllegalArgumentException("InputTuple.Field0: Bag contains unrecognized types: " + item.getClass().getName()); } } return Util.tupleFactory.newTuple(new DataByteArray(union.getResult().toByteArray())); } }
5,787
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/UnionSketch.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.pig.tuple; import static org.apache.datasketches.Util.DEFAULT_NOMINAL_ENTRIES; import java.io.IOException; import org.apache.datasketches.tuple.Sketch; import org.apache.datasketches.tuple.Sketches; import org.apache.datasketches.tuple.Summary; import org.apache.datasketches.tuple.SummaryDeserializer; import org.apache.datasketches.tuple.SummarySetOperations; import org.apache.datasketches.tuple.Union; import org.apache.log4j.Logger; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; /** * This is a generic implementation to be specialized in concrete UDFs * @param <S> Summary type */ public abstract class UnionSketch<S extends Summary> extends EvalFunc<Tuple> implements Accumulator<Tuple> { private final int sketchSize_; private final SummarySetOperations<S> summarySetOps_; private final SummaryDeserializer<S> summaryDeserializer_; private Union<S> union_; private boolean isFirstCall_ = true; /** * Constructs a function given a summary set operations, summary deserializer and default sketch size * @param summarySetOps an instance of SummarySetOperations * @param summaryDeserializer an instance of SummaryDeserializer */ public UnionSketch(final SummarySetOperations<S> summarySetOps, final SummaryDeserializer<S> summaryDeserializer) { this(DEFAULT_NOMINAL_ENTRIES, summarySetOps, summaryDeserializer); } /** * Constructs a function given a sketch size, summary set operations and summary deserializer * @param sketchSize parameter controlling the size of the sketch and the accuracy. * It represents nominal number of entries in the sketch. Forced to the nearest power of 2 * greater than given value. * @param summarySetOps an instance of SummarySetOperations * @param summaryDeserializer an instance of SummaryDeserializer */ public UnionSketch(final int sketchSize, final SummarySetOperations<S> summarySetOps, final SummaryDeserializer<S> summaryDeserializer) { super(); this.sketchSize_ = sketchSize; this.summarySetOps_ = summarySetOps; this.summaryDeserializer_ = summaryDeserializer; } @Override public Tuple exec(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { // this is to see in the log which way was used by Pig Logger.getLogger(getClass()).info("exec is used"); this.isFirstCall_ = false; } if (inputTuple == null || inputTuple.size() == 0) { return null; } final DataBag bag = (DataBag) inputTuple.get(0); final Union<S> union = new Union<>(this.sketchSize_, this.summarySetOps_); updateUnion(bag, union, this.summaryDeserializer_); return Util.tupleFactory.newTuple(new DataByteArray(union.getResult().toByteArray())); } @Override public void accumulate(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { // this is to see in the log which way was used by Pig Logger.getLogger(getClass()).info("accumulator is used"); this.isFirstCall_ = false; } if (inputTuple == null || inputTuple.size() != 1) { return; } final DataBag bag = (DataBag) inputTuple.get(0); if (bag == null || bag.size() == 0) { return; } if (this.union_ == null) { this.union_ = new Union<>(this.sketchSize_, this.summarySetOps_); } updateUnion(bag, this.union_, this.summaryDeserializer_); } @Override public Tuple getValue() { if (this.union_ == null) { //return an empty sketch return Util.tupleFactory.newTuple(new DataByteArray(Sketches.createEmptySketch().toByteArray())); } return Util.tupleFactory.newTuple(new DataByteArray(this.union_.getResult().toByteArray())); } @Override public void cleanup() { if (this.union_ != null) { this.union_.reset(); } } private static <S extends Summary> void updateUnion(final DataBag bag, final Union<S> union, final SummaryDeserializer<S> summaryDeserializer) throws ExecException { for (final Tuple innerTuple: bag) { if (innerTuple.size() != 1 || innerTuple.get(0) == null) { continue; } final Sketch<S> incomingSketch = Util.deserializeSketchFromTuple(innerTuple, summaryDeserializer); union.union(incomingSketch); } } }
5,788
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/AlgebraicInitial.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.pig.tuple; import java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataBag; import org.apache.pig.data.Tuple; /** * This is a common pass-through implementation for initial step of an Algebraic operation */ public abstract class AlgebraicInitial extends EvalFunc<Tuple> { @Override public Tuple exec(final Tuple inputTuple) throws IOException { final DataBag bag = (DataBag) inputTuple.get(0); if (bag == null) { throw new IllegalArgumentException("InputTuple.Field0: Bag may not be null"); } return inputTuple; } }
5,789
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/Util.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.pig.tuple; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.tuple.Sketch; import org.apache.datasketches.tuple.Sketches; import org.apache.datasketches.tuple.Summary; import org.apache.datasketches.tuple.SummaryDeserializer; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; final class Util { static final TupleFactory tupleFactory = TupleFactory.getInstance(); static Tuple doubleArrayToTuple(final double[] array) throws ExecException { final Tuple tuple = tupleFactory.newTuple(array.length); for (int i = 0; i < array.length; i++) { tuple.set(i, array[i]); } return tuple; } static <S extends Summary> Sketch<S> deserializeSketchFromTuple(final Tuple tuple, final SummaryDeserializer<S> summaryDeserializer) throws ExecException { final byte[] bytes = ((DataByteArray) tuple.get(0)).get(); return Sketches.heapifySketch(Memory.wrap(bytes), summaryDeserializer); } }
5,790
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/DataToSketch.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.pig.tuple; import static org.apache.datasketches.Util.DEFAULT_NOMINAL_ENTRIES; import java.io.IOException; import org.apache.datasketches.tuple.SummaryFactory; import org.apache.datasketches.tuple.UpdatableSketch; import org.apache.datasketches.tuple.UpdatableSketchBuilder; import org.apache.datasketches.tuple.UpdatableSummary; import org.apache.log4j.Logger; import org.apache.pig.Accumulator; import org.apache.pig.EvalFunc; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; /** * This is a generic implementation to be specialized in concrete UDFs. * * <p><b>Note</b> Strings as values are normally typed as DataType.CHARARRAY, which will be * encoded as UTF-8 prior to being submitted to the sketch. If the user requires a different * encoding for cross-platform compatibility, it is recommended that these values be encoded prior * to being submitted in a DataBag and then typed as a DataType.BYTEARRAY.</p> * * @param <U> Update type * @param <S> Summary type */ public abstract class DataToSketch<U, S extends UpdatableSummary<U>> extends EvalFunc<Tuple> implements Accumulator<Tuple> { private final UpdatableSketchBuilder<U, S> sketchBuilder_; private UpdatableSketch<U, S> accumSketch_; private boolean isFirstCall_ = true; /** * Constructs a function given a summary factory, default sketch size and default * sampling probability of 1. * @param summaryFactory an instance of SummaryFactory */ public DataToSketch(final SummaryFactory<S> summaryFactory) { this(DEFAULT_NOMINAL_ENTRIES, 1f, summaryFactory); } /** * Constructs a function given a sketch size, summary factory and default * sampling probability of 1. * @param sketchSize parameter controlling the size of the sketch and the accuracy. * It represents nominal number of entries in the sketch. Forced to the nearest power of 2 * greater than given value. * @param summaryFactory an instance of SummaryFactory */ public DataToSketch(final int sketchSize, final SummaryFactory<S> summaryFactory) { this(sketchSize, 1f, summaryFactory); } /** * Constructs a function given a sketch size, sampling probability and summary factory * @param sketchSize parameter controlling the size of the sketch and the accuracy. * It represents nominal number of entries in the sketch. Forced to the nearest power of 2 * greater than given value. * @param samplingProbability parameter from 0 to 1 inclusive * @param summaryFactory an instance of SummaryFactory */ public DataToSketch(final int sketchSize, final float samplingProbability, final SummaryFactory<S> summaryFactory) { super(); this.sketchBuilder_ = new UpdatableSketchBuilder<>(summaryFactory) .setNominalEntries(sketchSize).setSamplingProbability(samplingProbability); } @Override public void accumulate(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { // this is to see in the log which way was used by Pig Logger.getLogger(getClass()).info("accumulate is used"); this.isFirstCall_ = false; } if (this.accumSketch_ == null) { this.accumSketch_ = this.sketchBuilder_.build(); } if (inputTuple.size() != 1) { throw new IllegalArgumentException("Input tuple must have 1 bag"); } final DataBag bag = (DataBag) inputTuple.get(0); updateSketch(bag, this.accumSketch_); } @Override public void cleanup() { this.accumSketch_ = null; } @Override public Tuple getValue() { if (this.accumSketch_ == null) { this.accumSketch_ = this.sketchBuilder_.build(); } return Util.tupleFactory.newTuple(new DataByteArray(this.accumSketch_.compact().toByteArray())); } @Override public Tuple exec(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { // this is to see in the log which way was used by Pig Logger.getLogger(getClass()).info("exec is used"); this.isFirstCall_ = false; } if (inputTuple == null || inputTuple.size() == 0) { return null; } if (inputTuple.size() != 1) { throw new IllegalArgumentException("Input tuple must have 1 bag"); } final UpdatableSketch<U, S> sketch = this.sketchBuilder_.build(); final DataBag bag = (DataBag) inputTuple.get(0); updateSketch(bag, sketch); return Util.tupleFactory.newTuple(new DataByteArray(sketch.compact().toByteArray())); } static <U, S extends UpdatableSummary<U>> void updateSketch(final DataBag bag, final UpdatableSketch<U, S> sketch) throws ExecException { if (bag == null) { throw new IllegalArgumentException("InputTuple.Field0: Bag may not be null"); } for (final Tuple tuple: bag) { if (tuple.size() != 2) { throw new IllegalArgumentException("Inner tuple of input bag must have 2 fields."); } final Object key = tuple.get(0); if (key == null) { continue; } @SuppressWarnings("unchecked") final U value = (U) tuple.get(1); switch (tuple.getType(0)) { case DataType.BYTE: sketch.update(((Byte) key).longValue(), value); break; case DataType.INTEGER: sketch.update(((Integer) key).longValue(), value); break; case DataType.LONG: sketch.update((Long) key, value); break; case DataType.FLOAT: sketch.update((Float) key, value); break; case DataType.DOUBLE: sketch.update((Double) key, value); break; case DataType.BYTEARRAY: final DataByteArray dba = (DataByteArray) key; if (dba.size() != 0) { sketch.update(dba.get(), value); } break; case DataType.CHARARRAY: final String s = key.toString(); if (!s.isEmpty()) { sketch.update(s, value); } break; default: throw new IllegalArgumentException("Field 0 must be one of " + "NULL, BYTE, INTEGER, LONG, FLOAT, DOUBLE, BYTEARRAY or CHARARRAY. " + "Type = " + DataType.findTypeName(tuple.getType(0)) + ", Object = " + key.toString()); } } } }
5,791
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/ArrayOfDoublesSketchToQuantilesSketch.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.pig.tuple; import java.io.IOException; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.quantiles.DoublesSketch; import org.apache.datasketches.quantiles.DoublesSketchBuilder; import org.apache.datasketches.quantiles.UpdateDoublesSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketches; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; /** * This UDF converts a given column of double values from an ArrayOfDoubles sketch * to a quantiles DoublesSketch to further analyze the distribution of these values. * The result will be a DataByteArray with serialized quantiles sketch. */ public class ArrayOfDoublesSketchToQuantilesSketch extends EvalFunc<DataByteArray> { private final int k; /** * Constructor with default parameter k for quantiles sketch */ public ArrayOfDoublesSketchToQuantilesSketch() { this.k = 0; } /** * Constructor with a given parameter k for quantiles sketch * @param k string representation of the parameter k that determines the accuracy * and size of the quantiles sketch */ public ArrayOfDoublesSketchToQuantilesSketch(final String k) { this.k = Integer.parseInt(k); } @Override public DataByteArray exec(final Tuple input) throws IOException { if (input == null || input.size() == 0) { return null; } final DataByteArray dba = (DataByteArray) input.get(0); final ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dba.get())); int column = 1; if (input.size() > 1) { column = (int) input.get(1); if (column < 1 || column > sketch.getNumValues()) { throw new IllegalArgumentException("Column number out of range. The given sketch has " + sketch.getNumValues() + " columns"); } } final DoublesSketchBuilder builder = DoublesSketch.builder(); if (this.k > 0) { builder.setK(this.k); } final UpdateDoublesSketch qs = builder.build(); final ArrayOfDoublesSketchIterator it = sketch.iterator(); while (it.next()) { qs.update(it.getValues()[column - 1]); } return new DataByteArray(qs.compact().toByteArray()); } }
5,792
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/UnionArrayOfDoublesSketchAlgebraicIntermediateFinal.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.pig.tuple; import static org.apache.datasketches.Util.DEFAULT_NOMINAL_ENTRIES; import java.io.IOException; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketches; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion; import org.apache.log4j.Logger; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; /** * This is to calculate the intermediate pass (combiner) or the final pass * (reducer) of an Algebraic sketch operation. This may be called multiple times * (from the mapper and from the reducer). It will receive a bag of values * returned by either the Intermediate or the Initial stages, so * it needs to be able to differentiate between and interpret both types. */ abstract class UnionArrayOfDoublesSketchAlgebraicIntermediateFinal extends EvalFunc<Tuple> { private final int sketchSize_; private final int numValues_; private boolean isFirstCall_ = true; UnionArrayOfDoublesSketchAlgebraicIntermediateFinal() { this(DEFAULT_NOMINAL_ENTRIES, 1); } UnionArrayOfDoublesSketchAlgebraicIntermediateFinal(final int numValues) { this(DEFAULT_NOMINAL_ENTRIES, numValues); } UnionArrayOfDoublesSketchAlgebraicIntermediateFinal(final int sketchSize, final int numValues) { super(); this.sketchSize_ = sketchSize; this.numValues_ = numValues; } @Override public Tuple exec(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { // this is to see in the log which way was used by Pig Logger.getLogger(getClass()).info("algebraic is used"); this.isFirstCall_ = false; } final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().setNominalEntries(this.sketchSize_) .setNumberOfValues(this.numValues_).buildUnion(); final DataBag bag = (DataBag) inputTuple.get(0); if (bag == null) { throw new IllegalArgumentException("InputTuple.Field0: Bag may not be null"); } for (final Tuple dataTuple: bag) { final Object item = dataTuple.get(0); if (item instanceof DataBag) { // this is from a prior call to the initial function, so there is a nested bag. for (final Tuple innerTuple: (DataBag) item) { final DataByteArray dba = (DataByteArray) innerTuple.get(0); union.union(ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dba.get()))); } } else if (item instanceof DataByteArray) { // This is a sketch from a call to the Intermediate function // Add it to the current union final DataByteArray dba = (DataByteArray) item; union.union(ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dba.get()))); } else { // we should never get here. throw new IllegalArgumentException("InputTuple.Field0: Bag contains unrecognized types: " + item.getClass().getName()); } } return Util.tupleFactory.newTuple(new DataByteArray(union.getResult().toByteArray())); } }
5,793
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/ArrayOfDoublesSketchesToPValueEstimates.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.pig.tuple; import java.io.IOException; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.commons.math3.stat.inference.TTest; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketches; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; /** * Calculate p-values given two ArrayOfDoublesSketch. Each value in the sketch * is treated as a separate metric measurement, and a p-value will be generated * for each metric. */ public class ArrayOfDoublesSketchesToPValueEstimates extends EvalFunc<Tuple> { @Override public Tuple exec(final Tuple input) throws IOException { if (input == null || input.size() != 2) { return null; } // Get the two sketches final DataByteArray dbaA = (DataByteArray) input.get(0); final DataByteArray dbaB = (DataByteArray) input.get(1); final ArrayOfDoublesSketch sketchA = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dbaA.get())); final ArrayOfDoublesSketch sketchB = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dbaB.get())); // Check that the size of the arrays in the sketches are the same if (sketchA.getNumValues() != sketchB.getNumValues()) { throw new IllegalArgumentException("Both sketches must have the same number of values"); } // Store the number of metrics final int numMetrics = sketchA.getNumValues(); // If the sketches contain fewer than 2 values, the p-value can't be calculated if (sketchA.getRetainedEntries() < 2 || sketchB.getRetainedEntries() < 2) { return null; } // Get the statistical summary from each sketch final SummaryStatistics[] summariesA = ArrayOfDoublesSketchStats.sketchToSummaryStatistics(sketchA); final SummaryStatistics[] summariesB = ArrayOfDoublesSketchStats.sketchToSummaryStatistics(sketchB); // Calculate the p-values final TTest tTest = new TTest(); final Tuple pValues = TupleFactory.getInstance().newTuple(numMetrics); for (int i = 0; i < numMetrics; i++) { // Pass the sampled values for each metric pValues.set(i, tTest.tTest(summariesA[i], summariesB[i])); } return pValues; } }
5,794
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/UnionDoubleSummarySketch.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.pig.tuple; import org.apache.datasketches.tuple.adouble.DoubleSummary; import org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer; import org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations; import org.apache.pig.Algebraic; /** * This is to union Sketch&lt;DoubleSummary&gt;. * It supports all three ways: exec(), Accumulator and Algebraic */ @SuppressWarnings("javadoc") public class UnionDoubleSummarySketch extends UnionSketch<DoubleSummary> implements Algebraic { /** * Constructor with default sketch size and default mode (sum) */ public UnionDoubleSummarySketch() { super(new DoubleSummarySetOperations(DoubleSummary.Mode.Sum), new DoubleSummaryDeserializer()); } /** * Constructor with default mode (sum) * @param sketchSize String representation of sketch size */ public UnionDoubleSummarySketch(final String sketchSize) { super(Integer.parseInt(sketchSize), new DoubleSummarySetOperations(DoubleSummary.Mode.Sum), new DoubleSummaryDeserializer()); } /** * Constructor * @param sketchSize String representation of sketch size * @param summaryMode String representation of mode (sum, min or max) */ public UnionDoubleSummarySketch(final String sketchSize, final String summaryMode) { super(Integer.parseInt(sketchSize), new DoubleSummarySetOperations(DoubleSummary.Mode.valueOf(summaryMode)), new DoubleSummaryDeserializer()); } @Override public String getInitial() { return Initial.class.getName(); } @Override public String getIntermed() { return IntermediateFinal.class.getName(); } @Override public String getFinal() { return IntermediateFinal.class.getName(); } public static class Initial extends AlgebraicInitial { /** * Constructor for the initial pass of an Algebraic function. * Default sketch size and default mode. */ public Initial() {} /** * Constructor for the initial pass of an Algebraic function. This will be passed the same * constructor arguments as the original UDF. * @param sketchSize String representation of sketch size */ public Initial(final String sketchSize) {} /** * Constructor for the initial pass of an Algebraic function. This will be passed the same * constructor arguments as the original UDF. * @param sketchSize String representation of sketch size * @param summaryMode String representation of mode (sum, min or max) */ public Initial(final String sketchSize, final String summaryMode) {} } public static class IntermediateFinal extends UnionSketchAlgebraicIntermediateFinal<DoubleSummary> { /** * Constructor for the intermediate and final passes of an Algebraic function. * Default sketch size and default mode. */ public IntermediateFinal() { super(new DoubleSummarySetOperations(DoubleSummary.Mode.Sum), new DoubleSummaryDeserializer()); } /** * Constructor for the intermediate and final passes of an Algebraic function. This will be * passed the same constructor arguments as the original UDF. * @param sketchSize String representation of sketch size */ public IntermediateFinal(final String sketchSize) { super(Integer.parseInt(sketchSize), new DoubleSummarySetOperations(DoubleSummary.Mode.Sum), new DoubleSummaryDeserializer()); } /** * Constructor for the intermediate and final passes of an Algebraic function. This will be * passed the same constructor arguments as the original UDF. * @param sketchSize String representation of sketch size * @param summaryMode String representation of mode (sum, min or max) */ public IntermediateFinal(final String sketchSize, final String summaryMode) { super(Integer.parseInt(sketchSize), new DoubleSummarySetOperations(DoubleSummary.Mode.valueOf(summaryMode)), new DoubleSummaryDeserializer()); } } }
5,795
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/DataToSketchAlgebraicIntermediateFinal.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.pig.tuple; import static org.apache.datasketches.Util.DEFAULT_NOMINAL_ENTRIES; import java.io.IOException; import org.apache.datasketches.tuple.Sketch; import org.apache.datasketches.tuple.SummaryDeserializer; import org.apache.datasketches.tuple.SummaryFactory; import org.apache.datasketches.tuple.SummarySetOperations; import org.apache.datasketches.tuple.Union; import org.apache.datasketches.tuple.UpdatableSketch; import org.apache.datasketches.tuple.UpdatableSketchBuilder; import org.apache.datasketches.tuple.UpdatableSummary; import org.apache.log4j.Logger; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; /** * Class used to calculate the intermediate pass (combiner) or the final pass * (reducer) of an Algebraic sketch operation. This may be called multiple times * (from the mapper and from the reducer). It will receive a bag of values * returned by either the Intermediate stage or the Initial stages, so * it needs to be able to differentiate between and interpret both types. * @param <U> Type of the update value * @param <S> Type of the summary */ public abstract class DataToSketchAlgebraicIntermediateFinal<U, S extends UpdatableSummary<U>> extends EvalFunc<Tuple> { private final int sketchSize_; private final SummarySetOperations<S> summarySetOps_; private final SummaryDeserializer<S> summaryDeserializer_; private final UpdatableSketchBuilder<U, S> sketchBuilder_; private boolean isFirstCall_ = true; /** * Constructs a function given a summary factory, summary set operations, summary deserializer, * default sketch size and default sampling probability of 1. * @param summaryFactory an instance of SummaryFactory * @param summarySetOps an instance of SummarySetOperaions * @param summaryDeserializer an instance of SummaryDeserializer */ public DataToSketchAlgebraicIntermediateFinal(final SummaryFactory<S> summaryFactory, final SummarySetOperations<S> summarySetOps, final SummaryDeserializer<S> summaryDeserializer) { this(DEFAULT_NOMINAL_ENTRIES, 1f, summaryFactory, summarySetOps, summaryDeserializer); } /** * Constructs a function given a sketch size, summary factory, summary set operations, * summary deserializer and default sampling probability of 1. * @param sketchSize parameter controlling the size of the sketch and the accuracy. * It represents nominal number of entries in the sketch. Forced to the nearest power of 2 * greater than given value. * @param summaryFactory an instance of SummaryFactory * @param summarySetOps an instance of SummarySetOperaions * @param summaryDeserializer an instance of SummaryDeserializer */ public DataToSketchAlgebraicIntermediateFinal(final int sketchSize, final SummaryFactory<S> summaryFactory, final SummarySetOperations<S> summarySetOps, final SummaryDeserializer<S> summaryDeserializer) { this(sketchSize, 1f, summaryFactory, summarySetOps, summaryDeserializer); } /** * Constructs a function given a sketch size, sampling probability, summary factory, * summary set operations and summary deserializer * @param sketchSize parameter controlling the size of the sketch and the accuracy. * It represents nominal number of entries in the sketch. Forced to the nearest power of 2 * greater than given value. * @param samplingProbability parameter from 0 to 1 inclusive * @param summaryFactory an instance of SummaryFactory * @param summarySetOps an instance of SummarySetOperaions * @param summaryDeserializer an instance of SummaryDeserializer */ public DataToSketchAlgebraicIntermediateFinal(final int sketchSize, final float samplingProbability, final SummaryFactory<S> summaryFactory, final SummarySetOperations<S> summarySetOps, final SummaryDeserializer<S> summaryDeserializer) { this.sketchSize_ = sketchSize; this.summarySetOps_ = summarySetOps; this.summaryDeserializer_ = summaryDeserializer; this.sketchBuilder_ = new UpdatableSketchBuilder<>(summaryFactory) .setNominalEntries(sketchSize).setSamplingProbability(samplingProbability); } @Override public Tuple exec(final Tuple inputTuple) throws IOException { if (this.isFirstCall_) { // this is to see in the log which way was used by Pig Logger.getLogger(getClass()).info("algebraic is used"); this.isFirstCall_ = false; } final Union<S> union = new Union<>(this.sketchSize_, this.summarySetOps_); final DataBag bag = (DataBag) inputTuple.get(0); if (bag == null) { throw new IllegalArgumentException("InputTuple.Field0: Bag may not be null"); } for (final Tuple dataTuple: bag) { final Object item = dataTuple.get(0); if (item instanceof DataBag) { // this is a bag from the Initial function. // just insert each item of the tuple into the sketch final UpdatableSketch<U, S> sketch = this.sketchBuilder_.build(); DataToSketch.updateSketch((DataBag) item, sketch); union.union(sketch); } else if (item instanceof DataByteArray) { // This is a sketch from a prior call to the // Intermediate function. merge it with the // current sketch. final Sketch<S> incomingSketch = Util.deserializeSketchFromTuple(dataTuple, this.summaryDeserializer_); union.union(incomingSketch); } else { // we should never get here. throw new IllegalArgumentException( "InputTuple.Field0: Bag contains unrecognized types: " + item.getClass().getName()); } } return Util.tupleFactory.newTuple(new DataByteArray(union.getResult().toByteArray())); } }
5,796
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/DoubleSummarySketchToEstimates.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.pig.tuple; import java.io.IOException; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.tuple.Sketch; import org.apache.datasketches.tuple.SketchIterator; import org.apache.datasketches.tuple.Sketches; import org.apache.datasketches.tuple.SummaryDeserializer; import org.apache.datasketches.tuple.adouble.DoubleSummary; import org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; /** * This UDF converts a Sketch&lt;DoubleSummary&gt; to estimates. * The first estimate is the estimate of the number of unique * keys in the original population. * The second is the estimate of the sum of the parameter * in the original population (sums of the values in the sketch * scaled to the original population). This estimate assumes * that the DoubleSummary was used in the Sum mode. */ public class DoubleSummarySketchToEstimates extends EvalFunc<Tuple> { private static final SummaryDeserializer<DoubleSummary> SUMMARY_DESERIALIZER = new DoubleSummaryDeserializer(); @Override public Tuple exec(final Tuple input) throws IOException { if ((input == null) || (input.size() == 0)) { return null; } final DataByteArray dba = (DataByteArray) input.get(0); final Sketch<DoubleSummary> sketch = Sketches.heapifySketch( Memory.wrap(dba.get()), SUMMARY_DESERIALIZER); final Tuple output = TupleFactory.getInstance().newTuple(2); output.set(0, sketch.getEstimate()); double sum = 0; final SketchIterator<DoubleSummary> it = sketch.iterator(); while (it.next()) { sum += it.getSummary().getValue(); } output.set(1, sum / sketch.getTheta()); return output; } }
5,797
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/ArrayOfDoublesSketchToEstimates.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.pig.tuple; import java.io.IOException; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator; import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketches; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; /** * This UDF converts an ArrayOfDoubles sketch to estimates. * The result will be a tuple with N + 1 double values, where * N is the number of double values kept in the sketch per key. * The first estimate is the estimate of the number of unique * keys in the original population. * Next there are N estimates of the sums of the parameters * in the original population (sums of the values in the sketch * scaled to the original population). */ public class ArrayOfDoublesSketchToEstimates extends EvalFunc<Tuple> { @Override public Tuple exec(final Tuple input) throws IOException { if (input == null || input.size() == 0) { return null; } final DataByteArray dba = (DataByteArray) input.get(0); final ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dba.get())); final double[] estimates = new double[sketch.getNumValues() + 1]; estimates[0] = sketch.getEstimate(); if (sketch.getRetainedEntries() > 0) { // remove unnecessary check when version of sketches-core > 0.4.0 final ArrayOfDoublesSketchIterator it = sketch.iterator(); while (it.next()) { final double[] values = it.getValues(); for (int i = 0; i < sketch.getNumValues(); i++) { estimates[i + 1] += values[i]; } } for (int i = 0; i < sketch.getNumValues(); i++) { estimates[i + 1] /= sketch.getTheta(); } } return Util.doubleArrayToTuple(estimates); } }
5,798
0
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig
Create_ds/datasketches-pig/src/main/java/org/apache/datasketches/pig/tuple/DataToDoubleSummarySketch.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.pig.tuple; import org.apache.datasketches.tuple.adouble.DoubleSummary; import org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer; import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; import org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations; import org.apache.pig.Algebraic; /** * This UDF creates a Sketch&lt;DoubleSummary&gt; from raw data. * It supports all three ways: exec(), Accumulator and Algebraic. */ @SuppressWarnings("javadoc") public class DataToDoubleSummarySketch extends DataToSketch<Double, DoubleSummary> implements Algebraic { /** * Constructor with default sketch size and default mode (sum) */ public DataToDoubleSummarySketch() { super(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)); } /** * Constructor with default mode (sum) * @param sketchSize String representation of sketch size */ public DataToDoubleSummarySketch(final String sketchSize) { super(Integer.parseInt(sketchSize), new DoubleSummaryFactory(DoubleSummary.Mode.Sum)); } /** * Constructor * @param sketchSize String representation of sketch size * @param summaryMode String representation of mode (sum, min or max) */ public DataToDoubleSummarySketch(final String sketchSize, final String summaryMode) { super(Integer.parseInt(sketchSize), new DoubleSummaryFactory(DoubleSummary.Mode.valueOf(summaryMode))); } @Override public String getInitial() { return Initial.class.getName(); } @Override public String getIntermed() { return IntermediateFinal.class.getName(); } @Override public String getFinal() { return IntermediateFinal.class.getName(); } public static class Initial extends AlgebraicInitial { /** * Constructor wit default sketch size and default mode */ public Initial() {} /** * Constructor for the initial pass of an Algebraic function. This will be passed the same * constructor arguments as the original UDF. * @param sketchSize String representation of sketch size */ public Initial(final String sketchSize) {} /** * Constructor for the initial pass of an Algebraic function. This will be passed the same * constructor arguments as the original UDF. * @param sketchSize String representation of sketch size * @param summaryMode String representation of mode (sum, min or max) */ public Initial(final String sketchSize, final String summaryMode) {} } public static class IntermediateFinal extends DataToSketchAlgebraicIntermediateFinal<Double, DoubleSummary> { /** * Constructor for the intermediate and final passes of an Algebraic function. * Default sketch size and default mode */ public IntermediateFinal() { super(new DoubleSummaryFactory(DoubleSummary.Mode.Sum), new DoubleSummarySetOperations(DoubleSummary.Mode.Sum), new DoubleSummaryDeserializer()); } /** * Constructor for the intermediate and final passes of an Algebraic function. This will be * passed the same constructor arguments as the original UDF. * @param sketchSize String representation of sketch size */ public IntermediateFinal(final String sketchSize) { super(Integer.parseInt(sketchSize), new DoubleSummaryFactory(DoubleSummary.Mode.Sum), new DoubleSummarySetOperations(DoubleSummary.Mode.Sum), new DoubleSummaryDeserializer()); } /** * Constructor for the intermediate and final passes of an Algebraic function. This will be * passed the same constructor arguments as the original UDF. * @param sketchSize String representation of sketch size * @param summaryMode String representation of mode (sum, min or max) */ public IntermediateFinal(final String sketchSize, final String summaryMode) { super(Integer.parseInt(sketchSize), new DoubleSummaryFactory(DoubleSummary.Mode.valueOf(summaryMode)), new DoubleSummarySetOperations(DoubleSummary.Mode.valueOf(summaryMode)), new DoubleSummaryDeserializer()); } } }
5,799