如何用Python绘制ON/OFF键控图?能否简化实现并推广至钟形信号?
Great question! Let’s tackle both parts of your query one by one—first simplifying the ON/OFF Keying (OOK) implementation, then extending it to bell-shaped signals.
Simplified OOK Implementation with NumPy Vectorization
Your original list comprehension works, but we can make this cleaner and more efficient using NumPy’s vectorized operations. Vectorization avoids explicit Python loops, which is faster (especially for large datasets) and makes the code more readable.
Here’s a streamlined version:
import numpy as np L = 30 # Number of pulses rrt = 1 # Repetition rate t = 0.3 # Duty cycle ookInput = np.random.randint(2, size=L) # Create the full time array x = np.arange(0, L * rrt, 0.01) # Determine which pulse each time point falls into pulse_indices = (x // rrt).astype(int) # Create a mask for the "ON" portion of each pulse cycle on_window_mask = (x % rrt) < t # Generate the OOK signal by combining input and mask y = ookInput[pulse_indices] * on_window_mask.astype(int)
Why this is better:
- Faster execution: NumPy’s vectorized operations are implemented in C, so they outperform Python loops/list comprehensions for large
Lor high-resolution time steps. - Clearer logic: Each step is explicit, making it easier to tweak parameters or debug later.
- Scalable: This approach works seamlessly with larger datasets without modifying the core structure.
Extending to Bell-Shaped (e.g., Gaussian) Pulses
Absolutely! Replacing rectangular pulses with bell-shaped signals just requires swapping the "hard" on/off mask with a smooth pulse function. Gaussian pulses are a common choice for bell-shaped signals, but you could also use raised cosine or other smooth functions.
Here’s how to adapt the code for Gaussian OOK:
import numpy as np L = 30 # Number of pulses rrt = 1 # Repetition rate pulse_width = 0.3 # Adjust this to control Gaussian pulse width ookInput = np.random.randint(2, size=L) x = np.arange(0, L * rrt, 0.01) pulse_indices = (x // rrt).astype(int) # Calculate time relative to the start of each pulse cycle relative_time = x % rrt # Define a Gaussian pulse function def gaussian_pulse(t, width, amplitude=1): # Center the pulse in the ON window, adjust sigma for width control sigma = width / 4 # Tweak this to make the pulse narrower/wider return amplitude * np.exp(-((t - width/2) ** 2) / (2 * sigma ** 2)) # Generate the Gaussian OOK signal: apply pulse only when input is 1 y = ookInput[pulse_indices] * gaussian_pulse(relative_time, pulse_width)
Customization tips:
- Adjust
sigmain the Gaussian function to control how "sharp" or "wide" the bell shape is. - Swap
gaussian_pulsewith another smooth function (e.g., a raised cosine pulse usingnp.cos) if you need a different bell shape. - For visualization, add this with matplotlib:
import matplotlib.pyplot as plt plt.plot(x, y) plt.xlabel("Time") plt.ylabel("Amplitude") plt.title("Gaussian ON/OFF Keying Signal") plt.show()
内容的提问来源于stack exchange,提问作者Enzo

