Search in sources :

Example 6 with SketchesArgumentException

use of org.apache.datasketches.SketchesArgumentException in project sketches-core by DataSketches.

the class PreambleUtilTest method checkCorruptMemoryInput.

@SuppressWarnings("unused")
@Test
public void checkCorruptMemoryInput() {
    HllSketch sk = new HllSketch(12);
    byte[] memObj = sk.toCompactByteArray();
    WritableMemory wmem = WritableMemory.writableWrap(memObj);
    long memAdd = wmem.getCumulativeOffset(0);
    HllSketch bad;
    // checkFamily
    try {
        // corrupt, should be 7
        wmem.putByte(FAMILY_BYTE, (byte) 0);
        bad = HllSketch.heapify(wmem);
        fail();
    } catch (SketchesArgumentException e) {
    /* OK */
    }
    // corrected
    insertFamilyId(wmem);
    // check SerVer
    try {
        // corrupt, should be 1
        wmem.putByte(SER_VER_BYTE, (byte) 0);
        bad = HllSketch.heapify(wmem);
        fail();
    } catch (SketchesArgumentException e) {
    /* OK */
    }
    // corrected
    insertSerVer(wmem);
    // check bad PreInts
    try {
        // corrupt, should be 2
        insertPreInts(wmem, 0);
        bad = HllSketch.heapify(wmem);
        fail();
    } catch (SketchesArgumentException e) {
    /* OK */
    }
    // corrected
    insertPreInts(wmem, 2);
    // check wrong PreInts and LIST
    try {
        // corrupt, should be 2
        insertPreInts(wmem, 3);
        bad = HllSketch.heapify(wmem);
        fail();
    } catch (SketchesArgumentException e) {
    /* OK */
    }
    // corrected
    insertPreInts(wmem, 2);
    // move to Set mode
    for (int i = 1; i <= 15; i++) {
        sk.update(i);
    }
    memObj = sk.toCompactByteArray();
    wmem = WritableMemory.writableWrap(memObj);
    memAdd = wmem.getCumulativeOffset(0);
    // check wrong PreInts and SET
    try {
        // corrupt, should be 3
        insertPreInts(wmem, 2);
        bad = HllSketch.heapify(wmem);
        fail();
    } catch (SketchesArgumentException e) {
    /* OK */
    }
    // corrected
    insertPreInts(wmem, 3);
    // move to HLL mode
    for (int i = 15; i <= 1000; i++) {
        sk.update(i);
    }
    memObj = sk.toCompactByteArray();
    wmem = WritableMemory.writableWrap(memObj);
    memAdd = wmem.getCumulativeOffset(0);
    // check wrong PreInts and HLL
    try {
        // corrupt, should be 10
        insertPreInts(wmem, 2);
        bad = HllSketch.heapify(wmem);
        fail();
    } catch (SketchesArgumentException e) {
    /* OK */
    }
    // corrected
    insertPreInts(wmem, 10);
}
Also used : SketchesArgumentException(org.apache.datasketches.SketchesArgumentException) WritableMemory(org.apache.datasketches.memory.WritableMemory) Test(org.testng.annotations.Test)

Example 7 with SketchesArgumentException

use of org.apache.datasketches.SketchesArgumentException in project sketches-core by DataSketches.

the class PreambleUtil method preambleToString.

/**
 * Returns a human readable string summary of the preamble state of the given Memory.
 * Note: other than making sure that the given Memory size is large
 * enough for just the preamble, this does not do much value checking of the contents of the
 * preamble as this is primarily a tool for debugging the preamble visually.
 *
 * @param mem the given Memory.
 * @return the summary preamble string.
 */
static String preambleToString(final Memory mem) {
    // make sure we can get the assumed preamble
    final int preLongs = getAndCheckPreLongs(mem);
    final Family family = Family.idToFamily(mem.getByte(FAMILY_BYTE));
    switch(family) {
        case RESERVOIR:
        case VAROPT:
            return sketchPreambleToString(mem, family, preLongs);
        case RESERVOIR_UNION:
        case VAROPT_UNION:
            return unionPreambleToString(mem, family, preLongs);
        default:
            throw new SketchesArgumentException("Inspecting preamble with Sampling family's " + "PreambleUtil with object of family " + family.getFamilyName());
    }
}
Also used : SketchesArgumentException(org.apache.datasketches.SketchesArgumentException) Family(org.apache.datasketches.Family)

