Public
Edited
Jul 8, 2024
2 forks
42 stars
Topological subsamplingUnion-Find
Time series topological subsampling
Also listed in…
Algorithms
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
series = Plot.valueof(aapl, "Close")
Insert cell
features = topoline(series)
Insert cell
index = [
...d3.sort(
new Set([
0,
...d3
.sort(features, (d) => -d[sortby])
.filter((d) => d.persistence >= persistence)
.slice(0, numfeatures)
.flatMap(({ low, high }) => [low, high])
.filter((d) => d !== undefined),
series.length - 1
])
)
]
Insert cell
labelsHigh = d3
.sort(features, (d) => -d["error"])
.slice(0, numlabels >> 1)
.map(({ high }) => high)
.filter((d) => d !== undefined)
Insert cell
labelsLow = d3
.sort(features, (d) => -d["error"])
.slice(0, numlabels >> 1)
.map(({ low }) => low)
.filter((d) => d !== undefined)
Insert cell
topoline = function (series) {
const E_insert = 0;
const E_left = 1;
const E_right = 2;
const E_merge = 3;

const n = series.length;
const tree = new Int32Array(n).fill(-1);
const features = [];
let k = 0;
const order = d3.sort(
d3.range(0, tree.length),
(i) => series[i],
(i) => i
);

let event;
for (const i of order) {
const left = tree[i - 1] ?? tree[i];
const right = tree[i + 1] ?? tree[i];

if (left === -1 && right === -1) {
// insert leaf
tree[i] = i;
event = E_insert;
} else if (left === -1) {
tree[i] = right;
event = E_right;
} else if (right === -1) {
tree[i] = left;
event = E_left;
} else {
// merge node
let [a, b] = d3.sort(
[tree[left], tree[right]],
(i) => series[i],
(i) => i
);
if (i === order[order.length - 1]) b = a;
features.push({
low: b,
high: i,
persistence: series[i] - series[b],
error: error(b, i)
});
for (let j = i - 1; tree[j] === b; j--) tree[j] = a;
for (let j = i + 1; tree[j] === b; j++) tree[j] = a;
tree[i] = a;
event = E_merge;
}
k++;
}

// 🌶 ensure we have global min and max: if we didn't end on a merge event,
// it means that the maximum value was reached either on the left or on the right
if (event === E_left || event === E_right) {
const low = order[0];
const high = order.pop();
features.push({
low,
high,
persistence: series[high] - series[low],
error: error(low, high)
});
}

return d3.sort(features, (d) => -d.persistence);

function error(b, i) {
return d3.sum(d3.range(...d3.extent([i, b])), (k) =>
Math.abs(
(series[b] - series[i]) * ((k - i) / (b - i)) - (series[k] - series[i])
)
);
}
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more