Public
Edited
Dec 14, 2022
Importers
16 stars
Chandrupatla’s root-finding methodSidi’s root-finding methodRegular numbersDruidJS workerNatural breaksDistance to a segmentRay out of a convex hullWord Tour: 40k words and their friendsHello, @thi.ng/grid-iteratorsHead/tail breaksPseudo-blue noise shaderHow fast does walk-on-spheres converge?AoC 12: shortest path under constraintsKDE estimationPlot: Correlation heatmapPoisson Finish 2Poisson disk sampling functionsWoS with transportSimple and surprising sortLocal medianTime series topological subsamplingUnion-FindLevel set experiment 1Mean value coordinatesPoisson potentialMiddle-squareWorld of squares (spherical)World of squaresLargest Inscribed SquareHello, PyWaveletsGeothmetic meandianHello, Reorder.jsGeometric MedianImage FFTTransport to a mapDisc TransportTP3: Power Diagram and Semi-Discrete Optimal TransportThe blue waveHello, genetic-jsSliced Optimal TransportDruidJSSelf-Organizing Maps meet DelaunayHello, polygon-clippingseedrandom, minimalWalk on Spheres 2Walk on SpheresHello, AutoencoderKaprekar’s numberVoronoiMap2DHello, ccwt.jsPolygon TriangulationQuantile.invert?Linear congruential generatorHue blurNeedle in a haystackMoving average blurApollo 11 implementation of trigonometric functions, by Margaret H. Hamilton (march 1969)2D curves intersectionThe 2D approximate Newton-Raphson methodInverting Lee’s Tetrahedral projectionLinde–Buzo–Gray stipplingMean shift clustering with kd-tree2D point distributionsShortest pathKahan SummationHello, delatinDijkstra’s algorithm in gpu.jsLloyd’s relaxation on a graphManhattan DiameterManhattan VoronoiMobility landscapes — an introduction
Dijkstra’s shortest-path tree
H3 odditiesProtein MatrixConvex Spectral WeightsSort stuff by similarityKrigingDelaunay.findTrianglen-dimensions binning?Travelling with a self-organizing mapUMAP-o-MaticMNIST & UMAP-jsHello UMAP-jsMean shift clusteringLevenshtein transitionRd quasi-random sequencesAutomated label placement (countries)Phyllotaxis explainedMotionrugsPlanar hull (Andrew’s monotone chain algorithm)South Africa’s medial axisTravelling salesperson approximation with t-SNEDistance to shoreWorkerngraph: pagerank, louvain…t-SNE VoronoiCloud ContoursCircular function drawingKruskal MazeMyceliumTravelling salesperson approximation on the globe, with t-SNEtsne.jstsne.js & worker
Also listed in…
Graphs
Hello
Insert cell
Insert cell
Insert cell
Insert cell
function* shortest_tree({ graph, origins, cutoff, step }) {
const start_time = performance.now(),
_step = step === undefined ? 0 : +step,
neigh = new Map();
let n = 0;

// populate a fast lookup Map of links indices for each source
for (let i = 0, l = graph.sources.length; i < l; i++) {
const a = +graph.sources[i],
b = +graph.targets[i];
if (!neigh.has(a)) neigh.set(a, []);
neigh.get(a).push(i);

// keep track of the highest node’s id
n = Math.max(n, a + 1, b + 1);
}

const q = new FlatQueue(),
front = q.ids,
cost = new Float64Array(n).fill(Infinity),
predecessor = new Int32Array(n).fill(-1),
origin = new Int32Array(n).fill(-1),
status = {
cost,
predecessor,
origin,
step: 0,
front,
max_front_size: 0,
ended: false
};

origins.forEach(node => {
if (isFinite(node)) node = { id: node, cost: 0 };
if (node.id < n) {
origin[node.id] = node.id;
q.push(node.id, (cost[node.id] = node.cost));
}
});

const time = performance.now();

while (q.length > 0) {
const curr = q.peekValue(),
node = q.pop();
if (curr > cost[node]) continue; // ignore obsolete elements

if (neigh.has(node)) {
for (const i of neigh.get(node)) {
const c = graph.costs ? +graph.costs[i] : 1;
if (!isFinite(c)) continue;

const tentative = c + cost[node];
if (tentative > cutoff) continue;

const dest = graph.targets[i];
if (tentative >= 0 && tentative < cost[dest]) {
predecessor[dest] = node;
origin[dest] = origin[node];
q.push(dest, (cost[dest] = tentative));
status.max_front_size = Math.max(status.max_front_size, front.length);
}
}
}

status.step++;
if (_step && status.step % _step === 0) {
status.performance = performance.now() - time;
yield status;
}
}

status.ended = true;
status.performance = performance.now() - time;
yield status;
}
Insert cell
Insert cell
function shortest_paths(graph, tree) {
const paths = [];
const P = shortest_junctions(graph, tree);

for (const code of P.costs.keys()) {
const cost = P.costs.get(code),
junction = P.junctions.get(code),
path = junction.slice();
path.reverse();
while (tree.predecessor[path[0]] > -1)
path.unshift(tree.predecessor[path[0]]);
path.reverse();
while (tree.predecessor[path[0]] > -1)
path.unshift(tree.predecessor[path[0]]);
paths.push({ cost, junction, path });
}

return paths;
}
Insert cell
// returns the shortest path that connects i to j:
// - without stepping into other origins’ zones
// - without going above cutoff in each origin’s zone
function shortest_path(graph, tree, i, j) {
const P = shortest_junctions(graph, tree);

let cost = Infinity,
junction = [],
path = [];

const code = `${i}-${j}`;

if (P.costs.has(code)) {
cost = P.costs.get(code);
junction = P.junctions.get(code);
path = junction.slice();
path.reverse();
while (tree.predecessor[path[0]] > -1)
path.unshift(tree.predecessor[path[0]]);
path.reverse();
while (tree.predecessor[path[0]] > -1)
path.unshift(tree.predecessor[path[0]]);
}

return { cost, junction, path };
}
Insert cell
// returns the junctions between zones
function shortest_junctions(graph, tree) {
const origins = [...new Set(tree.origin)].filter(i => i > -1);
let costs = new Map(),
junctions = new Map();

for (let l = 0; l < graph.sources.length; l++) {
const i = tree.origin[graph.sources[l]],
j = tree.origin[graph.targets[l]];
if (i !== j && i > -1 && j > -1) {
const code = `${i}-${j}`;
const c =
graph.costs[l] +
tree.cost[graph.sources[l]] +
tree.cost[graph.targets[l]];
if (!costs.has(code) || c < costs.get(code)) {
costs.set(code, c);
junctions.set(code, [graph.sources[l], graph.targets[l]]);
}
}
}

return { costs, junctions };
}
Insert cell
Insert cell
shortest_tree_async = async args =>
args.worker !== false
? Generators.queue(worker(shortest_tree, args, `${FlatQueue.toString()}`))
: shortest_tree(args)
Insert cell
Insert cell
n = 100
Insert cell
Insert cell
Insert cell
origins = [0, 1, 2]
Insert cell
Insert cell
step = 10 // yield every … steps
Insert cell
run_args = ({
worker: true,
origins,
graph,
cutoff,
step
})
Insert cell
run = shortest_tree_async(run_args)
Insert cell
Insert cell
FlatQueue = require("flatqueue")
Insert cell
import { worker } from "@fil/worker"
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