herisson
herisson

Reputation: 128

2D integration of scattered data (python)

I have some scattered data along X and Y with value A. I want to integrate A over X and Y. However my data isn't on a cartesian grid (X,Y spacing between data points changes a lot) and the X,Y domain occupied by the data points is a complex shape (exact area unknown)

Is there an easy way to integrate such data?

Upvotes: 1

Views: 752

Answers (1)

Fallen Apart
Fallen Apart

Reputation: 741

I have done the following:

  • triangulate the domain
  • calculate the integral over each triangle
  • sum the integrals over triangles (it can be done due to integral additivity property)

Let's say we have the following data:

import numpy as np
X = np.array([0, 0, 1, 1, 1.5])
Y = np.array([0, 1.1, 0, 1, 1.3])
A = np.array([2, 1.1, 0.5, 2, 0.3])

We do the triangulation using scipy:

from scipy.spatial import Delaunay
domain_points = np.array(list(zip(X,Y)))
tri = Delaunay(domain_points)

enter image description here

We compute the integral:

def area_from_3_points(x, y, z):
    return np.sqrt(np.sum(np.cross(x-y, x-z), axis=-1)**2)/2
integral = 0
for vertices in tri.simplices:
    mean_value = (A[vertices[0]] + A[vertices[1]] + A[vertices[2]]) / 3
    area = area_from_3_points(domain_points[vertices[0]], domain_points[vertices[1]], domain_points[vertices[2]])
    integral += mean_value*area
print(integral)

Out: 2.1166666666666667

Upvotes: 4

Related Questions