how to calculate volume in javascript from arbitrary points coordinate array like this one?
const points = [
[0, 1, 0],
[1, -1, 1],
[-1, -1, 1],
[0, -1, -1]
]
i've used the scipy.spatial.convexHull library to calculate volume, but i can't use python on my react js app, thus i need a javascript library that can perform the similar functionality. thanks in advance
This JavaScript library performs the Delaunay triangulation in arbitrary dimension. So you can use the same way I show you in Python.
Here I do it with Node:
var triangulate = require("delaunay-triangulate")
const vertices = [
[0.,0.,0.], [0.,1.,0.1], [1.,1.,0.1], [0.,1.,0.],
[0.,0.,1.], [0.,1.,1.1], [1.,1.,1.1], [0.,1.,1.]
];
const tetrahedra_indices = triangulate(vertices);
var tetrahedra = new Array(tetrahedra_indices.length);
for(let i = 0; i < tetrahedra.length; i++){
const indices = tetrahedra_indices[i];
tetrahedra[i] = [
vertices[indices[0]],
vertices[indices[1]],
vertices[indices[2]],
vertices[indices[3]]
];
}
const array1_minus_array2 = (arr1, arr2) => (
arr2.map(function(num, idx){ return num - arr1[idx] })
);
const det3x3 = arr => (
arr[0][0] * (arr[1][1]*arr[2][2] - arr[1][2]*arr[2][1]) -
arr[0][1] * (arr[1][0]*arr[2][2] - arr[1][2]*arr[2][0]) +
arr[0][2] * (arr[1][0]*arr[2][1] - arr[1][1]*arr[2][0])
);
const volume_tetrahedron = tetrahedron => {
const a = tetrahedron[0];
const b = tetrahedron[1];
const c = tetrahedron[2];
const d = tetrahedron[3];
const matrix3x3 = [
array1_minus_array2(a, d),
array1_minus_array2(b, d),
array1_minus_array2(c, d)
];
return Math.abs(det3x3(matrix3x3)) / 6;
};
const volumes = tetrahedra.map(volume_tetrahedron);
const volume = volumes.reduce( (a,b) => a + b );
console.log(volume);
// 0.5166666666666667