d3-contour.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. // https://d3js.org/d3-contour/ v1.3.2 Copyright 2018 Mike Bostock
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-array')) :
  4. typeof define === 'function' && define.amd ? define(['exports', 'd3-array'], factory) :
  5. (factory((global.d3 = global.d3 || {}),global.d3));
  6. }(this, (function (exports,d3Array) { 'use strict';
  7. var array = Array.prototype;
  8. var slice = array.slice;
  9. function ascending(a, b) {
  10. return a - b;
  11. }
  12. function area(ring) {
  13. var i = 0, n = ring.length, area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];
  14. while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];
  15. return area;
  16. }
  17. function constant(x) {
  18. return function() {
  19. return x;
  20. };
  21. }
  22. function contains(ring, hole) {
  23. var i = -1, n = hole.length, c;
  24. while (++i < n) if (c = ringContains(ring, hole[i])) return c;
  25. return 0;
  26. }
  27. function ringContains(ring, point) {
  28. var x = point[0], y = point[1], contains = -1;
  29. for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) {
  30. var pi = ring[i], xi = pi[0], yi = pi[1], pj = ring[j], xj = pj[0], yj = pj[1];
  31. if (segmentContains(pi, pj, point)) return 0;
  32. if (((yi > y) !== (yj > y)) && ((x < (xj - xi) * (y - yi) / (yj - yi) + xi))) contains = -contains;
  33. }
  34. return contains;
  35. }
  36. function segmentContains(a, b, c) {
  37. var i; return collinear(a, b, c) && within(a[i = +(a[0] === b[0])], c[i], b[i]);
  38. }
  39. function collinear(a, b, c) {
  40. return (b[0] - a[0]) * (c[1] - a[1]) === (c[0] - a[0]) * (b[1] - a[1]);
  41. }
  42. function within(p, q, r) {
  43. return p <= q && q <= r || r <= q && q <= p;
  44. }
  45. function noop() {}
  46. var cases = [
  47. [],
  48. [[[1.0, 1.5], [0.5, 1.0]]],
  49. [[[1.5, 1.0], [1.0, 1.5]]],
  50. [[[1.5, 1.0], [0.5, 1.0]]],
  51. [[[1.0, 0.5], [1.5, 1.0]]],
  52. [[[1.0, 1.5], [0.5, 1.0]], [[1.0, 0.5], [1.5, 1.0]]],
  53. [[[1.0, 0.5], [1.0, 1.5]]],
  54. [[[1.0, 0.5], [0.5, 1.0]]],
  55. [[[0.5, 1.0], [1.0, 0.5]]],
  56. [[[1.0, 1.5], [1.0, 0.5]]],
  57. [[[0.5, 1.0], [1.0, 0.5]], [[1.5, 1.0], [1.0, 1.5]]],
  58. [[[1.5, 1.0], [1.0, 0.5]]],
  59. [[[0.5, 1.0], [1.5, 1.0]]],
  60. [[[1.0, 1.5], [1.5, 1.0]]],
  61. [[[0.5, 1.0], [1.0, 1.5]]],
  62. []
  63. ];
  64. function contours() {
  65. var dx = 1,
  66. dy = 1,
  67. threshold = d3Array.thresholdSturges,
  68. smooth = smoothLinear;
  69. function contours(values) {
  70. var tz = threshold(values);
  71. // Convert number of thresholds into uniform thresholds.
  72. if (!Array.isArray(tz)) {
  73. var domain = d3Array.extent(values), start = domain[0], stop = domain[1];
  74. tz = d3Array.tickStep(start, stop, tz);
  75. tz = d3Array.range(Math.floor(start / tz) * tz, Math.floor(stop / tz) * tz, tz);
  76. } else {
  77. tz = tz.slice().sort(ascending);
  78. }
  79. return tz.map(function(value) {
  80. return contour(values, value);
  81. });
  82. }
  83. // Accumulate, smooth contour rings, assign holes to exterior rings.
  84. // Based on https://github.com/mbostock/shapefile/blob/v0.6.2/shp/polygon.js
  85. function contour(values, value) {
  86. var polygons = [],
  87. holes = [];
  88. isorings(values, value, function(ring) {
  89. smooth(ring, values, value);
  90. if (area(ring) > 0) polygons.push([ring]);
  91. else holes.push(ring);
  92. });
  93. holes.forEach(function(hole) {
  94. for (var i = 0, n = polygons.length, polygon; i < n; ++i) {
  95. if (contains((polygon = polygons[i])[0], hole) !== -1) {
  96. polygon.push(hole);
  97. return;
  98. }
  99. }
  100. });
  101. return {
  102. type: "MultiPolygon",
  103. value: value,
  104. coordinates: polygons
  105. };
  106. }
  107. // Marching squares with isolines stitched into rings.
  108. // Based on https://github.com/topojson/topojson-client/blob/v3.0.0/src/stitch.js
  109. function isorings(values, value, callback) {
  110. var fragmentByStart = new Array,
  111. fragmentByEnd = new Array,
  112. x, y, t0, t1, t2, t3;
  113. // Special case for the first row (y = -1, t2 = t3 = 0).
  114. x = y = -1;
  115. t1 = values[0] >= value;
  116. cases[t1 << 1].forEach(stitch);
  117. while (++x < dx - 1) {
  118. t0 = t1, t1 = values[x + 1] >= value;
  119. cases[t0 | t1 << 1].forEach(stitch);
  120. }
  121. cases[t1 << 0].forEach(stitch);
  122. // General case for the intermediate rows.
  123. while (++y < dy - 1) {
  124. x = -1;
  125. t1 = values[y * dx + dx] >= value;
  126. t2 = values[y * dx] >= value;
  127. cases[t1 << 1 | t2 << 2].forEach(stitch);
  128. while (++x < dx - 1) {
  129. t0 = t1, t1 = values[y * dx + dx + x + 1] >= value;
  130. t3 = t2, t2 = values[y * dx + x + 1] >= value;
  131. cases[t0 | t1 << 1 | t2 << 2 | t3 << 3].forEach(stitch);
  132. }
  133. cases[t1 | t2 << 3].forEach(stitch);
  134. }
  135. // Special case for the last row (y = dy - 1, t0 = t1 = 0).
  136. x = -1;
  137. t2 = values[y * dx] >= value;
  138. cases[t2 << 2].forEach(stitch);
  139. while (++x < dx - 1) {
  140. t3 = t2, t2 = values[y * dx + x + 1] >= value;
  141. cases[t2 << 2 | t3 << 3].forEach(stitch);
  142. }
  143. cases[t2 << 3].forEach(stitch);
  144. function stitch(line) {
  145. var start = [line[0][0] + x, line[0][1] + y],
  146. end = [line[1][0] + x, line[1][1] + y],
  147. startIndex = index(start),
  148. endIndex = index(end),
  149. f, g;
  150. if (f = fragmentByEnd[startIndex]) {
  151. if (g = fragmentByStart[endIndex]) {
  152. delete fragmentByEnd[f.end];
  153. delete fragmentByStart[g.start];
  154. if (f === g) {
  155. f.ring.push(end);
  156. callback(f.ring);
  157. } else {
  158. fragmentByStart[f.start] = fragmentByEnd[g.end] = {start: f.start, end: g.end, ring: f.ring.concat(g.ring)};
  159. }
  160. } else {
  161. delete fragmentByEnd[f.end];
  162. f.ring.push(end);
  163. fragmentByEnd[f.end = endIndex] = f;
  164. }
  165. } else if (f = fragmentByStart[endIndex]) {
  166. if (g = fragmentByEnd[startIndex]) {
  167. delete fragmentByStart[f.start];
  168. delete fragmentByEnd[g.end];
  169. if (f === g) {
  170. f.ring.push(end);
  171. callback(f.ring);
  172. } else {
  173. fragmentByStart[g.start] = fragmentByEnd[f.end] = {start: g.start, end: f.end, ring: g.ring.concat(f.ring)};
  174. }
  175. } else {
  176. delete fragmentByStart[f.start];
  177. f.ring.unshift(start);
  178. fragmentByStart[f.start = startIndex] = f;
  179. }
  180. } else {
  181. fragmentByStart[startIndex] = fragmentByEnd[endIndex] = {start: startIndex, end: endIndex, ring: [start, end]};
  182. }
  183. }
  184. }
  185. function index(point) {
  186. return point[0] * 2 + point[1] * (dx + 1) * 4;
  187. }
  188. function smoothLinear(ring, values, value) {
  189. ring.forEach(function(point) {
  190. var x = point[0],
  191. y = point[1],
  192. xt = x | 0,
  193. yt = y | 0,
  194. v0,
  195. v1 = values[yt * dx + xt];
  196. if (x > 0 && x < dx && xt === x) {
  197. v0 = values[yt * dx + xt - 1];
  198. point[0] = x + (value - v0) / (v1 - v0) - 0.5;
  199. }
  200. if (y > 0 && y < dy && yt === y) {
  201. v0 = values[(yt - 1) * dx + xt];
  202. point[1] = y + (value - v0) / (v1 - v0) - 0.5;
  203. }
  204. });
  205. }
  206. contours.contour = contour;
  207. contours.size = function(_) {
  208. if (!arguments.length) return [dx, dy];
  209. var _0 = Math.ceil(_[0]), _1 = Math.ceil(_[1]);
  210. if (!(_0 > 0) || !(_1 > 0)) throw new Error("invalid size");
  211. return dx = _0, dy = _1, contours;
  212. };
  213. contours.thresholds = function(_) {
  214. return arguments.length ? (threshold = typeof _ === "function" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), contours) : threshold;
  215. };
  216. contours.smooth = function(_) {
  217. return arguments.length ? (smooth = _ ? smoothLinear : noop, contours) : smooth === smoothLinear;
  218. };
  219. return contours;
  220. }
  221. // TODO Optimize edge cases.
  222. // TODO Optimize index calculation.
  223. // TODO Optimize arguments.
  224. function blurX(source, target, r) {
  225. var n = source.width,
  226. m = source.height,
  227. w = (r << 1) + 1;
  228. for (var j = 0; j < m; ++j) {
  229. for (var i = 0, sr = 0; i < n + r; ++i) {
  230. if (i < n) {
  231. sr += source.data[i + j * n];
  232. }
  233. if (i >= r) {
  234. if (i >= w) {
  235. sr -= source.data[i - w + j * n];
  236. }
  237. target.data[i - r + j * n] = sr / Math.min(i + 1, n - 1 + w - i, w);
  238. }
  239. }
  240. }
  241. }
  242. // TODO Optimize edge cases.
  243. // TODO Optimize index calculation.
  244. // TODO Optimize arguments.
  245. function blurY(source, target, r) {
  246. var n = source.width,
  247. m = source.height,
  248. w = (r << 1) + 1;
  249. for (var i = 0; i < n; ++i) {
  250. for (var j = 0, sr = 0; j < m + r; ++j) {
  251. if (j < m) {
  252. sr += source.data[i + j * n];
  253. }
  254. if (j >= r) {
  255. if (j >= w) {
  256. sr -= source.data[i + (j - w) * n];
  257. }
  258. target.data[i + (j - r) * n] = sr / Math.min(j + 1, m - 1 + w - j, w);
  259. }
  260. }
  261. }
  262. }
  263. function defaultX(d) {
  264. return d[0];
  265. }
  266. function defaultY(d) {
  267. return d[1];
  268. }
  269. function defaultWeight() {
  270. return 1;
  271. }
  272. function density() {
  273. var x = defaultX,
  274. y = defaultY,
  275. weight = defaultWeight,
  276. dx = 960,
  277. dy = 500,
  278. r = 20, // blur radius
  279. k = 2, // log2(grid cell size)
  280. o = r * 3, // grid offset, to pad for blur
  281. n = (dx + o * 2) >> k, // grid width
  282. m = (dy + o * 2) >> k, // grid height
  283. threshold = constant(20);
  284. function density(data) {
  285. var values0 = new Float32Array(n * m),
  286. values1 = new Float32Array(n * m);
  287. data.forEach(function(d, i, data) {
  288. var xi = (+x(d, i, data) + o) >> k,
  289. yi = (+y(d, i, data) + o) >> k,
  290. wi = +weight(d, i, data);
  291. if (xi >= 0 && xi < n && yi >= 0 && yi < m) {
  292. values0[xi + yi * n] += wi;
  293. }
  294. });
  295. // TODO Optimize.
  296. blurX({width: n, height: m, data: values0}, {width: n, height: m, data: values1}, r >> k);
  297. blurY({width: n, height: m, data: values1}, {width: n, height: m, data: values0}, r >> k);
  298. blurX({width: n, height: m, data: values0}, {width: n, height: m, data: values1}, r >> k);
  299. blurY({width: n, height: m, data: values1}, {width: n, height: m, data: values0}, r >> k);
  300. blurX({width: n, height: m, data: values0}, {width: n, height: m, data: values1}, r >> k);
  301. blurY({width: n, height: m, data: values1}, {width: n, height: m, data: values0}, r >> k);
  302. var tz = threshold(values0);
  303. // Convert number of thresholds into uniform thresholds.
  304. if (!Array.isArray(tz)) {
  305. var stop = d3Array.max(values0);
  306. tz = d3Array.tickStep(0, stop, tz);
  307. tz = d3Array.range(0, Math.floor(stop / tz) * tz, tz);
  308. tz.shift();
  309. }
  310. return contours()
  311. .thresholds(tz)
  312. .size([n, m])
  313. (values0)
  314. .map(transform);
  315. }
  316. function transform(geometry) {
  317. geometry.value *= Math.pow(2, -2 * k); // Density in points per square pixel.
  318. geometry.coordinates.forEach(transformPolygon);
  319. return geometry;
  320. }
  321. function transformPolygon(coordinates) {
  322. coordinates.forEach(transformRing);
  323. }
  324. function transformRing(coordinates) {
  325. coordinates.forEach(transformPoint);
  326. }
  327. // TODO Optimize.
  328. function transformPoint(coordinates) {
  329. coordinates[0] = coordinates[0] * Math.pow(2, k) - o;
  330. coordinates[1] = coordinates[1] * Math.pow(2, k) - o;
  331. }
  332. function resize() {
  333. o = r * 3;
  334. n = (dx + o * 2) >> k;
  335. m = (dy + o * 2) >> k;
  336. return density;
  337. }
  338. density.x = function(_) {
  339. return arguments.length ? (x = typeof _ === "function" ? _ : constant(+_), density) : x;
  340. };
  341. density.y = function(_) {
  342. return arguments.length ? (y = typeof _ === "function" ? _ : constant(+_), density) : y;
  343. };
  344. density.weight = function(_) {
  345. return arguments.length ? (weight = typeof _ === "function" ? _ : constant(+_), density) : weight;
  346. };
  347. density.size = function(_) {
  348. if (!arguments.length) return [dx, dy];
  349. var _0 = Math.ceil(_[0]), _1 = Math.ceil(_[1]);
  350. if (!(_0 >= 0) && !(_0 >= 0)) throw new Error("invalid size");
  351. return dx = _0, dy = _1, resize();
  352. };
  353. density.cellSize = function(_) {
  354. if (!arguments.length) return 1 << k;
  355. if (!((_ = +_) >= 1)) throw new Error("invalid cell size");
  356. return k = Math.floor(Math.log(_) / Math.LN2), resize();
  357. };
  358. density.thresholds = function(_) {
  359. return arguments.length ? (threshold = typeof _ === "function" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), density) : threshold;
  360. };
  361. density.bandwidth = function(_) {
  362. if (!arguments.length) return Math.sqrt(r * (r + 1));
  363. if (!((_ = +_) >= 0)) throw new Error("invalid bandwidth");
  364. return r = Math.round((Math.sqrt(4 * _ * _ + 1) - 1) / 2), resize();
  365. };
  366. return density;
  367. }
  368. exports.contours = contours;
  369. exports.contourDensity = density;
  370. Object.defineProperty(exports, '__esModule', { value: true });
  371. })));