Example 8 with SketchesArgumentException

use of org.apache.datasketches.SketchesArgumentException in project sketches-core by DataSketches.

the class ReservoirItemsSketch method heapify.

/**
 * Returns a sketch instance of this class from the given srcMem,
 * which must be a Memory representation of this sketch class.
 *
 * @param <T>    The type of item this sketch contains
 * @param srcMem a Memory representation of a sketch of this class.
 *               <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
 * @param serDe  An instance of ArrayOfItemsSerDe
 * @return a sketch instance of this class
 */
public static <T> ReservoirItemsSketch<T> heapify(final Memory srcMem, final ArrayOfItemsSerDe<T> serDe) {
    Family.RESERVOIR.checkFamilyID(srcMem.getByte(FAMILY_BYTE));
    final int numPreLongs = extractPreLongs(srcMem);
    final ResizeFactor rf = ResizeFactor.getRF(extractResizeFactor(srcMem));
    final int serVer = extractSerVer(srcMem);
    final boolean isEmpty = (extractFlags(srcMem) & EMPTY_FLAG_MASK) != 0;
    final long itemsSeen = (isEmpty ? 0 : extractN(srcMem));
    int k = extractK(srcMem);
    // Check values
    final boolean preLongsEqMin = (numPreLongs == Family.RESERVOIR.getMinPreLongs());
    final boolean preLongsEqMax = (numPreLongs == Family.RESERVOIR.getMaxPreLongs());
    if (!preLongsEqMin & !preLongsEqMax) {
        throw new SketchesArgumentException("Possible corruption: Non-empty sketch with only " + Family.RESERVOIR.getMinPreLongs() + " preLong(s)");
    }
    if (serVer != SER_VER) {
        if (serVer == 1) {
            final short encK = extractEncodedReservoirSize(srcMem);
            k = ReservoirSize.decodeValue(encK);
        } else {
            throw new SketchesArgumentException("Possible Corruption: Ser Ver must be " + SER_VER + ": " + serVer);
        }
    }
    if (isEmpty) {
        return new ReservoirItemsSketch<>(k, rf);
    }
    final int preLongBytes = numPreLongs << 3;
    // default to full reservoir
    int allocatedItems = k;
    if (itemsSeen < k) {
        // under-full so determine size to allocate, using ceilingLog2(totalSeen) as minimum
        // casts to int are safe since under-full
        final int ceilingLgK = Util.toLog2(Util.ceilingPowerOf2(k), "heapify");
        final int minLgSize = Util.toLog2(Util.ceilingPowerOf2((int) itemsSeen), "heapify");
        final int initialLgSize = SamplingUtil.startingSubMultiple(ceilingLgK, rf.lg(), Math.max(minLgSize, MIN_LG_ARR_ITEMS));
        allocatedItems = SamplingUtil.getAdjustedSize(k, 1 << initialLgSize);
    }
    final int itemsToRead = (int) Math.min(k, itemsSeen);
    final T[] data = serDe.deserializeFromMemory(srcMem.region(preLongBytes, srcMem.getCapacity() - preLongBytes), itemsToRead);
    final ArrayList<T> dataList = new ArrayList<>(Arrays.asList(data));
    final ReservoirItemsSketch<T> ris = new ReservoirItemsSketch<>(dataList, itemsSeen, rf, k);
    ris.data_.ensureCapacity(allocatedItems);
    ris.currItemsAlloc_ = allocatedItems;
    return ris;
}
Also used : SketchesArgumentException(org.apache.datasketches.SketchesArgumentException) ArrayList(java.util.ArrayList) PreambleUtil.extractResizeFactor(org.apache.datasketches.sampling.PreambleUtil.extractResizeFactor) ResizeFactor(org.apache.datasketches.ResizeFactor)

Example 9 with SketchesArgumentException

use of org.apache.datasketches.SketchesArgumentException in project sketches-core by DataSketches.

the class ReservoirLongsSketch method heapify.

/**
 * Returns a sketch instance of this class from the given srcMem, which must be a Memory
 * representation of this sketch class.
 *
 * @param srcMem a Memory representation of a sketch of this class. <a href=
 *        "{@docRoot}/resources/dictionary.html#mem">See Memory</a>
 * @return a sketch instance of this class
 */
public static ReservoirLongsSketch heapify(final Memory srcMem) {
    Family.RESERVOIR.checkFamilyID(srcMem.getByte(FAMILY_BYTE));
    final int numPreLongs = extractPreLongs(srcMem);
    final ResizeFactor rf = ResizeFactor.getRF(extractResizeFactor(srcMem));
    final int serVer = extractSerVer(srcMem);
    final boolean isEmpty = (extractFlags(srcMem) & EMPTY_FLAG_MASK) != 0;
    final long itemsSeen = (isEmpty ? 0 : extractN(srcMem));
    int k = extractK(srcMem);
    // Check values
    final boolean preLongsEqMin = (numPreLongs == Family.RESERVOIR.getMinPreLongs());
    final boolean preLongsEqMax = (numPreLongs == Family.RESERVOIR.getMaxPreLongs());
    if (!preLongsEqMin & !preLongsEqMax) {
        throw new SketchesArgumentException("Possible corruption: Non-empty sketch with only " + Family.RESERVOIR.getMinPreLongs() + "preLongs");
    }
    if (serVer != SER_VER) {
        if (serVer == 1) {
            final short encK = extractEncodedReservoirSize(srcMem);
            k = ReservoirSize.decodeValue(encK);
        } else {
            throw new SketchesArgumentException("Possible Corruption: Ser Ver must be " + SER_VER + ": " + serVer);
        }
    }
    if (isEmpty) {
        return new ReservoirLongsSketch(k, rf);
    }
    final int preLongBytes = numPreLongs << 3;
    final int numSketchLongs = (int) Math.min(itemsSeen, k);
    // default to full reservoir
    int allocatedSize = k;
    if (itemsSeen < k) {
        // under-full so determine size to allocate, using ceilingLog2(totalSeen) as minimum
        // casts to int are safe since under-full
        final int ceilingLgK = Util.toLog2(Util.ceilingPowerOf2(k), "heapify");
        final int minLgSize = Util.toLog2(Util.ceilingPowerOf2((int) itemsSeen), "heapify");
        final int initialLgSize = SamplingUtil.startingSubMultiple(ceilingLgK, rf.lg(), Math.max(minLgSize, MIN_LG_ARR_LONGS));
        allocatedSize = SamplingUtil.getAdjustedSize(k, 1 << initialLgSize);
    }
    final long[] data = new long[allocatedSize];
    srcMem.getLongArray(preLongBytes, data, 0, numSketchLongs);
    return new ReservoirLongsSketch(data, itemsSeen, rf, k);
}
Also used : SketchesArgumentException(org.apache.datasketches.SketchesArgumentException) PreambleUtil.extractResizeFactor(org.apache.datasketches.sampling.PreambleUtil.extractResizeFactor) ResizeFactor(org.apache.datasketches.ResizeFactor)

Example 10 with SketchesArgumentException

use of org.apache.datasketches.SketchesArgumentException in project sketches-core by DataSketches.

the class VarOptItemsSketch method heapify.

/**
 * Returns a sketch instance of this class from the given srcMem,
 * which must be a Memory representation of this sketch class.
 *
 * @param <T>    The type of item this sketch contains
 * @param srcMem a Memory representation of a sketch of this class.
 *               <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
 * @param serDe  An instance of ArrayOfItemsSerDe
 * @return a sketch instance of this class
 */
@SuppressWarnings("null")
public static <T> VarOptItemsSketch<T> heapify(final Memory srcMem, final ArrayOfItemsSerDe<T> serDe) {
    final int numPreLongs = getAndCheckPreLongs(srcMem);
    final ResizeFactor rf = ResizeFactor.getRF(extractResizeFactor(srcMem));
    final int serVer = extractSerVer(srcMem);
    final int familyId = extractFamilyID(srcMem);
    final int flags = extractFlags(srcMem);
    final boolean isEmpty = (flags & EMPTY_FLAG_MASK) != 0;
    final boolean isGadget = (flags & GADGET_FLAG_MASK) != 0;
    // Check values
    if (isEmpty) {
        if (numPreLongs != VO_PRELONGS_EMPTY) {
            throw new SketchesArgumentException("Possible corruption: Must be " + VO_PRELONGS_EMPTY + " for an empty sketch. Found: " + numPreLongs);
        }
    } else {
        if ((numPreLongs != VO_PRELONGS_WARMUP) && (numPreLongs != VO_PRELONGS_FULL)) {
            throw new SketchesArgumentException("Possible corruption: Must be " + VO_PRELONGS_WARMUP + " or " + VO_PRELONGS_FULL + " for a non-empty sketch. Found: " + numPreLongs);
        }
    }
    if (serVer != SER_VER) {
        throw new SketchesArgumentException("Possible Corruption: Ser Ver must be " + SER_VER + ": " + serVer);
    }
    final int reqFamilyId = Family.VAROPT.getID();
    if (familyId != reqFamilyId) {
        throw new SketchesArgumentException("Possible Corruption: FamilyID must be " + reqFamilyId + ": " + familyId);
    }
    final int k = extractK(srcMem);
    if (k < 1) {
        throw new SketchesArgumentException("Possible Corruption: k must be at least 1: " + k);
    }
    if (isEmpty) {
        assert numPreLongs == Family.VAROPT.getMinPreLongs();
        return new VarOptItemsSketch<>(k, rf);
    }
    final long n = extractN(srcMem);
    if (n < 0) {
        throw new SketchesArgumentException("Possible Corruption: n cannot be negative: " + n);
    }
    // get rest of preamble
    final int hCount = extractHRegionItemCount(srcMem);
    final int rCount = extractRRegionItemCount(srcMem);
    if (hCount < 0) {
        throw new SketchesArgumentException("Possible Corruption: H region count cannot be " + "negative: " + hCount);
    }
    if (rCount < 0) {
        throw new SketchesArgumentException("Possible Corruption: R region count cannot be " + "negative: " + rCount);
    }
    double totalRWeight = 0.0;
    if (numPreLongs == Family.VAROPT.getMaxPreLongs()) {
        if (rCount > 0) {
            totalRWeight = extractTotalRWeight(srcMem);
        } else {
            throw new SketchesArgumentException("Possible Corruption: " + Family.VAROPT.getMaxPreLongs() + " preLongs but no items in R region");
        }
    }
    final int preLongBytes = numPreLongs << 3;
    final int totalItems = hCount + rCount;
    // default to full
    int allocatedItems = k + 1;
    if (rCount == 0) {
        // Not in sampling mode, so determine size to allocate, using ceilingLog2(hCount) as minimum
        final int ceilingLgK = Util.toLog2(Util.ceilingPowerOf2(k), "heapify");
        final int minLgSize = Util.toLog2(Util.ceilingPowerOf2(hCount), "heapify");
        final int initialLgSize = SamplingUtil.startingSubMultiple(ceilingLgK, rf.lg(), Math.max(minLgSize, MIN_LG_ARR_ITEMS));
        allocatedItems = SamplingUtil.getAdjustedSize(k, 1 << initialLgSize);
        if (allocatedItems == k) {
            ++allocatedItems;
        }
    }
    // allocate full-sized ArrayLists, but we store only hCount weights at any moment
    final long weightOffsetBytes = TOTAL_WEIGHT_R_DOUBLE + (rCount > 0 ? Double.BYTES : 0);
    final ArrayList<Double> weightList = new ArrayList<>(allocatedItems);
    final double[] wts = new double[allocatedItems];
    srcMem.getDoubleArray(weightOffsetBytes, wts, 0, hCount);
    // can't use Arrays.asList(wts) since double[] rather than Double[]
    for (int i = 0; i < hCount; ++i) {
        if (wts[i] <= 0.0) {
            throw new SketchesArgumentException("Possible Corruption: " + "Non-positive weight in heapify(): " + wts[i]);
        }
        weightList.add(wts[i]);
    }
    // marks, if we have a gadget
    long markBytes = 0;
    int markCount = 0;
    ArrayList<Boolean> markList = null;
    if (isGadget) {
        final long markOffsetBytes = preLongBytes + ((long) hCount * Double.BYTES);
        markBytes = ArrayOfBooleansSerDe.computeBytesNeeded(hCount);
        markList = new ArrayList<>(allocatedItems);
        final ArrayOfBooleansSerDe booleansSerDe = new ArrayOfBooleansSerDe();
        final Boolean[] markArray = booleansSerDe.deserializeFromMemory(srcMem.region(markOffsetBytes, (hCount >>> 3) + 1), hCount);
        for (Boolean mark : markArray) {
            if (mark) {
                ++markCount;
            }
        }
        markList.addAll(Arrays.asList(markArray));
    }
    final long offsetBytes = preLongBytes + ((long) hCount * Double.BYTES) + markBytes;
    final T[] data = serDe.deserializeFromMemory(srcMem.region(offsetBytes, srcMem.getCapacity() - offsetBytes), totalItems);
    final List<T> wrappedData = Arrays.asList(data);
    final ArrayList<T> dataList = new ArrayList<>(allocatedItems);
    dataList.addAll(wrappedData.subList(0, hCount));
    // Load items in R as needed
    if (rCount > 0) {
        // the gap
        weightList.add(-1.0);
        // the gap
        if (isGadget) {
            markList.add(false);
        }
        for (int i = 0; i < rCount; ++i) {
            weightList.add(-1.0);
            if (isGadget) {
                markList.add(false);
            }
        }
        // the gap
        dataList.add(null);
        dataList.addAll(wrappedData.subList(hCount, totalItems));
    }
    final VarOptItemsSketch<T> sketch = new VarOptItemsSketch<>(dataList, weightList, k, n, allocatedItems, rf, hCount, rCount, totalRWeight);
    if (isGadget) {
        sketch.marks_ = markList;
        sketch.numMarksInH_ = markCount;
    }
    return sketch;
}
Also used : ArrayOfBooleansSerDe(org.apache.datasketches.ArrayOfBooleansSerDe) ArrayList(java.util.ArrayList) PreambleUtil.extractResizeFactor(org.apache.datasketches.sampling.PreambleUtil.extractResizeFactor) ResizeFactor(org.apache.datasketches.ResizeFactor) SketchesArgumentException(org.apache.datasketches.SketchesArgumentException)

