Skip to content

Instantly share code, notes, and snippets.

@338rajesh
Last active November 15, 2022 12:17
Show Gist options
  • Save 338rajesh/d9c4097a8125c3c00f634e979860a348 to your computer and use it in GitHub Desktop.
Save 338rajesh/d9c4097a8125c3c00f634e979860a348 to your computer and use it in GitHub Desktop.
Get the chunks of data points on curve about a pivot value.
import numpy as np
import matplotlib.pyplot as plt
import os
from scipy import integrate
CFD = os.path.dirname(__file__)
def get_chunks(x: np.ndarray[float], y: np.ndarray[float], pivot: float = 0.0):
sort_indices = np.argsort(x)
x, y = x[sort_indices], y[sort_indices]
num_points = x.size
#
chunk_counter = 1
previous_chunk_sign = np.sign(y[0]-pivot)
chunks = {}
for (i, ay) in enumerate(y):
ay_sign = np.sign(ay-pivot)
if ay_sign != 0.0:
if ay_sign != previous_chunk_sign:
chunk_counter += 1
previous_chunk_sign = ay_sign
#
if chunk_counter in chunks.keys():
chunks[chunk_counter].append([x[i], ay])
else:
chunks[chunk_counter] = [[x[i], ay]]
#
chunks = {k: np.array(v) for (k, v) in chunks.items()}
return chunks
pvt = 5.0
X = np.linspace(0.0*np.pi, 1.5*np.pi, 2000)
Y = np.sin(X) + pvt
CHUNKS = get_chunks(X, Y, pivot=pvt)
# evaluate areas
areas = {k: integrate.simpson(v[:, 1]-pvt, v[:, 0]) for (k, v) in CHUNKS.items()}
plt.figure()
for (k, v) in CHUNKS.items():
print(f"Area of chunk-{k} is {areas[k]:4.3f}")
plt.plot(v[:, 0], v[:, 1], label=f'chunk-{k}')
plt.legend(loc='best')
plt.savefig(os.path.join(CFD, "sinx.png"))
plt.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment