Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the volume of a 3D polyhedron with Python?

Tags:

python

spatial

I am trying to figure out the best way of calculating the volume of a 3D polyhedron with Python, and I'm hoping there is a simple solution out there, which I can't seem to find.

Example polyhedron Example Polyhedron

I did find this post that describes calculating the area of a planar polygon in 3D space, but that doesn't seem to help.

like image 451
ryanjdillon Avatar asked Jun 16 '13 00:06

ryanjdillon


2 Answers

If you only have convex polyhedrons you can use the QHull binding of scipy.spatial.ConvexHull.

    import numpy as np
    from scipy.spatial import ConvexHull

    points = np.array([[....]])  # your points
    volume = ConvexHull(points).volume

Additionally, with the module Delaunay you can triangulate your passed points into tetrahedra for other stuff..

like image 106
MagnusBadel Avatar answered Sep 22 '22 14:09

MagnusBadel


Is your polygon such that you can find a point inside so that you can connect every vertex to the point without crossing a face? If so, you can subdivide each face into triangles. You can do this easily by letting one vertex of a face be a pivot point and drawing lines from the other vertices to the pivot vertex. For instance, a pentagon gets divided into three triangles that fan from a common vertex. Each triangle will form a tetrahedron (a 3-sided pyramid) with the point inside. You can then add up the volumes of all of the tetrahedra for each face. The following is for a convex polyhedron that surrounds the origin (x=0,y=0,z=0). It assumes that there is a list of faces f, and each face has a list of vertices v.

def volume(self):
  ''' calculate volume of polyhedron '''
  vol = 0.
  for f in self.f: # the faces
    n = len(f.v)
    v2 = f.v[0] # the pivot of the fan
    x2 = v2.x
    y2 = v2.y
    z2 = v2.z
    for i in range(1,n-1): # divide into triangular fan segments
      v0 = f.v[i]
      x0 = v0.x
      y0 = v0.y
      z0 = v0.z
      v1 = f.v[i+1]
      x1 = v1.x
      y1 = v1.y
      z1 = v1.z
      # Add volume of tetrahedron formed by triangle and origin
      vol += math.fabs(x0 * y1 * z2 + x1 * y2 * z0 \
                     + x2 * y0 * z1 - x0 * y2 * z1 \
                    - x1 * y0 * z2 - x2 * y1 * z0)
 return vol/6.
like image 43
R. Strickland Avatar answered Sep 22 '22 14:09

R. Strickland