在Java脚本中根据点坐标计算体积

2022-05-29 00:00:00 geometry spatial volume javascript

如何从这样的任意点坐标数组在Java脚本中计算体积?

const points = [
  [0, 1, 0],
  [1, -1, 1],
  [-1, -1, 1],
  [0, -1, -1]
]

我使用了scipy.spatial.vvexHull库来计算体积,但我不能在我的react js应用程序上使用python,因此我需要一个能够执行类似功能的javascrip库。提前感谢


解决方案

This JavaScript library执行任意维度的Delaunay三角剖分。因此,您可以使用我在Python中向您展示的相同方式。

我在这里使用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

相关文章