Skip to content

Instantly share code, notes, and snippets.

@noc0lour
Created December 6, 2023 12:06
Show Gist options
  • Save noc0lour/4f30c9f93cecec773b6a0744f5d6032e to your computer and use it in GitHub Desktop.
Save noc0lour/4f30c9f93cecec773b6a0744f5d6032e to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
np.set_printoptions(threshold=np.inf)
def main():
threshold = 0.5
samples = np.random.standard_normal((10000,))
# Get a boolean array for all samples higher or lower than the threshold
low_samples = samples < threshold
high_samples = samples >= threshold
# Compute the rising edge and falling edges by comparing the current value to the next with
# the boolean operator & (if both are true the result is true) and converting this to an index
# into the current array
rising_edge_idx = np.nonzero(low_samples[:-1] & np.roll(high_samples, -1)[:-1])[0]
falling_edge_idx = np.nonzero(high_samples[:-1] & np.roll(low_samples, -1)[:-1])[0]
rising_edge_diff = np.diff(rising_edge_idx)
pulse_widths = rising_edge_idx - falling_edge_idx
# Plot the signal and mark rising edges in red and falling edges in yellow
plt.plot(samples, alpha=0.5)
for re in rising_edge_idx:
plt.axvspan(re, re+1, color='red', alpha=0.5)
for fe in falling_edge_idx:
plt.axvspan(fe, fe+1, color='yellow', alpha=0.5)
plt.show()
if __name__ == "__main__":
exit(not main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment