Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions assembly/Histogram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,14 @@ export default class Histogram<T, U> extends AbstractHistogramBase<T, U> {
}
}
for (; i < end; i++) {
if (!isFlatStorage<T>()) {
// Jump over the empty subtrees of the packed counts
i = this.nextNonZeroIndex(i);
if (i < 0 || i >= end) {
i = end;
break;
}
}
totalToCurrentIndex += this.getCountAtIndex(i);
if (totalToCurrentIndex >= countAtPercentile) break;
}
Expand Down Expand Up @@ -783,6 +791,25 @@ export default class Histogram<T, U> extends AbstractHistogramBase<T, U> {
return unchecked(<u64>this.counts[index]);
}

/**
* Lowest index >= fromIndex with a non-zero count, or -1 when there is none.
* A packed histogram skips the empty subtrees of its counts array, so the
* scans built on this cost time proportional to the populated indexes
* rather than to the counts array length.
*/
nextNonZeroIndex(fromIndex: i32): i32 {
if (idof<T>() == idof<PackedArray>()) {
return changetype<PackedArray>(this.counts).nextNonZeroIndex(fromIndex);
}
const length = this.countsArrayLength;
for (let i = fromIndex; i < length; i++) {
if (this.getCountAtIndex(i) != 0) {
return i;
}
}
return -1;
}

