4

I am trying to find the volume given a set of data points (x,y,z) using python. These data points are samples collected from an experiment (so the plotted surface can be quite irregular). I have worked out how to create a 3D plot but not how to calculate the volume using python.

X, Y = np.meshgrid(x, y)
Z = griddata(xpts, ypts, zpts, x, y)
fig = plt.figure()
ax = fig.gca(projection='3d')               
surf = ax.plot_surface(X, Y, Z,           
                       rstride=5,           
                       cstride=5,           
                       cmap=cm.jet,         
                       linewidth=0,         
                       antialiased=True,
                       vmin=np.nanmin(Z),
                       vmax = np.nanmax(Z))

Here's a similar question to find the area under an irregular surface using python, Volume under "plane" defined by data points - python. Could this be adapted to find the volume? Any help is appreciated. Thanks.

Community
  • 1
  • 1
Peter Q
  • 43
  • 1
  • 3
  • First you have to define the body you are trying to find the volume of, the rest is relatively straightforward. – Mad Physicist Apr 01 '17 at 05:19
  • For example, if I were to give you the points `0,0`, `2,0`, `1,1`, `1,2` in 2D, what would be the enclosing shape to find the area? – Mad Physicist Apr 01 '17 at 05:22
  • convex hull of a point cloud is well defined, pretty much anything else is really hard, "subjective" and/or ill defined – f5r5e5d Apr 01 '17 at 05:29
  • 1
    If the points are imprecise, anyway, why not approximate them with a polynomial surface and calculate the volume by integration. – DYZ Apr 01 '17 at 05:58
  • 2
    The question you link to already asks for the **volume** between the surface and a plane, not the area. So what exactly is different in this case? Make that expicitely clear in the question and best add the plot to it, such that one can see which kind of surface you have. – ImportanceOfBeingErnest Apr 01 '17 at 22:29
  • the link returns the area under the surface . If you enter in the coordinates for a 2 x 2 x 2 cube, at the origin, it returns 2 (area on the x plane). – Peter Q Apr 02 '17 at 03:53

1 Answers1

6

I would be lazy and use ConvexHull like a black box:

import scipy.spatial as ss
import numpy as np
npoints = 6
ndimensions = 3
points = np.random.rand(npoints, ndimensions)
hull = ss.ConvexHull(points)
print('volume inside points is: ',hull.volume)

though this is probably not CPU-optimized since ConvexHull computes a bunch of things.

Hope this helps.

Stéphane
  • 1,389
  • 3
  • 13
  • 34
  • Perfect. Thank you @Stéphane. New to python so this was a real help. Found this link regarding computation time. [Volume of convex hull with qhull](http://stackoverflow.com/questions/24733185/volume-of-convex-hull-with-qhull-from-scipy) – Peter Q Apr 02 '17 at 04:31