Aggregations

SketchesArgumentException (org.apache.datasketches.SketchesArgumentException)64 WritableMemory (org.apache.datasketches.memory.WritableMemory)38 Test (org.testng.annotations.Test)29 Family (org.apache.datasketches.Family)14 Memory (org.apache.datasketches.memory.Memory)13 Family.idToFamily (org.apache.datasketches.Family.idToFamily)10 SketchesReadOnlyException (org.apache.datasketches.SketchesReadOnlyException)7 WritableHandle (org.apache.datasketches.memory.WritableHandle)6 ResizeFactor (org.apache.datasketches.ResizeFactor)5 ArrayOfLongsSerDe (org.apache.datasketches.ArrayOfLongsSerDe)4 AnotbAction (org.apache.datasketches.SetOperationCornerCases.AnotbAction)3 CornerCase (org.apache.datasketches.SetOperationCornerCases.CornerCase)3 PreambleUtil.extractResizeFactor (org.apache.datasketches.sampling.PreambleUtil.extractResizeFactor)3 ArrayList (java.util.ArrayList)2 SketchesStateException (org.apache.datasketches.SketchesStateException)2 PreambleUtil.insertLgResizeFactor (org.apache.datasketches.theta.PreambleUtil.insertLgResizeFactor)2 UpdateSketch (org.apache.datasketches.theta.UpdateSketch)2 UpdateSketchBuilder (org.apache.datasketches.theta.UpdateSketchBuilder)2 BigDecimal (java.math.BigDecimal)1 ArrayOfBooleansSerDe (org.apache.datasketches.ArrayOfBooleansSerDe)1