/** Address of counts[0] in linear memory. Only valid when isFlatStorage<T>(). */
@inline
get countsDataStart(): usize {
Expand Down Expand Up @@ -844,6 +871,13 @@ export default class Histogram<T, U> extends AbstractHistogramBase<T, U> {
observedOtherTotalCount += horizontalSum(acc);
}
for (; i < end; i++) {
if (!isFlatStorage<V>()) {
// Jump over the empty subtrees of the other packed counts
i = otherHistogram.nextNonZeroIndex(i);
if (i < 0 || i >= end) {
break;
}
}
const otherCount = otherHistogram.getCountAtIndex(i);
if (otherCount > 0) {
this.addToCountAtIndex(i, otherCount);
Expand Down Expand Up @@ -876,6 +910,13 @@ export default class Histogram<T, U> extends AbstractHistogramBase<T, U> {
i < otherMaxIndex;
i = otherHistogram.nextCountsIndexToScan(i)
) {
if (!isFlatStorage<V>()) {
// Jump over the empty subtrees of the other packed counts
i = otherHistogram.nextNonZeroIndex(i);
if (i < 0 || i >= otherMaxIndex) {
break;
}
}
otherCount = otherHistogram.getCountAtIndex(i);
if (otherCount > 0) {
this.recordCountAtValue(otherCount, otherHistogram.valueFromIndex(i));
Expand Down Expand Up @@ -945,6 +986,13 @@ export default class Histogram<T, U> extends AbstractHistogramBase<T, U> {
}
}
for (; index < lengthToCover; index++) {
if (!isFlatStorage<T>()) {
// Jump over the empty subtrees of the packed counts
index = this.nextNonZeroIndex(index);
if (index < 0 || index >= lengthToCover) {
break;
}
}
const countAtIndex: u64 = this.getCountAtIndex(index);
if (countAtIndex > 0) {
observedTotalCount += countAtIndex;
Expand Down Expand Up @@ -1011,6 +1059,13 @@ export default class Histogram<T, U> extends AbstractHistogramBase<T, U> {
observedOtherTotalCount += horizontalSum(acc);
}
for (; i < end; i++) {
if (!isFlatStorage<V>()) {
// Jump over the empty subtrees of the other packed counts
i = otherHistogram.nextNonZeroIndex(i);
if (i < 0 || i >= end) {
break;
}
}
const otherCount = otherHistogram.getCountAtIndex(i);
if (otherCount > 0) {
this.addToCountAtIndex(i, -otherCount);
Expand All @@ -1025,6 +1080,13 @@ export default class Histogram<T, U> extends AbstractHistogramBase<T, U> {
i <= otherLastIndex;
i = otherHistogram.nextCountsIndexToScan(i)
) {
if (!isFlatStorage<V>()) {
// Jump over the empty subtrees of the other packed counts
i = otherHistogram.nextNonZeroIndex(i);
if (i < 0 || i > otherLastIndex) {
break;
}
}
const otherCount = otherHistogram.getCountAtIndex(i);
if (otherCount > 0) {
const otherValue = otherHistogram.valueFromIndex(i);
Expand Down
191 changes: 191 additions & 0 deletions assembly/__tests__/PackedArrayIteration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
/*
* Cross-checks PackedArray.nextNonZeroIndex (set-0 tree walk) against a brute
* force scan of a plain array model: sparse and dense contents, values whose
* low byte is zero, values set back to zero, resizes and the unpacked fallback.
*/

import { describe, test, expect } from "assemblyscript-unittest-framework/assembly";
import { PackedArray } from "../packedarray/PackedArray";

let seed: u32 = 4242;
function nextRandom(): u32 {
seed = seed * 1664525 + 1013904223;
return seed;
}

function bruteForceNext(model: StaticArray<u64>, fromIndex: i32): i32 {
for (let i = fromIndex; i < model.length; i++) {
if (model[i] != 0) return i;
}
return -1;
}

/**
* Number of disagreements between the walk and the model: first a full walk
* from index 0, then lookups from random start indexes (including past the end).
*/
function mismatches(packed: PackedArray, model: StaticArray<u64>): i32 {
let count = 0;
let index = packed.nextNonZeroIndex(0);
let expected = bruteForceNext(model, 0);
while (expected >= 0) {
if (index != expected) count++;
if (index < 0) break;
index = packed.nextNonZeroIndex(index + 1);
expected = bruteForceNext(model, expected + 1);
}
if (index != -1) count++;
for (let n = 0; n < 200; n++) {
const from = <i32>(nextRandom() % <u32>(model.length + 16));
if (packed.nextNonZeroIndex(from) != bruteForceNext(model, from)) count++;
}
return count;
}

describe("Packed Array non-zero iteration", () => {
test("should find no non-zero index in an empty array", () => {
// given
const packed = new PackedArray(100000);
// when
const fromStart = packed.nextNonZeroIndex(0);
const fromLastIndex = packed.nextNonZeroIndex(99999);
const fromEnd = packed.nextNonZeroIndex(100000);
// then
expect<i32>(fromStart).equal(-1);
expect<i32>(fromLastIndex).equal(-1);
expect<i32>(fromEnd).equal(-1);
});

test("should walk a sparse array", () => {
// given
const length = 100000;
const packed = new PackedArray(length);
const model = new StaticArray<u64>(length);
for (let n = 0; n < 300; n++) {
const i = <i32>(nextRandom() % <u32>length);
const v = <u64>(1 + (nextRandom() % 1000));
packed.add(i, v);
model[i] += v;
}
// when
const count = mismatches(packed, model);
// then
expect<i32>(count).equal(0);
});

test("should find values whose low byte is zero", () => {
// given
const packed = new PackedArray(4096);
const model = new StaticArray<u64>(4096);
packed.set(300, 256);
model[300] = 256;
packed.set(2000, 0x10000);
model[2000] = 0x10000;
packed.set(4095, 0x0100000000000000);
model[4095] = 0x0100000000000000;
// when
const first = packed.nextNonZeroIndex(0);
const second = packed.nextNonZeroIndex(301);
const third = packed.nextNonZeroIndex(2001);
const count = mismatches(packed, model);
// then
expect<i32>(first).equal(300);
expect<i32>(second).equal(2000);
expect<i32>(third).equal(4095);
expect<i32>(count).equal(0);
});

test("should walk a dense array", () => {
// given
const length = 4096;
const packed = new PackedArray(length);
const model = new StaticArray<u64>(length);
for (let i = 0; i < length; i++) {
const v = <u64>(nextRandom() % 100000);
packed.set(i, v);
model[i] = v;
}
// when
const count = mismatches(packed, model);
// then
expect<i32>(count).equal(0);
});

test("should skip values set back to zero, leaving their leaf in place", () => {
// given
const length = 20000;
const packed = new PackedArray(length);
const model = new StaticArray<u64>(length);
for (let n = 0; n < 500; n++) {
const i = <i32>(nextRandom() % <u32>length);
const v = <u64>(1 + (nextRandom() % 100000));
packed.set(i, v);
model[i] = v;
}
// when
for (let i = 0; i < length; i++) {
if (model[i] != 0 && nextRandom() % 2 == 0) {
packed.set(i, 0);
model[i] = 0;
}
}
const count = mismatches(packed, model);
// then
expect<i32>(count).equal(0);
});

test("should walk the whole array after a resize", () => {
// given
const packed = new PackedArray(256, 16);
const model = new StaticArray<u64>(100000);
for (let i = 0; i < 256; i += 5) {
const v = <u64>(1 + (nextRandom() % 1000000));
packed.set(i, v);
model[i] = v;
}
packed.resize(100000);
// when
for (let n = 0; n < 200; n++) {
const i = <i32>(nextRandom() % 100000);
const v = <u64>(1 + (nextRandom() % 1000000));
packed.add(i, v);
model[i] += v;
}
const count = mismatches(packed, model);
// then
expect<i32>(count).equal(0);
});

test("should scan linearly once the array is unpacked", () => {
// 64 bit values at every index outgrow the packed representation
// given
const length = 5000;
const packed = new PackedArray(length);
const model = new StaticArray<u64>(length);
for (let i = 0; i < length; i++) {
packed.set(i, u64.MAX_VALUE - i);
model[i] = u64.MAX_VALUE - i;
}
for (let i = 0; i < length; i++) {
if (nextRandom() % 4 != 0) {
packed.set(i, 0);
model[i] = 0;
}
}
// when
const countBeforeResize = mismatches(packed, model);
// then
expect<i32>(countBeforeResize).equal(0);

// given
packed.resize(6000);
const grown = new StaticArray<u64>(6000);
for (let i = 0; i < length; i++) grown[i] = model[i];
packed.set(5999, 7);
grown[5999] = 7;
// when
const countAfterResize = mismatches(packed, grown);
// then
expect<i32>(countAfterResize).equal(0);
});
});
12 changes: 7 additions & 5 deletions assembly/encoding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,13 @@ function fillBufferFromCountsArray<T, U>(
// Count trailing 0s (which follow this count):
let zerosCount = 0;
if (count == 0) {
zerosCount = 1;
while (srcIndex < countsLimit && self.getCountAtIndex(srcIndex) == 0) {
zerosCount++;
srcIndex++;
}
// The run of zeros extends to the next non-zero count (or to the limit);
// a packed histogram finds it without visiting every empty index.
const nextNonZeroIndex = self.nextNonZeroIndex(srcIndex);
const zerosEnd =
nextNonZeroIndex < 0 ? countsLimit : min(nextNonZeroIndex, countsLimit);
zerosCount = 1 + zerosEnd - srcIndex;
srcIndex = zerosEnd;
}
if (zerosCount > 1) {
ZigZagEncoding.encode(buffer, -zerosCount);
Expand Down
36 changes: 36 additions & 0 deletions assembly/packedarray/PackedArray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,42 @@ export class PackedArray {
}
}

/**
* Lowest index >= fromIndex holding a non-zero value, or -1 when there is none.
*
* On a packed context the set-0 tree is walked to skip the groups of 8
* indexes that were never populated, so a scan over the whole array costs
* time proportional to the populated groups rather than to the virtual
* length. An unpacked context is scanned linearly.
*/
nextNonZeroIndex(fromIndex: i32): i32 {
const arrayContext = this.arrayContext;
const length = arrayContext.getVirtualLength();
let index = fromIndex;
if (!arrayContext.isPacked) {
for (; index < length; index++) {
if (arrayContext.getAtUnpackedIndex(index) != 0) {
return index;
}
}
return -1;
}
while (index < length) {
index = arrayContext.nextIndexWithLeaf(index);
if (index < 0) {
return -1;
}
// The leaf found only vouches for the group of 8 indexes holding index
const groupEnd = min<i32>((index | 0x7) + 1, length);
for (; index < groupEnd; index++) {
if (this.get(index) != 0) {
return index;
}
}
}
return -1;
}

/**
* Move the contents to a new unpacked context of the given virtual length,
* once the packed representation cannot grow any further
Expand Down
Loading
Loading