@d3plus/math 3.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,939 @@
1
+ /*
2
+ @d3plus/math v3.0.0
3
+ Mathematical functions to aid in calculating visualizations.
4
+ Copyright (c) 2025 D3plus - https://d3plus.org
5
+ @license MIT
6
+ */
7
+
8
+ (function (factory) {
9
+ typeof define === 'function' && define.amd ? define(factory) :
10
+ factory();
11
+ })((function () { 'use strict';
12
+
13
+ if (typeof window !== "undefined") {
14
+ (function () {
15
+ try {
16
+ if (typeof SVGElement === 'undefined' || Boolean(SVGElement.prototype.innerHTML)) {
17
+ return;
18
+ }
19
+ } catch (e) {
20
+ return;
21
+ }
22
+
23
+ function serializeNode (node) {
24
+ switch (node.nodeType) {
25
+ case 1:
26
+ return serializeElementNode(node);
27
+ case 3:
28
+ return serializeTextNode(node);
29
+ case 8:
30
+ return serializeCommentNode(node);
31
+ }
32
+ }
33
+
34
+ function serializeTextNode (node) {
35
+ return node.textContent.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
36
+ }
37
+
38
+ function serializeCommentNode (node) {
39
+ return '<!--' + node.nodeValue + '-->'
40
+ }
41
+
42
+ function serializeElementNode (node) {
43
+ var output = '';
44
+
45
+ output += '<' + node.tagName;
46
+
47
+ if (node.hasAttributes()) {
48
+ [].forEach.call(node.attributes, function(attrNode) {
49
+ output += ' ' + attrNode.name + '="' + attrNode.value + '"';
50
+ });
51
+ }
52
+
53
+ output += '>';
54
+
55
+ if (node.hasChildNodes()) {
56
+ [].forEach.call(node.childNodes, function(childNode) {
57
+ output += serializeNode(childNode);
58
+ });
59
+ }
60
+
61
+ output += '</' + node.tagName + '>';
62
+
63
+ return output;
64
+ }
65
+
66
+ Object.defineProperty(SVGElement.prototype, 'innerHTML', {
67
+ get: function () {
68
+ var output = '';
69
+
70
+ [].forEach.call(this.childNodes, function(childNode) {
71
+ output += serializeNode(childNode);
72
+ });
73
+
74
+ return output;
75
+ },
76
+ set: function (markup) {
77
+ while (this.firstChild) {
78
+ this.removeChild(this.firstChild);
79
+ }
80
+
81
+ try {
82
+ var dXML = new DOMParser();
83
+ dXML.async = false;
84
+
85
+ var sXML = '<svg xmlns=\'http://www.w3.org/2000/svg\' xmlns:xlink=\'http://www.w3.org/1999/xlink\'>' + markup + '</svg>';
86
+ var svgDocElement = dXML.parseFromString(sXML, 'text/xml').documentElement;
87
+
88
+ [].forEach.call(svgDocElement.childNodes, function(childNode) {
89
+ this.appendChild(this.ownerDocument.importNode(childNode, true));
90
+ }.bind(this));
91
+ } catch (e) {
92
+ throw new Error('Error parsing markup string');
93
+ }
94
+ }
95
+ });
96
+
97
+ Object.defineProperty(SVGElement.prototype, 'innerSVG', {
98
+ get: function () {
99
+ return this.innerHTML;
100
+ },
101
+ set: function (markup) {
102
+ this.innerHTML = markup;
103
+ }
104
+ });
105
+
106
+ })();
107
+ }
108
+
109
+ }));
110
+
111
+ (function (global, factory) {
112
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-array'), require('d3-polygon')) :
113
+ typeof define === 'function' && define.amd ? define('@d3plus/math', ['exports', 'd3-array', 'd3-polygon'], factory) :
114
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.d3plus = {}, global.d3Array, global.d3Polygon));
115
+ })(this, (function (exports, d3Array, d3Polygon) { 'use strict';
116
+
117
+ /**
118
+ @desc Sort an array of numbers by their numeric value, ensuring that the array is not changed in place.
119
+
120
+ This is necessary because the default behavior of .sort in JavaScript is to sort arrays as string values
121
+
122
+ [1, 10, 12, 102, 20].sort()
123
+ // output
124
+ [1, 10, 102, 12, 20]
125
+
126
+ @param {Array<number>} array input array
127
+ @return {Array<number>} sorted array
128
+ @private
129
+ @example
130
+ numericSort([3, 2, 1]) // => [1, 2, 3]
131
+ */ function numericSort(array) {
132
+ return array.slice().sort((a, b)=>a - b);
133
+ }
134
+ /**
135
+ For a sorted input, counting the number of unique values is possible in constant time and constant memory. This is a simple implementation of the algorithm.
136
+
137
+ Values are compared with `===`, so objects and non-primitive objects are not handled in any special way.
138
+ @private
139
+ @param {Array} input an array of primitive values.
140
+ @returns {number} count of unique values
141
+ @example
142
+ uniqueCountSorted([1, 2, 3]); // => 3
143
+ uniqueCountSorted([1, 1, 1]); // => 1
144
+ */ function uniqueCountSorted(input) {
145
+ let lastSeenValue, uniqueValueCount = 0;
146
+ for(let i = 0; i < input.length; i++){
147
+ if (i === 0 || input[i] !== lastSeenValue) {
148
+ lastSeenValue = input[i];
149
+ uniqueValueCount++;
150
+ }
151
+ }
152
+ return uniqueValueCount;
153
+ }
154
+ /**
155
+ Create a new column x row matrix.
156
+ @private
157
+ @param {number} columns
158
+ @param {number} rows
159
+ @return {Array<Array<number>>} matrix
160
+ @example
161
+ makeMatrix(10, 10);
162
+ */ function makeMatrix(columns, rows) {
163
+ const matrix = [];
164
+ for(let i = 0; i < columns; i++){
165
+ const column = [];
166
+ for(let j = 0; j < rows; j++)column.push(0);
167
+ matrix.push(column);
168
+ }
169
+ return matrix;
170
+ }
171
+ /**
172
+ Generates incrementally computed values based on the sums and sums of squares for the data array
173
+ @private
174
+ @param {number} j
175
+ @param {number} i
176
+ @param {Array<number>} sums
177
+ @param {Array<number>} sumsOfSquares
178
+ @return {number}
179
+ @example
180
+ ssq(0, 1, [-1, 0, 2], [1, 1, 5]);
181
+ */ function ssq(j, i, sums, sumsOfSquares) {
182
+ let sji; // s(j, i)
183
+ if (j > 0) {
184
+ const muji = (sums[i] - sums[j - 1]) / (i - j + 1); // mu(j, i)
185
+ sji = sumsOfSquares[i] - sumsOfSquares[j - 1] - (i - j + 1) * muji * muji;
186
+ } else sji = sumsOfSquares[i] - sums[i] * sums[i] / (i + 1);
187
+ if (sji < 0) return 0;
188
+ return sji;
189
+ }
190
+ /**
191
+ Function that recursively divides and conquers computations for cluster j
192
+ @private
193
+ @param {number} iMin Minimum index in cluster to be computed
194
+ @param {number} iMax Maximum index in cluster to be computed
195
+ @param {number} cluster Index of the cluster currently being computed
196
+ @param {Array<Array<number>>} matrix
197
+ @param {Array<Array<number>>} backtrackMatrix
198
+ @param {Array<number>} sums
199
+ @param {Array<number>} sumsOfSquares
200
+ */ function fillMatrixColumn(iMin, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares) {
201
+ if (iMin > iMax) return;
202
+ // Start at midpoint between iMin and iMax
203
+ const i = Math.floor((iMin + iMax) / 2);
204
+ matrix[cluster][i] = matrix[cluster - 1][i - 1];
205
+ backtrackMatrix[cluster][i] = i;
206
+ let jlow = cluster; // the lower end for j
207
+ if (iMin > cluster) jlow = Math.max(jlow, backtrackMatrix[cluster][iMin - 1] || 0);
208
+ jlow = Math.max(jlow, backtrackMatrix[cluster - 1][i] || 0);
209
+ let jhigh = i - 1; // the upper end for j
210
+ if (iMax < matrix.length - 1) jhigh = Math.min(jhigh, backtrackMatrix[cluster][iMax + 1] || 0);
211
+ for(let j = jhigh; j >= jlow; --j){
212
+ const sji = ssq(j, i, sums, sumsOfSquares);
213
+ if (sji + matrix[cluster - 1][jlow - 1] >= matrix[cluster][i]) break;
214
+ // Examine the lower bound of the cluster border
215
+ const sjlowi = ssq(jlow, i, sums, sumsOfSquares);
216
+ const ssqjlow = sjlowi + matrix[cluster - 1][jlow - 1];
217
+ if (ssqjlow < matrix[cluster][i]) {
218
+ // Shrink the lower bound
219
+ matrix[cluster][i] = ssqjlow;
220
+ backtrackMatrix[cluster][i] = jlow;
221
+ }
222
+ jlow++;
223
+ const ssqj = sji + matrix[cluster - 1][j - 1];
224
+ if (ssqj < matrix[cluster][i]) {
225
+ matrix[cluster][i] = ssqj;
226
+ backtrackMatrix[cluster][i] = j;
227
+ }
228
+ }
229
+ fillMatrixColumn(iMin, i - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares);
230
+ fillMatrixColumn(i + 1, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares);
231
+ }
232
+ /**
233
+ Initializes the main matrices used in Ckmeans and kicks off the divide and conquer cluster computation strategy
234
+ @private
235
+ @param {Array<number>} data sorted array of values
236
+ @param {Array<Array<number>>} matrix
237
+ @param {Array<Array<number>>} backtrackMatrix
238
+ */ function fillMatrices(data, matrix, backtrackMatrix) {
239
+ const nValues = matrix[0] ? matrix[0].length : 0;
240
+ // Shift values by the median to improve numeric stability
241
+ const shift = data[Math.floor(nValues / 2)];
242
+ // Cumulative sum and cumulative sum of squares for all values in data array
243
+ const sums = [];
244
+ const sumsOfSquares = [];
245
+ // Initialize first column in matrix & backtrackMatrix
246
+ for(let i = 0, shiftedValue = void 0; i < nValues; ++i){
247
+ shiftedValue = data[i] - shift;
248
+ if (i === 0) {
249
+ sums.push(shiftedValue);
250
+ sumsOfSquares.push(shiftedValue * shiftedValue);
251
+ } else {
252
+ sums.push(sums[i - 1] + shiftedValue);
253
+ sumsOfSquares.push(sumsOfSquares[i - 1] + shiftedValue * shiftedValue);
254
+ }
255
+ // Initialize for cluster = 0
256
+ matrix[0][i] = ssq(0, i, sums, sumsOfSquares);
257
+ backtrackMatrix[0][i] = 0;
258
+ }
259
+ // Initialize the rest of the columns
260
+ for(let cluster = 1; cluster < matrix.length; ++cluster){
261
+ let iMin = nValues - 1;
262
+ if (cluster < matrix.length - 1) iMin = cluster;
263
+ fillMatrixColumn(iMin, nValues - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares);
264
+ }
265
+ }
266
+ /**
267
+ @module ckmeans
268
+ @desc Ported to ES6 from the excellent [simple-statistics](https://github.com/simple-statistics/simple-statistics) packages.
269
+
270
+ Ckmeans clustering is an improvement on heuristic-based clustering approaches like Jenks. The algorithm was developed in [Haizhou Wang and Mingzhou Song](http://journal.r-project.org/archive/2011-2/RJournal_2011-2_Wang+Song.pdf) as a [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming) approach to the problem of clustering numeric data into groups with the least within-group sum-of-squared-deviations.
271
+
272
+ Minimizing the difference within groups - what Wang & Song refer to as `withinss`, or within sum-of-squares, means that groups are optimally homogenous within and the data is split into representative groups. This is very useful for visualization, where you may want to represent a continuous variable in discrete color or style groups. This function can provide groups that emphasize differences between data.
273
+
274
+ Being a dynamic approach, this algorithm is based on two matrices that store incrementally-computed values for squared deviations and backtracking indexes.
275
+
276
+ This implementation is based on Ckmeans 3.4.6, which introduced a new divide and conquer approach that improved runtime from O(kn^2) to O(kn log(n)).
277
+
278
+ Unlike the [original implementation](https://cran.r-project.org/web/packages/Ckmeans.1d.dp/index.html), this implementation does not include any code to automatically determine the optimal number of clusters: this information needs to be explicitly provided.
279
+
280
+ ### References
281
+ _Ckmeans.1d.dp: Optimal k-means Clustering in One Dimension by Dynamic
282
+ Programming_ Haizhou Wang and Mingzhou Song ISSN 2073-4859 from The R Journal Vol. 3/2, December 2011
283
+ @param {Array<number>} data input data, as an array of number values
284
+ @param {number} nClusters number of desired classes. This cannot be greater than the number of values in the data array.
285
+ @returns {Array<Array<number>>} clustered input
286
+ @private
287
+ @example
288
+ ckmeans([-1, 2, -1, 2, 4, 5, 6, -1, 2, -1], 3);
289
+ // The input, clustered into groups of similar numbers.
290
+ //= [[-1, -1, -1, -1], [2, 2, 2], [4, 5, 6]]);
291
+ */ function ckmeans(data, nClusters) {
292
+ if (nClusters > data.length) {
293
+ throw new Error("Cannot generate more classes than there are data values");
294
+ }
295
+ const sorted = numericSort(data);
296
+ // we'll use this as the maximum number of clusters
297
+ const uniqueCount = uniqueCountSorted(sorted);
298
+ // if all of the input values are identical, there's one cluster with all of the input in it.
299
+ if (uniqueCount === 1) {
300
+ return [
301
+ sorted
302
+ ];
303
+ }
304
+ const backtrackMatrix = makeMatrix(nClusters, sorted.length), matrix = makeMatrix(nClusters, sorted.length);
305
+ // This is a dynamic programming way to solve the problem of minimizing within-cluster sum of squares. It's similar to linear regression in this way, and this calculation incrementally computes the sum of squares that are later read.
306
+ fillMatrices(sorted, matrix, backtrackMatrix);
307
+ // The real work of Ckmeans clustering happens in the matrix generation: the generated matrices encode all possible clustering combinations, and once they're generated we can solve for the best clustering groups very quickly.
308
+ let clusterRight = backtrackMatrix[0] ? backtrackMatrix[0].length - 1 : 0;
309
+ const clusters = [];
310
+ // Backtrack the clusters from the dynamic programming matrix. This starts at the bottom-right corner of the matrix (if the top-left is 0, 0), and moves the cluster target with the loop.
311
+ for(let cluster = backtrackMatrix.length - 1; cluster >= 0; cluster--){
312
+ const clusterLeft = backtrackMatrix[cluster][clusterRight];
313
+ // fill the cluster from the sorted input by taking a slice of the array. the backtrack matrix makes this easy - it stores the indexes where the cluster should start and end.
314
+ clusters[cluster] = sorted.slice(clusterLeft, clusterRight + 1);
315
+ if (cluster > 0) clusterRight = clusterLeft - 1;
316
+ }
317
+ return clusters;
318
+ }
319
+
320
+ /**
321
+ @function closest
322
+ @desc Finds the closest numeric value in an array.
323
+ @param {Number} n The number value to use when searching the array.
324
+ @param {Array} arr The array of values to test against.
325
+ */ function closest(n, arr = []) {
326
+ if (!arr || !(arr instanceof Array) || !arr.length) return undefined;
327
+ return arr.reduce((prev, curr)=>Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev);
328
+ }
329
+
330
+ /**
331
+ @function lineIntersection
332
+ @desc Finds the intersection point (if there is one) of the lines p1q1 and p2q2.
333
+ @param {Array} p1 The first point of the first line segment, which should always be an `[x, y]` formatted Array.
334
+ @param {Array} q1 The second point of the first line segment, which should always be an `[x, y]` formatted Array.
335
+ @param {Array} p2 The first point of the second line segment, which should always be an `[x, y]` formatted Array.
336
+ @param {Array} q2 The second point of the second line segment, which should always be an `[x, y]` formatted Array.
337
+ @returns {Boolean}
338
+ */ function lineIntersection(p1, q1, p2, q2) {
339
+ // allow for some margins due to numerical errors
340
+ const eps = 1e-9;
341
+ // find the intersection point between the two infinite lines
342
+ const dx1 = p1[0] - q1[0], dx2 = p2[0] - q2[0], dy1 = p1[1] - q1[1], dy2 = p2[1] - q2[1];
343
+ const denom = dx1 * dy2 - dy1 * dx2;
344
+ if (Math.abs(denom) < eps) return null;
345
+ const cross1 = p1[0] * q1[1] - p1[1] * q1[0], cross2 = p2[0] * q2[1] - p2[1] * q2[0];
346
+ const px = (cross1 * dx2 - cross2 * dx1) / denom, py = (cross1 * dy2 - cross2 * dy1) / denom;
347
+ return [
348
+ px,
349
+ py
350
+ ];
351
+ }
352
+
353
+ /**
354
+ @function segmentBoxContains
355
+ @desc Checks whether a point is inside the bounding box of a line segment.
356
+ @param {Array} s1 The first point of the line segment to be used for the bounding box, which should always be an `[x, y]` formatted Array.
357
+ @param {Array} s2 The second point of the line segment to be used for the bounding box, which should always be an `[x, y]` formatted Array.
358
+ @param {Array} p The point to be checked, which should always be an `[x, y]` formatted Array.
359
+ @returns {Boolean}
360
+ */ function segmentBoxContains(s1, s2, p) {
361
+ const eps = 1e-9, [px, py] = p;
362
+ return !(px < Math.min(s1[0], s2[0]) - eps || px > Math.max(s1[0], s2[0]) + eps || py < Math.min(s1[1], s2[1]) - eps || py > Math.max(s1[1], s2[1]) + eps);
363
+ }
364
+
365
+ /**
366
+ @function segmentsIntersect
367
+ @desc Checks whether the line segments p1q1 && p2q2 intersect.
368
+ @param {Array} p1 The first point of the first line segment, which should always be an `[x, y]` formatted Array.
369
+ @param {Array} q1 The second point of the first line segment, which should always be an `[x, y]` formatted Array.
370
+ @param {Array} p2 The first point of the second line segment, which should always be an `[x, y]` formatted Array.
371
+ @param {Array} q2 The second point of the second line segment, which should always be an `[x, y]` formatted Array.
372
+ @returns {Boolean}
373
+ */ function segmentsIntersect(p1, q1, p2, q2) {
374
+ const p = lineIntersection(p1, q1, p2, q2);
375
+ if (!p) return false;
376
+ return segmentBoxContains(p1, q1, p) && segmentBoxContains(p2, q2, p);
377
+ }
378
+
379
+ /**
380
+ @function polygonInside
381
+ @desc Checks if one polygon is inside another polygon.
382
+ @param {Array} polyA An Array of `[x, y]` points to be used as the inner polygon, checking if it is inside polyA.
383
+ @param {Array} polyB An Array of `[x, y]` points to be used as the containing polygon.
384
+ @returns {Boolean}
385
+ */ function polygonInside(polyA, polyB) {
386
+ let iA = -1;
387
+ const nA = polyA.length;
388
+ const nB = polyB.length;
389
+ let bA = polyA[nA - 1];
390
+ while(++iA < nA){
391
+ const aA = bA;
392
+ bA = polyA[iA];
393
+ let iB = -1;
394
+ let bB = polyB[nB - 1];
395
+ while(++iB < nB){
396
+ const aB = bB;
397
+ bB = polyB[iB];
398
+ if (segmentsIntersect(aA, bA, aB, bB)) return false;
399
+ }
400
+ }
401
+ return d3Polygon.polygonContains(polyB, polyA[0]);
402
+ }
403
+
404
+ /**
405
+ @function pointDistanceSquared
406
+ @desc Returns the squared euclidean distance between two points.
407
+ @param {Array} p1 The first point, which should always be an `[x, y]` formatted Array.
408
+ @param {Array} p2 The second point, which should always be an `[x, y]` formatted Array.
409
+ @returns {Number}
410
+ */ var pointDistanceSquared = ((p1, p2)=>{
411
+ const dx = p2[0] - p1[0], dy = p2[1] - p1[1];
412
+ return dx * dx + dy * dy;
413
+ });
414
+
415
+ /**
416
+ @function polygonRayCast
417
+ @desc Gives the two closest intersection points between a ray cast from a point inside a polygon. The two points should lie on opposite sides of the origin.
418
+ @param {Array} poly The polygon to test against, which should be an `[x, y]` formatted Array.
419
+ @param {Array} origin The origin point of the ray to be cast, which should be an `[x, y]` formatted Array.
420
+ @param {Number} [alpha = 0] The angle in radians of the ray.
421
+ @returns {Array} An array containing two values, the closest point on the left and the closest point on the right. If either point cannot be found, that value will be `null`.
422
+ */ function polygonRayCast(poly, origin, alpha = 0) {
423
+ const eps = 1e-9;
424
+ origin = [
425
+ origin[0] + eps * Math.cos(alpha),
426
+ origin[1] + eps * Math.sin(alpha)
427
+ ];
428
+ const [x0, y0] = origin;
429
+ const shiftedOrigin = [
430
+ x0 + Math.cos(alpha),
431
+ y0 + Math.sin(alpha)
432
+ ];
433
+ let idx = 0;
434
+ if (Math.abs(shiftedOrigin[0] - x0) < eps) idx = 1;
435
+ let i = -1;
436
+ const n = poly.length;
437
+ let b = poly[n - 1];
438
+ let minSqDistLeft = Number.MAX_VALUE;
439
+ let minSqDistRight = Number.MAX_VALUE;
440
+ let closestPointLeft = null;
441
+ let closestPointRight = null;
442
+ while(++i < n){
443
+ const a = b;
444
+ b = poly[i];
445
+ const p = lineIntersection(origin, shiftedOrigin, a, b);
446
+ if (p && segmentBoxContains(a, b, p)) {
447
+ const sqDist = pointDistanceSquared(origin, p);
448
+ if (p[idx] < origin[idx]) {
449
+ if (sqDist < minSqDistLeft) {
450
+ minSqDistLeft = sqDist;
451
+ closestPointLeft = p;
452
+ }
453
+ } else if (p[idx] > origin[idx]) {
454
+ if (sqDist < minSqDistRight) {
455
+ minSqDistRight = sqDist;
456
+ closestPointRight = p;
457
+ }
458
+ }
459
+ }
460
+ }
461
+ return [
462
+ closestPointLeft,
463
+ closestPointRight
464
+ ];
465
+ }
466
+
467
+ /**
468
+ @function pointRotate
469
+ @desc Rotates a point around a given origin.
470
+ @param {Array} p The point to be rotated, which should always be an `[x, y]` formatted Array.
471
+ @param {Number} alpha The angle in radians to rotate.
472
+ @param {Array} [origin = [0, 0]] The origin point of the rotation, which should always be an `[x, y]` formatted Array.
473
+ @returns {Boolean}
474
+ */ function pointRotate(p, alpha, origin = [
475
+ 0,
476
+ 0
477
+ ]) {
478
+ const cosAlpha = Math.cos(alpha), sinAlpha = Math.sin(alpha), xshifted = p[0] - origin[0], yshifted = p[1] - origin[1];
479
+ return [
480
+ cosAlpha * xshifted - sinAlpha * yshifted + origin[0],
481
+ sinAlpha * xshifted + cosAlpha * yshifted + origin[1]
482
+ ];
483
+ }
484
+
485
+ /**
486
+ @function polygonRotate
487
+ @desc Rotates a point around a given origin.
488
+ @param {Array} poly The polygon to be rotated, which should be an Array of `[x, y]` values.
489
+ @param {Number} alpha The angle in radians to rotate.
490
+ @param {Array} [origin = [0, 0]] The origin point of the rotation, which should be an `[x, y]` formatted Array.
491
+ @returns {Boolean}
492
+ */ var polygonRotate = ((poly, alpha, origin = [
493
+ 0,
494
+ 0
495
+ ])=>poly.map((p)=>pointRotate(p, alpha, origin)));
496
+
497
+ /**
498
+ @desc square distance from a point to a segment
499
+ @param {Array} point
500
+ @param {Array} segmentAnchor1
501
+ @param {Array} segmentAnchor2
502
+ @private
503
+ */ function getSqSegDist(p, p1, p2) {
504
+ let x = p1[0], y = p1[1];
505
+ let dx = p2[0] - x, dy = p2[1] - y;
506
+ if (dx !== 0 || dy !== 0) {
507
+ const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy);
508
+ if (t > 1) {
509
+ x = p2[0];
510
+ y = p2[1];
511
+ } else if (t > 0) {
512
+ x += dx * t;
513
+ y += dy * t;
514
+ }
515
+ }
516
+ dx = p[0] - x;
517
+ dy = p[1] - y;
518
+ return dx * dx + dy * dy;
519
+ }
520
+ /**
521
+ @desc basic distance-based simplification
522
+ @param {Array} polygon
523
+ @param {Number} sqTolerance
524
+ @private
525
+ */ function simplifyRadialDist(poly, sqTolerance) {
526
+ let point, prevPoint = poly[0];
527
+ const newPoints = [
528
+ prevPoint
529
+ ];
530
+ for(let i = 1, len = poly.length; i < len; i++){
531
+ point = poly[i];
532
+ if (pointDistanceSquared(point, prevPoint) > sqTolerance) {
533
+ newPoints.push(point);
534
+ prevPoint = point;
535
+ }
536
+ }
537
+ if (prevPoint !== point) newPoints.push(point);
538
+ return newPoints;
539
+ }
540
+ /**
541
+ @param {Array} polygon
542
+ @param {Number} first
543
+ @param {Number} last
544
+ @param {Number} sqTolerance
545
+ @param {Array} simplified
546
+ @private
547
+ */ function simplifyDPStep(poly, first, last, sqTolerance, simplified) {
548
+ let index, maxSqDist = sqTolerance;
549
+ for(let i = first + 1; i < last; i++){
550
+ const sqDist = getSqSegDist(poly[i], poly[first], poly[last]);
551
+ if (sqDist > maxSqDist) {
552
+ index = i;
553
+ maxSqDist = sqDist;
554
+ }
555
+ }
556
+ if (maxSqDist > sqTolerance) {
557
+ if (index - first > 1) simplifyDPStep(poly, first, index, sqTolerance, simplified);
558
+ simplified.push(poly[index]);
559
+ if (last - index > 1) simplifyDPStep(poly, index, last, sqTolerance, simplified);
560
+ }
561
+ }
562
+ /**
563
+ @desc simplification using Ramer-Douglas-Peucker algorithm
564
+ @param {Array} polygon
565
+ @param {Number} sqTolerance
566
+ @private
567
+ */ function simplifyDouglasPeucker(poly, sqTolerance) {
568
+ const last = poly.length - 1;
569
+ const simplified = [
570
+ poly[0]
571
+ ];
572
+ simplifyDPStep(poly, 0, last, sqTolerance, simplified);
573
+ simplified.push(poly[last]);
574
+ return simplified;
575
+ }
576
+ /**
577
+ @function largestRect
578
+ @desc Simplifies the points of a polygon using both the Ramer-Douglas-Peucker algorithm and basic distance-based simplification. Adapted to an ES6 module from the excellent [Simplify.js](http://mourner.github.io/simplify-js/).
579
+ @author Vladimir Agafonkin
580
+ @param {Array} poly An Array of points that represent a polygon.
581
+ @param {Number} [tolerance = 1] Affects the amount of simplification (in the same metric as the point coordinates).
582
+ @param {Boolean} [highestQuality = false] Excludes distance-based preprocessing step which leads to highest quality simplification but runs ~10-20 times slower.
583
+
584
+ */ var simplify = ((poly, tolerance = 1, highestQuality = false)=>{
585
+ if (poly.length <= 2) return poly;
586
+ const sqTolerance = tolerance * tolerance;
587
+ poly = highestQuality ? poly : simplifyRadialDist(poly, sqTolerance);
588
+ poly = simplifyDouglasPeucker(poly, sqTolerance);
589
+ return poly;
590
+ });
591
+
592
+ // Algorithm constants
593
+ const aspectRatioStep = 0.5; // step size for the aspect ratio
594
+ const angleStep = 5; // step size for angles (in degrees); has linear impact on running time
595
+ const polyCache = {};
596
+ /**
597
+ @typedef {Object} LargestRect
598
+ @desc The returned Object of the largestRect function.
599
+ @property {Number} width The width of the rectangle
600
+ @property {Number} height The height of the rectangle
601
+ @property {Number} cx The x coordinate of the rectangle's center
602
+ @property {Number} cy The y coordinate of the rectangle's center
603
+ @property {Number} angle The rotation angle of the rectangle in degrees. The anchor of rotation is the center point.
604
+ @property {Number} area The area of the largest rectangle.
605
+ @property {Array} points An array of x/y coordinates for each point in the rectangle, useful for rendering paths.
606
+ */ /**
607
+ @function largestRect
608
+ @author Daniel Smilkov [dsmilkov@gmail.com]
609
+ @desc An angle of zero means that the longer side of the polygon (the width) will be aligned with the x axis. An angle of 90 and/or -90 means that the longer side of the polygon (the width) will be aligned with the y axis. The value can be a number between -90 and 90 specifying the angle of rotation of the polygon, a string which is parsed to a number, or an array of numbers specifying the possible rotations of the polygon.
610
+ @param {Array} poly An Array of points that represent a polygon.
611
+ @param {Object} [options] An Object that allows for overriding various parameters of the algorithm.
612
+ @param {Number|String|Array} [options.angle = d3.range(-90, 95, 5)] The allowed rotations of the final rectangle.
613
+ @param {Number|String|Array} [options.aspectRatio] The ratio between the width and height of the rectangle. The value can be a number, a string which is parsed to a number, or an array of numbers specifying the possible aspect ratios of the final rectangle.
614
+ @param {Number} [options.maxAspectRatio = 15] The maximum aspect ratio (width/height) allowed for the rectangle. This property should only be used if the aspectRatio is not provided.
615
+ @param {Number} [options.minAspectRatio = 1] The minimum aspect ratio (width/height) allowed for the rectangle. This property should only be used if the aspectRatio is not provided.
616
+ @param {Number} [options.nTries = 20] The number of randomly drawn points inside the polygon which the algorithm explores as possible center points of the maximal rectangle.
617
+ @param {Number} [options.minHeight = 0] The minimum height of the rectangle.
618
+ @param {Number} [options.minWidth = 0] The minimum width of the rectangle.
619
+ @param {Number} [options.tolerance = 0.02] The simplification tolerance factor, between 0 and 1. A larger tolerance corresponds to more extensive simplification.
620
+ @param {Array} [options.origin] The center point of the rectangle. If specified, the rectangle will be fixed at that point, otherwise the algorithm optimizes across all possible points. The given value can be either a two dimensional array specifying the x and y coordinate of the origin or an array of two dimensional points specifying multiple possible center points of the rectangle.
621
+ @param {Boolean} [options.cache] Whether or not to cache the result, which would be used in subsequent calculations to preserve consistency and speed up calculation time.
622
+ @return {LargestRect}
623
+ */ function largestRect(poly, options = {}) {
624
+ if (poly.length < 3) {
625
+ if (options.verbose) console.error("polygon has to have at least 3 points", poly);
626
+ return null;
627
+ }
628
+ // For visualization debugging purposes
629
+ const events = [];
630
+ // User's input normalization
631
+ options = Object.assign({
632
+ angle: d3Array.range(-90, 90 + angleStep, angleStep),
633
+ cache: true,
634
+ maxAspectRatio: 15,
635
+ minAspectRatio: 1,
636
+ minHeight: 0,
637
+ minWidth: 0,
638
+ nTries: 20,
639
+ tolerance: 0.02,
640
+ verbose: false
641
+ }, options);
642
+ const angles = options.angle instanceof Array ? options.angle : typeof options.angle === "number" ? [
643
+ options.angle
644
+ ] : typeof options.angle === "string" && !isNaN(options.angle) ? [
645
+ Number(options.angle)
646
+ ] : [];
647
+ const aspectRatios = options.aspectRatio instanceof Array ? options.aspectRatio : typeof options.aspectRatio === "number" ? [
648
+ options.aspectRatio
649
+ ] : typeof options.aspectRatio === "string" && !isNaN(options.aspectRatio) ? [
650
+ Number(options.aspectRatio)
651
+ ] : [];
652
+ const origins = options.origin && options.origin instanceof Array ? options.origin[0] instanceof Array ? options.origin : [
653
+ options.origin
654
+ ] : [];
655
+ let cacheString;
656
+ if (options.cache) {
657
+ cacheString = d3Array.merge(poly).join(",");
658
+ cacheString += `-${options.minAspectRatio}`;
659
+ cacheString += `-${options.maxAspectRatio}`;
660
+ cacheString += `-${options.minHeight}`;
661
+ cacheString += `-${options.minWidth}`;
662
+ cacheString += `-${angles.join(",")}`;
663
+ cacheString += `-${origins.join(",")}`;
664
+ if (polyCache[cacheString]) return polyCache[cacheString];
665
+ }
666
+ const area = Math.abs(d3Polygon.polygonArea(poly)); // take absolute value of the signed area
667
+ if (area === 0) {
668
+ if (options.verbose) console.error("polygon has 0 area", poly);
669
+ return null;
670
+ }
671
+ // get the width of the bounding box of the original polygon to determine tolerance
672
+ let [minx, maxx] = d3Array.extent(poly, (d)=>d[0]);
673
+ let [miny, maxy] = d3Array.extent(poly, (d)=>d[1]);
674
+ // simplify polygon
675
+ const tolerance = Math.min(maxx - minx, maxy - miny) * options.tolerance;
676
+ if (tolerance > 0) poly = simplify(poly, tolerance);
677
+ if (options.events) events.push({
678
+ type: "simplify",
679
+ poly
680
+ });
681
+ // get the width of the bounding box of the simplified polygon
682
+ [minx, maxx] = d3Array.extent(poly, (d)=>d[0]);
683
+ [miny, maxy] = d3Array.extent(poly, (d)=>d[1]);
684
+ const [boxWidth, boxHeight] = [
685
+ maxx - minx,
686
+ maxy - miny
687
+ ];
688
+ // discretize the binary search for optimal width to a resolution of this times the polygon width
689
+ const widthStep = Math.min(boxWidth, boxHeight) / 50;
690
+ // populate possible center points with random points inside the polygon
691
+ if (!origins.length) {
692
+ // get the centroid of the polygon
693
+ const centroid = d3Polygon.polygonCentroid(poly);
694
+ if (!isFinite(centroid[0])) {
695
+ if (options.verbose) console.error("cannot find centroid", poly);
696
+ return null;
697
+ }
698
+ if (d3Polygon.polygonContains(poly, centroid)) origins.push(centroid);
699
+ let nTries = options.nTries;
700
+ // get few more points inside the polygon
701
+ while(nTries){
702
+ const rndX = Math.random() * boxWidth + minx;
703
+ const rndY = Math.random() * boxHeight + miny;
704
+ const rndPoint = [
705
+ rndX,
706
+ rndY
707
+ ];
708
+ if (d3Polygon.polygonContains(poly, rndPoint)) {
709
+ origins.push(rndPoint);
710
+ }
711
+ nTries--;
712
+ }
713
+ }
714
+ if (options.events) events.push({
715
+ type: "origins",
716
+ points: origins
717
+ });
718
+ let maxArea = 0;
719
+ let maxRect = null;
720
+ for(let ai = 0; ai < angles.length; ai++){
721
+ const angle = angles[ai];
722
+ const angleRad = -angle * Math.PI / 180;
723
+ if (options.events) events.push({
724
+ type: "angle",
725
+ angle
726
+ });
727
+ for(let i = 0; i < origins.length; i++){
728
+ const origOrigin = origins[i];
729
+ // generate improved origins
730
+ const [p1W, p2W] = polygonRayCast(poly, origOrigin, angleRad);
731
+ const [p1H, p2H] = polygonRayCast(poly, origOrigin, angleRad + Math.PI / 2);
732
+ const modifOrigins = [];
733
+ if (p1W && p2W) modifOrigins.push([
734
+ (p1W[0] + p2W[0]) / 2,
735
+ (p1W[1] + p2W[1]) / 2
736
+ ]); // average along with width axis
737
+ if (p1H && p2H) modifOrigins.push([
738
+ (p1H[0] + p2H[0]) / 2,
739
+ (p1H[1] + p2H[1]) / 2
740
+ ]); // average along with height axis
741
+ if (options.events) events.push({
742
+ type: "modifOrigin",
743
+ idx: i,
744
+ p1W,
745
+ p2W,
746
+ p1H,
747
+ p2H,
748
+ modifOrigins
749
+ });
750
+ for(let i = 0; i < modifOrigins.length; i++){
751
+ const origin = modifOrigins[i];
752
+ if (options.events) events.push({
753
+ type: "origin",
754
+ cx: origin[0],
755
+ cy: origin[1]
756
+ });
757
+ const [p1W, p2W] = polygonRayCast(poly, origin, angleRad);
758
+ if (p1W === null || p2W === null) continue;
759
+ const minSqDistW = Math.min(pointDistanceSquared(origin, p1W), pointDistanceSquared(origin, p2W));
760
+ const maxWidth = 2 * Math.sqrt(minSqDistW);
761
+ const [p1H, p2H] = polygonRayCast(poly, origin, angleRad + Math.PI / 2);
762
+ if (p1H === null || p2H === null) continue;
763
+ const minSqDistH = Math.min(pointDistanceSquared(origin, p1H), pointDistanceSquared(origin, p2H));
764
+ const maxHeight = 2 * Math.sqrt(minSqDistH);
765
+ if (maxWidth * maxHeight < maxArea) continue;
766
+ let aRatios = aspectRatios;
767
+ if (!aRatios.length) {
768
+ const minAspectRatio = Math.max(options.minAspectRatio, options.minWidth / maxHeight, maxArea / (maxHeight * maxHeight));
769
+ const maxAspectRatio = Math.min(options.maxAspectRatio, maxWidth / options.minHeight, maxWidth * maxWidth / maxArea);
770
+ aRatios = d3Array.range(minAspectRatio, maxAspectRatio + aspectRatioStep, aspectRatioStep);
771
+ }
772
+ for(let a = 0; a < aRatios.length; a++){
773
+ const aRatio = aRatios[a];
774
+ // do a binary search to find the max width that works
775
+ let left = Math.max(options.minWidth, Math.sqrt(maxArea * aRatio));
776
+ let right = Math.min(maxWidth, maxHeight * aRatio);
777
+ if (right * maxHeight < maxArea) continue;
778
+ if (options.events && right - left >= widthStep) events.push({
779
+ type: "aRatio",
780
+ aRatio
781
+ });
782
+ while(right - left >= widthStep){
783
+ const width = (left + right) / 2;
784
+ const height = width / aRatio;
785
+ const [cx, cy] = origin;
786
+ let rectPoly = [
787
+ [
788
+ cx - width / 2,
789
+ cy - height / 2
790
+ ],
791
+ [
792
+ cx + width / 2,
793
+ cy - height / 2
794
+ ],
795
+ [
796
+ cx + width / 2,
797
+ cy + height / 2
798
+ ],
799
+ [
800
+ cx - width / 2,
801
+ cy + height / 2
802
+ ]
803
+ ];
804
+ rectPoly = polygonRotate(rectPoly, angleRad, origin);
805
+ const insidePoly = polygonInside(rectPoly, poly);
806
+ if (insidePoly) {
807
+ // we know that the area is already greater than the maxArea found so far
808
+ maxArea = width * height;
809
+ rectPoly.push(rectPoly[0]);
810
+ maxRect = {
811
+ area: maxArea,
812
+ cx,
813
+ cy,
814
+ width,
815
+ height,
816
+ angle: -angle,
817
+ points: rectPoly
818
+ };
819
+ left = width; // increase the width in the binary search
820
+ } else {
821
+ right = width; // decrease the width in the binary search
822
+ }
823
+ if (options.events) events.push({
824
+ type: "rectangle",
825
+ areaFraction: width * height / area,
826
+ cx,
827
+ cy,
828
+ width,
829
+ height,
830
+ angle,
831
+ insidePoly
832
+ });
833
+ }
834
+ }
835
+ }
836
+ }
837
+ }
838
+ if (options.cache) {
839
+ polyCache[cacheString] = maxRect;
840
+ }
841
+ return options.events ? Object.assign(maxRect || {}, {
842
+ events
843
+ }) : maxRect;
844
+ }
845
+
846
+ /**
847
+ @function path2polygon
848
+ @desc Transforms a path string into an Array of points.
849
+ @param {String} path An SVG string path, commonly the "d" property of a <path> element.
850
+ @param {Number} [segmentLength = 50] The length of line segments when converting curves line segments. Higher values lower computation time, but will result in curves that are more rigid.
851
+ @returns {Array}
852
+ */ var path2polygon = ((path, segmentLength = 50)=>{
853
+ if (typeof document === "undefined") return [];
854
+ const svgPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
855
+ svgPath.setAttribute("d", path);
856
+ const len = svgPath.getTotalLength();
857
+ const NUM_POINTS = len / segmentLength < 10 ? len / 10 : len / segmentLength;
858
+ const points = [];
859
+ for(let i = 0; i < NUM_POINTS; i++){
860
+ const pt = svgPath.getPointAtLength(i * len / (NUM_POINTS - 1));
861
+ points.push([
862
+ pt.x,
863
+ pt.y
864
+ ]);
865
+ }
866
+ return points;
867
+ });
868
+
869
+ /**
870
+ @function pointDistance
871
+ @desc Calculates the pixel distance between two points.
872
+ @param {Array} p1 The first point, which should always be an `[x, y]` formatted Array.
873
+ @param {Array} p2 The second point, which should always be an `[x, y]` formatted Array.
874
+ @returns {Number}
875
+ */ var pointDistance = ((p1, p2)=>Math.sqrt(pointDistanceSquared(p1, p2)));
876
+
877
+ const pi = Math.PI;
878
+ /**
879
+ @function shapeEdgePoint
880
+ @desc Calculates the x/y position of a point at the edge of a shape, from the center of the shape, given a specified pixel distance and radian angle.
881
+ @param {Number} angle The angle, in radians, of the offset point.
882
+ @param {Number} distance The pixel distance away from the origin.
883
+ @returns {String} [shape = "circle"] The type of shape, which can be either "circle" or "square".
884
+ */ var shapeEdgePoint = ((angle, distance, shape = "circle")=>{
885
+ if (angle < 0) angle = pi * 2 + angle;
886
+ if (shape === "square") {
887
+ const diagonal = 45 * (pi / 180);
888
+ let x = 0, y = 0;
889
+ if (angle < pi / 2) {
890
+ const tan = Math.tan(angle);
891
+ x += angle < diagonal ? distance : distance / tan;
892
+ y += angle < diagonal ? tan * distance : distance;
893
+ } else if (angle <= pi) {
894
+ const tan = Math.tan(pi - angle);
895
+ x -= angle < pi - diagonal ? distance / tan : distance;
896
+ y += angle < pi - diagonal ? distance : tan * distance;
897
+ } else if (angle < diagonal + pi) {
898
+ x -= distance;
899
+ y -= Math.tan(angle - pi) * distance;
900
+ } else if (angle < 3 * pi / 2) {
901
+ x -= distance / Math.tan(angle - pi);
902
+ y -= distance;
903
+ } else if (angle < 2 * pi - diagonal) {
904
+ x += distance / Math.tan(2 * pi - angle);
905
+ y -= distance;
906
+ } else {
907
+ x += distance;
908
+ y -= Math.tan(2 * pi - angle) * distance;
909
+ }
910
+ return [
911
+ x,
912
+ y
913
+ ];
914
+ } else if (shape === "circle") {
915
+ return [
916
+ distance * Math.cos(angle),
917
+ distance * Math.sin(angle)
918
+ ];
919
+ } else return null;
920
+ });
921
+
922
+ exports.ckmeans = ckmeans;
923
+ exports.closest = closest;
924
+ exports.largestRect = largestRect;
925
+ exports.lineIntersection = lineIntersection;
926
+ exports.path2polygon = path2polygon;
927
+ exports.pointDistance = pointDistance;
928
+ exports.pointDistanceSquared = pointDistanceSquared;
929
+ exports.pointRotate = pointRotate;
930
+ exports.polygonInside = polygonInside;
931
+ exports.polygonRayCast = polygonRayCast;
932
+ exports.polygonRotate = polygonRotate;
933
+ exports.segmentBoxContains = segmentBoxContains;
934
+ exports.segmentsIntersect = segmentsIntersect;
935
+ exports.shapeEdgePoint = shapeEdgePoint;
936
+ exports.simplify = simplify;
937
+
938
+ }));
939
+ //# sourceMappingURL=d3plus-math.js.map