contour
by jpeter06
HTML
<script src="https://d3js.org/d3-array.v2.min.js"></script>
<script src="https://d3js.org/d3-contour.v2.min.js"></script>
<div #svgContainer class="svgContainer">
<svg
class="svg-content"
viewBox="0 0 35 35"
width="100%"
height="100%"
>
<polygon points="25, 3.5, 25, 2.5, 25, 1.5, 25, 0.5, 24.5, 0, 23.5, 0, 22.733129027646388, 0.5, 22.5, 1.4596041311349714, 22.48657982871376, 1.5, 22.301105165853624, 2.5, 22.478715647395585, 3.5, 22.5, 3.5235747968712525, 23.5, 3.8398744456992073, 24.5, 3.639144598470901, 25, 3.5"
style="fill:lime;stroke:purple;stroke-width:0.1;fill-rule:nonzero;" />
<polygon points="25, 24.5, 25, 23.5, 25, 22.5, 25, 21.5, 25, 20.5, 25, 19.5, 25, 18.5, 25, 17.5, 25, 16.5, 25, 15.5, 25, 14.5, 25, 13.5, 25, 12.5, 25, 11.5, 25, 10.5, 25, 9.5, 25, 8.5, 24.5, 7.557260606827263, 23.611231193969743, 8.5, 23.5, 8.640830344130586, 22.694300256711962, 9.5, 22.5, 9.749024592707201, 21.800625293728256, 10.5, 21.5, 10.892437507773144, 20.940309326550956, 11.5, 20.5, 12.093046030749276, 20.13199602440665, 12.5, 19.5, 13.398907148795514, 19.411455295852804, 13.5, 18.66151063145258, 14.5, 18.5, 14.803920062344162, 18.00096240462284, 15.5, 17.559840192319015, 16.5, 17.5, 16.707662171737415, 17.144374551630396, 17.5, 16.934478108627882, 18.5, 16.904662557275206, 19.5, 17.023552084823397, 20.5, 17.320570867550973, 21.5, 17.5, 21.862606339699333, 17.63399559355684, 22.5, 17.820345008590813, 23.5, 17.5, 23.792185190205032, 17.028936254704128, 23.5, 16.5, 23.108540550081965, 15.5, 22.53533537228779, 15.412875351809818, 22.5, 14.5, 21.90031894417837, 13.5, 21.596261520701603, 12.717443138970085, 21.5, 12.5, 21.445541030478246, 11.5, 21.462167802794788, 11.354496447353458, 21.5, 10.5, 21.606035726023425, 9.5, 21.865206543248227, 8.5, 22.353663719174637, 8.283968417683639, 22.5, 7.5, 22.80292588740459, 6.5002415382828405, 23.5, 6.5, 23.500102433414696, 5.5, 23.97372836106659, 4.846553418292937, 24.5, 5.5, 25, 6.5, 25, 7.5, 25, 8.5, 25,...
CSS
html, body{
margin:0px;
padding:0px;
width:100%;
height:100%;
overflow:hidden;
}
.svgContainer {
display: flex;
flex-grow: 1;
background:tan;
}
JavaScript
console.log("starting");
// Populate a grid of n×m values where -2 ≤ x ≤ 2 and -2 ≤ y ≤ 1.
var n = 25, m = 25, values = new Array(n * m);
for (var j = 0.5, k = 0; j < m; ++j) {
for (var i = 0.5; i < n; ++i, ++k) {
values[k] = goldsteinPrice(i / n * 4 - 2, 1 - j / m * 3);
}
}
// Compute the contour polygons at log-spaced intervals; returns an array of MultiPolygon.
var contours = d3.contours()
.size([n, m])
.thresholds(Array.from({ length: 19 }, (_, i) => Math.pow(2, i + 2)))
(values);
console.log(contours);
// See https://en.wikipedia.org/wiki/Test_functions_for_optimization
function goldsteinPrice(x, y) {
return (1 + Math.pow(x + y + 1, 2) * (19 - 14 * x + 3 * x * x - 14 * y + 6 * x * x + 3 * y * y))
* (30 + Math.pow(2 * x - 3 * y, 2) * (18 - 32 * x + 12 * x * x + 48 * y - 36 * x * y + 27 * y * y));
}