UNPKG

@d3plus/math

Version:

Mathematical functions to aid in calculating visualizations.

940 lines (889 loc) 42.7 kB
/* @d3plus/math v3.0.5 Mathematical functions to aid in calculating visualizations. Copyright (c) 2025 D3plus - https://d3plus.org @license MIT */ (function (factory) { typeof define === 'function' && define.amd ? define(factory) : factory(); })((function () { 'use strict'; if (typeof window !== "undefined") { (function () { try { if (typeof SVGElement === 'undefined' || Boolean(SVGElement.prototype.innerHTML)) { return; } } catch (e) { return; } function serializeNode (node) { switch (node.nodeType) { case 1: return serializeElementNode(node); case 3: return serializeTextNode(node); case 8: return serializeCommentNode(node); } } function serializeTextNode (node) { return node.textContent.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } function serializeCommentNode (node) { return '<!--' + node.nodeValue + '-->' } function serializeElementNode (node) { var output = ''; output += '<' + node.tagName; if (node.hasAttributes()) { [].forEach.call(node.attributes, function(attrNode) { output += ' ' + attrNode.name + '="' + attrNode.value + '"'; }); } output += '>'; if (node.hasChildNodes()) { [].forEach.call(node.childNodes, function(childNode) { output += serializeNode(childNode); }); } output += '</' + node.tagName + '>'; return output; } Object.defineProperty(SVGElement.prototype, 'innerHTML', { get: function () { var output = ''; [].forEach.call(this.childNodes, function(childNode) { output += serializeNode(childNode); }); return output; }, set: function (markup) { while (this.firstChild) { this.removeChild(this.firstChild); } try { var dXML = new DOMParser(); dXML.async = false; var sXML = '<svg xmlns=\'http://www.w3.org/2000/svg\' xmlns:xlink=\'http://www.w3.org/1999/xlink\'>' + markup + '</svg>'; var svgDocElement = dXML.parseFromString(sXML, 'text/xml').documentElement; [].forEach.call(svgDocElement.childNodes, function(childNode) { this.appendChild(this.ownerDocument.importNode(childNode, true)); }.bind(this)); } catch (e) { throw new Error('Error parsing markup string'); } } }); Object.defineProperty(SVGElement.prototype, 'innerSVG', { get: function () { return this.innerHTML; }, set: function (markup) { this.innerHTML = markup; } }); })(); } })); (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-array'), require('d3-polygon')) : typeof define === 'function' && define.amd ? define('@d3plus/math', ['exports', 'd3-array', 'd3-polygon'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.d3plus = {}, global.d3Array, global.d3Polygon)); })(this, (function (exports, d3Array, d3Polygon) { 'use strict'; /** @desc Sort an array of numbers by their numeric value, ensuring that the array is not changed in place. This is necessary because the default behavior of .sort in JavaScript is to sort arrays as string values [1, 10, 12, 102, 20].sort() // output [1, 10, 102, 12, 20] @param {Array<number>} array input array @return {Array<number>} sorted array @private @example numericSort([3, 2, 1]) // => [1, 2, 3] */ function numericSort(array) { return array.slice().sort((a, b)=>a - b); } /** 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. Values are compared with `===`, so objects and non-primitive objects are not handled in any special way. @private @param {Array} input an array of primitive values. @returns {number} count of unique values @example uniqueCountSorted([1, 2, 3]); // => 3 uniqueCountSorted([1, 1, 1]); // => 1 */ function uniqueCountSorted(input) { let lastSeenValue, uniqueValueCount = 0; for(let i = 0; i < input.length; i++){ if (i === 0 || input[i] !== lastSeenValue) { lastSeenValue = input[i]; uniqueValueCount++; } } return uniqueValueCount; } /** Create a new column x row matrix. @private @param {number} columns @param {number} rows @return {Array<Array<number>>} matrix @example makeMatrix(10, 10); */ function makeMatrix(columns, rows) { const matrix = []; for(let i = 0; i < columns; i++){ const column = []; for(let j = 0; j < rows; j++)column.push(0); matrix.push(column); } return matrix; } /** Generates incrementally computed values based on the sums and sums of squares for the data array @private @param {number} j @param {number} i @param {Array<number>} sums @param {Array<number>} sumsOfSquares @return {number} @example ssq(0, 1, [-1, 0, 2], [1, 1, 5]); */ function ssq(j, i, sums, sumsOfSquares) { let sji; // s(j, i) if (j > 0) { const muji = (sums[i] - sums[j - 1]) / (i - j + 1); // mu(j, i) sji = sumsOfSquares[i] - sumsOfSquares[j - 1] - (i - j + 1) * muji * muji; } else sji = sumsOfSquares[i] - sums[i] * sums[i] / (i + 1); if (sji < 0) return 0; return sji; } /** Function that recursively divides and conquers computations for cluster j @private @param {number} iMin Minimum index in cluster to be computed @param {number} iMax Maximum index in cluster to be computed @param {number} cluster Index of the cluster currently being computed @param {Array<Array<number>>} matrix @param {Array<Array<number>>} backtrackMatrix @param {Array<number>} sums @param {Array<number>} sumsOfSquares */ function fillMatrixColumn(iMin, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares) { if (iMin > iMax) return; // Start at midpoint between iMin and iMax const i = Math.floor((iMin + iMax) / 2); matrix[cluster][i] = matrix[cluster - 1][i - 1]; backtrackMatrix[cluster][i] = i; let jlow = cluster; // the lower end for j if (iMin > cluster) jlow = Math.max(jlow, backtrackMatrix[cluster][iMin - 1] || 0); jlow = Math.max(jlow, backtrackMatrix[cluster - 1][i] || 0); let jhigh = i - 1; // the upper end for j if (iMax < matrix.length - 1) jhigh = Math.min(jhigh, backtrackMatrix[cluster][iMax + 1] || 0); for(let j = jhigh; j >= jlow; --j){ const sji = ssq(j, i, sums, sumsOfSquares); if (sji + matrix[cluster - 1][jlow - 1] >= matrix[cluster][i]) break; // Examine the lower bound of the cluster border const sjlowi = ssq(jlow, i, sums, sumsOfSquares); const ssqjlow = sjlowi + matrix[cluster - 1][jlow - 1]; if (ssqjlow < matrix[cluster][i]) { // Shrink the lower bound matrix[cluster][i] = ssqjlow; backtrackMatrix[cluster][i] = jlow; } jlow++; const ssqj = sji + matrix[cluster - 1][j - 1]; if (ssqj < matrix[cluster][i]) { matrix[cluster][i] = ssqj; backtrackMatrix[cluster][i] = j; } } fillMatrixColumn(iMin, i - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares); fillMatrixColumn(i + 1, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares); } /** Initializes the main matrices used in Ckmeans and kicks off the divide and conquer cluster computation strategy @private @param {Array<number>} data sorted array of values @param {Array<Array<number>>} matrix @param {Array<Array<number>>} backtrackMatrix */ function fillMatrices(data, matrix, backtrackMatrix) { const nValues = matrix[0] ? matrix[0].length : 0; // Shift values by the median to improve numeric stability const shift = data[Math.floor(nValues / 2)]; // Cumulative sum and cumulative sum of squares for all values in data array const sums = []; const sumsOfSquares = []; // Initialize first column in matrix & backtrackMatrix for(let i = 0, shiftedValue = void 0; i < nValues; ++i){ shiftedValue = data[i] - shift; if (i === 0) { sums.push(shiftedValue); sumsOfSquares.push(shiftedValue * shiftedValue); } else { sums.push(sums[i - 1] + shiftedValue); sumsOfSquares.push(sumsOfSquares[i - 1] + shiftedValue * shiftedValue); } // Initialize for cluster = 0 matrix[0][i] = ssq(0, i, sums, sumsOfSquares); backtrackMatrix[0][i] = 0; } // Initialize the rest of the columns for(let cluster = 1; cluster < matrix.length; ++cluster){ let iMin = nValues - 1; if (cluster < matrix.length - 1) iMin = cluster; fillMatrixColumn(iMin, nValues - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares); } } /** @module ckmeans @desc Ported to ES6 from the excellent [simple-statistics](https://github.com/simple-statistics/simple-statistics) packages. 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. 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. Being a dynamic approach, this algorithm is based on two matrices that store incrementally-computed values for squared deviations and backtracking indexes. 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)). 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. ### References _Ckmeans.1d.dp: Optimal k-means Clustering in One Dimension by Dynamic Programming_ Haizhou Wang and Mingzhou Song ISSN 2073-4859 from The R Journal Vol. 3/2, December 2011 @param {Array<number>} data input data, as an array of number values @param {number} nClusters number of desired classes. This cannot be greater than the number of values in the data array. @returns {Array<Array<number>>} clustered input @private @example ckmeans([-1, 2, -1, 2, 4, 5, 6, -1, 2, -1], 3); // The input, clustered into groups of similar numbers. //= [[-1, -1, -1, -1], [2, 2, 2], [4, 5, 6]]); */ function ckmeans(data, nClusters) { if (nClusters > data.length) { throw new Error("Cannot generate more classes than there are data values"); } const sorted = numericSort(data); // we'll use this as the maximum number of clusters const uniqueCount = uniqueCountSorted(sorted); // if all of the input values are identical, there's one cluster with all of the input in it. if (uniqueCount === 1) { return [ sorted ]; } const backtrackMatrix = makeMatrix(nClusters, sorted.length), matrix = makeMatrix(nClusters, sorted.length); // 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. fillMatrices(sorted, matrix, backtrackMatrix); // 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. let clusterRight = backtrackMatrix[0] ? backtrackMatrix[0].length - 1 : 0; const clusters = []; // 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. for(let cluster = backtrackMatrix.length - 1; cluster >= 0; cluster--){ const clusterLeft = backtrackMatrix[cluster][clusterRight]; // 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. clusters[cluster] = sorted.slice(clusterLeft, clusterRight + 1); if (cluster > 0) clusterRight = clusterLeft - 1; } return clusters; } /** @function closest @desc Finds the closest numeric value in an array. @param {Number} n The number value to use when searching the array. @param {Array} arr The array of values to test against. */ function closest(n, arr = []) { if (!arr || !(arr instanceof Array) || !arr.length) return undefined; return arr.reduce((prev, curr)=>Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev); } /** @function lineIntersection @desc Finds the intersection point (if there is one) of the lines p1q1 and p2q2. @param {Array} p1 The first point of the first line segment, which should always be an `[x, y]` formatted Array. @param {Array} q1 The second point of the first line segment, which should always be an `[x, y]` formatted Array. @param {Array} p2 The first point of the second line segment, which should always be an `[x, y]` formatted Array. @param {Array} q2 The second point of the second line segment, which should always be an `[x, y]` formatted Array. @returns {Boolean} */ function lineIntersection(p1, q1, p2, q2) { // allow for some margins due to numerical errors const eps = 1e-9; // find the intersection point between the two infinite lines const dx1 = p1[0] - q1[0], dx2 = p2[0] - q2[0], dy1 = p1[1] - q1[1], dy2 = p2[1] - q2[1]; const denom = dx1 * dy2 - dy1 * dx2; if (Math.abs(denom) < eps) return null; const cross1 = p1[0] * q1[1] - p1[1] * q1[0], cross2 = p2[0] * q2[1] - p2[1] * q2[0]; const px = (cross1 * dx2 - cross2 * dx1) / denom, py = (cross1 * dy2 - cross2 * dy1) / denom; return [ px, py ]; } /** @function segmentBoxContains @desc Checks whether a point is inside the bounding box of a line segment. @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. @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. @param {Array} p The point to be checked, which should always be an `[x, y]` formatted Array. @returns {Boolean} */ function segmentBoxContains(s1, s2, p) { const eps = 1e-9, [px, py] = p; 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); } /** @function segmentsIntersect @desc Checks whether the line segments p1q1 && p2q2 intersect. @param {Array} p1 The first point of the first line segment, which should always be an `[x, y]` formatted Array. @param {Array} q1 The second point of the first line segment, which should always be an `[x, y]` formatted Array. @param {Array} p2 The first point of the second line segment, which should always be an `[x, y]` formatted Array. @param {Array} q2 The second point of the second line segment, which should always be an `[x, y]` formatted Array. @returns {Boolean} */ function segmentsIntersect(p1, q1, p2, q2) { const p = lineIntersection(p1, q1, p2, q2); if (!p) return false; return segmentBoxContains(p1, q1, p) && segmentBoxContains(p2, q2, p); } /** @function polygonInside @desc Checks if one polygon is inside another polygon. @param {Array} polyA An Array of `[x, y]` points to be used as the inner polygon, checking if it is inside polyA. @param {Array} polyB An Array of `[x, y]` points to be used as the containing polygon. @returns {Boolean} */ function polygonInside(polyA, polyB) { let iA = -1; const nA = polyA.length; const nB = polyB.length; let bA = polyA[nA - 1]; while(++iA < nA){ const aA = bA; bA = polyA[iA]; let iB = -1; let bB = polyB[nB - 1]; while(++iB < nB){ const aB = bB; bB = polyB[iB]; if (segmentsIntersect(aA, bA, aB, bB)) return false; } } return d3Polygon.polygonContains(polyB, polyA[0]); } /** @function pointDistanceSquared @desc Returns the squared euclidean distance between two points. @param {Array} p1 The first point, which should always be an `[x, y]` formatted Array. @param {Array} p2 The second point, which should always be an `[x, y]` formatted Array. @returns {Number} */ var pointDistanceSquared = ((p1, p2)=>{ const dx = p2[0] - p1[0], dy = p2[1] - p1[1]; return dx * dx + dy * dy; }); /** @function polygonRayCast @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. @param {Array} poly The polygon to test against, which should be an `[x, y]` formatted Array. @param {Array} origin The origin point of the ray to be cast, which should be an `[x, y]` formatted Array. @param {Number} [alpha = 0] The angle in radians of the ray. @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`. */ function polygonRayCast(poly, origin, alpha = 0) { const eps = 1e-9; origin = [ origin[0] + eps * Math.cos(alpha), origin[1] + eps * Math.sin(alpha) ]; const [x0, y0] = origin; const shiftedOrigin = [ x0 + Math.cos(alpha), y0 + Math.sin(alpha) ]; let idx = 0; if (Math.abs(shiftedOrigin[0] - x0) < eps) idx = 1; let i = -1; const n = poly.length; let b = poly[n - 1]; let minSqDistLeft = Number.MAX_VALUE; let minSqDistRight = Number.MAX_VALUE; let closestPointLeft = null; let closestPointRight = null; while(++i < n){ const a = b; b = poly[i]; const p = lineIntersection(origin, shiftedOrigin, a, b); if (p && segmentBoxContains(a, b, p)) { const sqDist = pointDistanceSquared(origin, p); if (p[idx] < origin[idx]) { if (sqDist < minSqDistLeft) { minSqDistLeft = sqDist; closestPointLeft = p; } } else if (p[idx] > origin[idx]) { if (sqDist < minSqDistRight) { minSqDistRight = sqDist; closestPointRight = p; } } } } return [ closestPointLeft, closestPointRight ]; } /** @function pointRotate @desc Rotates a point around a given origin. @param {Array} p The point to be rotated, which should always be an `[x, y]` formatted Array. @param {Number} alpha The angle in radians to rotate. @param {Array} [origin = [0, 0]] The origin point of the rotation, which should always be an `[x, y]` formatted Array. @returns {Boolean} */ function pointRotate(p, alpha, origin = [ 0, 0 ]) { const cosAlpha = Math.cos(alpha), sinAlpha = Math.sin(alpha), xshifted = p[0] - origin[0], yshifted = p[1] - origin[1]; return [ cosAlpha * xshifted - sinAlpha * yshifted + origin[0], sinAlpha * xshifted + cosAlpha * yshifted + origin[1] ]; } /** @function polygonRotate @desc Rotates a point around a given origin. @param {Array} poly The polygon to be rotated, which should be an Array of `[x, y]` values. @param {Number} alpha The angle in radians to rotate. @param {Array} [origin = [0, 0]] The origin point of the rotation, which should be an `[x, y]` formatted Array. @returns {Boolean} */ var polygonRotate = ((poly, alpha, origin = [ 0, 0 ])=>poly.map((p)=>pointRotate(p, alpha, origin))); /** @desc square distance from a point to a segment @param {Array} point @param {Array} segmentAnchor1 @param {Array} segmentAnchor2 @private */ function getSqSegDist(p, p1, p2) { let x = p1[0], y = p1[1]; let dx = p2[0] - x, dy = p2[1] - y; if (dx !== 0 || dy !== 0) { const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy); if (t > 1) { x = p2[0]; y = p2[1]; } else if (t > 0) { x += dx * t; y += dy * t; } } dx = p[0] - x; dy = p[1] - y; return dx * dx + dy * dy; } /** @desc basic distance-based simplification @param {Array} polygon @param {Number} sqTolerance @private */ function simplifyRadialDist(poly, sqTolerance) { let point, prevPoint = poly[0]; const newPoints = [ prevPoint ]; for(let i = 1, len = poly.length; i < len; i++){ point = poly[i]; if (pointDistanceSquared(point, prevPoint) > sqTolerance) { newPoints.push(point); prevPoint = point; } } if (prevPoint !== point) newPoints.push(point); return newPoints; } /** @param {Array} polygon @param {Number} first @param {Number} last @param {Number} sqTolerance @param {Array} simplified @private */ function simplifyDPStep(poly, first, last, sqTolerance, simplified) { let index, maxSqDist = sqTolerance; for(let i = first + 1; i < last; i++){ const sqDist = getSqSegDist(poly[i], poly[first], poly[last]); if (sqDist > maxSqDist) { index = i; maxSqDist = sqDist; } } if (maxSqDist > sqTolerance) { if (index - first > 1) simplifyDPStep(poly, first, index, sqTolerance, simplified); simplified.push(poly[index]); if (last - index > 1) simplifyDPStep(poly, index, last, sqTolerance, simplified); } } /** @desc simplification using Ramer-Douglas-Peucker algorithm @param {Array} polygon @param {Number} sqTolerance @private */ function simplifyDouglasPeucker(poly, sqTolerance) { const last = poly.length - 1; const simplified = [ poly[0] ]; simplifyDPStep(poly, 0, last, sqTolerance, simplified); simplified.push(poly[last]); return simplified; } /** @function largestRect @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/). @author Vladimir Agafonkin @param {Array} poly An Array of points that represent a polygon. @param {Number} [tolerance = 1] Affects the amount of simplification (in the same metric as the point coordinates). @param {Boolean} [highestQuality = false] Excludes distance-based preprocessing step which leads to highest quality simplification but runs ~10-20 times slower. */ var simplify = ((poly, tolerance = 1, highestQuality = false)=>{ if (poly.length <= 2) return poly; const sqTolerance = tolerance * tolerance; poly = highestQuality ? poly : simplifyRadialDist(poly, sqTolerance); poly = simplifyDouglasPeucker(poly, sqTolerance); return poly; }); // Algorithm constants const aspectRatioStep = 0.5; // step size for the aspect ratio const angleStep = 5; // step size for angles (in degrees); has linear impact on running time const polyCache = {}; /** @typedef {Object} largestRect @desc The returned Object of the largestRect function. @property {Number} width The width of the rectangle @property {Number} height The height of the rectangle @property {Number} cx The x coordinate of the rectangle's center @property {Number} cy The y coordinate of the rectangle's center @property {Number} angle The rotation angle of the rectangle in degrees. The anchor of rotation is the center point. @property {Number} area The area of the largest rectangle. @property {Array} points An array of x/y coordinates for each point in the rectangle, useful for rendering paths. */ /** @function largestRect @author Daniel Smilkov [dsmilkov@gmail.com] @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. @param {Array} poly An Array of points that represent a polygon. @param {Object} [options] An Object that allows for overriding various parameters of the algorithm. @param {Number|String|Array} [options.angle = d3.range(-90, 95, 5)] The allowed rotations of the final rectangle. @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. @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. @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. @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. @param {Number} [options.minHeight = 0] The minimum height of the rectangle. @param {Number} [options.minWidth = 0] The minimum width of the rectangle. @param {Number} [options.tolerance = 0.02] The simplification tolerance factor, between 0 and 1. A larger tolerance corresponds to more extensive simplification. @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. @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. @return {largestRect} */ function largestRect(poly, options = {}) { if (poly.length < 3) { if (options.verbose) console.error("polygon has to have at least 3 points", poly); return null; } // For visualization debugging purposes const events = []; // User's input normalization options = Object.assign({ angle: d3Array.range(-90, 90 + angleStep, angleStep), cache: true, maxAspectRatio: 15, minAspectRatio: 1, minHeight: 0, minWidth: 0, nTries: 20, tolerance: 0.02, verbose: false }, options); const angles = options.angle instanceof Array ? options.angle : typeof options.angle === "number" ? [ options.angle ] : typeof options.angle === "string" && !isNaN(options.angle) ? [ Number(options.angle) ] : []; const aspectRatios = options.aspectRatio instanceof Array ? options.aspectRatio : typeof options.aspectRatio === "number" ? [ options.aspectRatio ] : typeof options.aspectRatio === "string" && !isNaN(options.aspectRatio) ? [ Number(options.aspectRatio) ] : []; const origins = options.origin && options.origin instanceof Array ? options.origin[0] instanceof Array ? options.origin : [ options.origin ] : []; let cacheString; if (options.cache) { cacheString = d3Array.merge(poly).join(","); cacheString += `-${options.minAspectRatio}`; cacheString += `-${options.maxAspectRatio}`; cacheString += `-${options.minHeight}`; cacheString += `-${options.minWidth}`; cacheString += `-${angles.join(",")}`; cacheString += `-${origins.join(",")}`; if (polyCache[cacheString]) return polyCache[cacheString]; } const area = Math.abs(d3Polygon.polygonArea(poly)); // take absolute value of the signed area if (area === 0) { if (options.verbose) console.error("polygon has 0 area", poly); return null; } // get the width of the bounding box of the original polygon to determine tolerance let [minx, maxx] = d3Array.extent(poly, (d)=>d[0]); let [miny, maxy] = d3Array.extent(poly, (d)=>d[1]); // simplify polygon const tolerance = Math.min(maxx - minx, maxy - miny) * options.tolerance; if (tolerance > 0) poly = simplify(poly, tolerance); if (options.events) events.push({ type: "simplify", poly }); // get the width of the bounding box of the simplified polygon [minx, maxx] = d3Array.extent(poly, (d)=>d[0]); [miny, maxy] = d3Array.extent(poly, (d)=>d[1]); const [boxWidth, boxHeight] = [ maxx - minx, maxy - miny ]; // discretize the binary search for optimal width to a resolution of this times the polygon width const widthStep = Math.min(boxWidth, boxHeight) / 50; // populate possible center points with random points inside the polygon if (!origins.length) { // get the centroid of the polygon const centroid = d3Polygon.polygonCentroid(poly); if (!isFinite(centroid[0])) { if (options.verbose) console.error("cannot find centroid", poly); return null; } if (d3Polygon.polygonContains(poly, centroid)) origins.push(centroid); let nTries = options.nTries; // get few more points inside the polygon while(nTries){ const rndX = Math.random() * boxWidth + minx; const rndY = Math.random() * boxHeight + miny; const rndPoint = [ rndX, rndY ]; if (d3Polygon.polygonContains(poly, rndPoint)) { origins.push(rndPoint); } nTries--; } } if (options.events) events.push({ type: "origins", points: origins }); let maxArea = 0; let maxRect = null; for(let ai = 0; ai < angles.length; ai++){ const angle = angles[ai]; const angleRad = -angle * Math.PI / 180; if (options.events) events.push({ type: "angle", angle }); for(let i = 0; i < origins.length; i++){ const origOrigin = origins[i]; // generate improved origins const [p1W, p2W] = polygonRayCast(poly, origOrigin, angleRad); const [p1H, p2H] = polygonRayCast(poly, origOrigin, angleRad + Math.PI / 2); const modifOrigins = []; if (p1W && p2W) modifOrigins.push([ (p1W[0] + p2W[0]) / 2, (p1W[1] + p2W[1]) / 2 ]); // average along with width axis if (p1H && p2H) modifOrigins.push([ (p1H[0] + p2H[0]) / 2, (p1H[1] + p2H[1]) / 2 ]); // average along with height axis if (options.events) events.push({ type: "modifOrigin", idx: i, p1W, p2W, p1H, p2H, modifOrigins }); for(let i = 0; i < modifOrigins.length; i++){ const origin = modifOrigins[i]; if (options.events) events.push({ type: "origin", cx: origin[0], cy: origin[1] }); const [p1W, p2W] = polygonRayCast(poly, origin, angleRad); if (p1W === null || p2W === null) continue; const minSqDistW = Math.min(pointDistanceSquared(origin, p1W), pointDistanceSquared(origin, p2W)); const maxWidth = 2 * Math.sqrt(minSqDistW); const [p1H, p2H] = polygonRayCast(poly, origin, angleRad + Math.PI / 2); if (p1H === null || p2H === null) continue; const minSqDistH = Math.min(pointDistanceSquared(origin, p1H), pointDistanceSquared(origin, p2H)); const maxHeight = 2 * Math.sqrt(minSqDistH); if (maxWidth * maxHeight < maxArea) continue; let aRatios = aspectRatios; if (!aRatios.length) { const minAspectRatio = Math.max(options.minAspectRatio, options.minWidth / maxHeight, maxArea / (maxHeight * maxHeight)); const maxAspectRatio = Math.min(options.maxAspectRatio, maxWidth / options.minHeight, maxWidth * maxWidth / maxArea); aRatios = d3Array.range(minAspectRatio, maxAspectRatio + aspectRatioStep, aspectRatioStep); } for(let a = 0; a < aRatios.length; a++){ const aRatio = aRatios[a]; // do a binary search to find the max width that works let left = Math.max(options.minWidth, Math.sqrt(maxArea * aRatio)); let right = Math.min(maxWidth, maxHeight * aRatio); if (right * maxHeight < maxArea) continue; if (options.events && right - left >= widthStep) events.push({ type: "aRatio", aRatio }); while(right - left >= widthStep){ const width = (left + right) / 2; const height = width / aRatio; const [cx, cy] = origin; let rectPoly = [ [ cx - width / 2, cy - height / 2 ], [ cx + width / 2, cy - height / 2 ], [ cx + width / 2, cy + height / 2 ], [ cx - width / 2, cy + height / 2 ] ]; rectPoly = polygonRotate(rectPoly, angleRad, origin); const insidePoly = polygonInside(rectPoly, poly); if (insidePoly) { // we know that the area is already greater than the maxArea found so far maxArea = width * height; rectPoly.push(rectPoly[0]); maxRect = { area: maxArea, cx, cy, width, height, angle: -angle, points: rectPoly }; left = width; // increase the width in the binary search } else { right = width; // decrease the width in the binary search } if (options.events) events.push({ type: "rectangle", areaFraction: width * height / area, cx, cy, width, height, angle, insidePoly }); } } } } } if (options.cache) { polyCache[cacheString] = maxRect; } return options.events ? Object.assign(maxRect || {}, { events }) : maxRect; } /** @function path2polygon @desc Transforms a path string into an Array of points. @param {String} path An SVG string path, commonly the "d" property of a <path> element. @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. @returns {Array} */ var path2polygon = ((path, segmentLength = 50)=>{ if (typeof document === "undefined") return []; const svgPath = document.createElementNS("http://www.w3.org/2000/svg", "path"); svgPath.setAttribute("d", path); const len = svgPath.getTotalLength(); const NUM_POINTS = len / segmentLength < 10 ? len / 10 : len / segmentLength; const points = []; for(let i = 0; i < NUM_POINTS; i++){ const pt = svgPath.getPointAtLength(i * len / (NUM_POINTS - 1)); points.push([ pt.x, pt.y ]); } return points; }); /** @function pointDistance @desc Calculates the pixel distance between two points. @param {Array} p1 The first point, which should always be an `[x, y]` formatted Array. @param {Array} p2 The second point, which should always be an `[x, y]` formatted Array. @returns {Number} */ var pointDistance = ((p1, p2)=>Math.sqrt(pointDistanceSquared(p1, p2))); const pi = Math.PI; /** @function shapeEdgePoint @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. @param {Number} angle The angle, in radians, of the offset point. @param {Number} distance The pixel distance away from the origin. @returns {String} [shape = "circle"] The type of shape, which can be either "circle" or "square". */ var shapeEdgePoint = ((angle, distance, shape = "circle")=>{ if (angle < 0) angle = pi * 2 + angle; if (shape === "square") { const diagonal = 45 * (pi / 180); let x = 0, y = 0; if (angle < pi / 2) { const tan = Math.tan(angle); x += angle < diagonal ? distance : distance / tan; y += angle < diagonal ? tan * distance : distance; } else if (angle <= pi) { const tan = Math.tan(pi - angle); x -= angle < pi - diagonal ? distance / tan : distance; y += angle < pi - diagonal ? distance : tan * distance; } else if (angle < diagonal + pi) { x -= distance; y -= Math.tan(angle - pi) * distance; } else if (angle < 3 * pi / 2) { x -= distance / Math.tan(angle - pi); y -= distance; } else if (angle < 2 * pi - diagonal) { x += distance / Math.tan(2 * pi - angle); y -= distance; } else { x += distance; y -= Math.tan(2 * pi - angle) * distance; } return [ x, y ]; } else if (shape === "circle") { return [ distance * Math.cos(angle), distance * Math.sin(angle) ]; } else return null; }); exports.ckmeans = ckmeans; exports.closest = closest; exports.largestRect = largestRect; exports.lineIntersection = lineIntersection; exports.path2polygon = path2polygon; exports.pointDistance = pointDistance; exports.pointDistanceSquared = pointDistanceSquared; exports.pointRotate = pointRotate; exports.polygonInside = polygonInside; exports.polygonRayCast = polygonRayCast; exports.polygonRotate = polygonRotate; exports.segmentBoxContains = segmentBoxContains; exports.segmentsIntersect = segmentsIntersect; exports.shapeEdgePoint = shapeEdgePoint; exports.simplify = simplify; })); //# sourceMappingURL=d3plus-math.js.map