How to make Sparse Noise in PsychoPy?

Hello everyone,
I am trying to make a sparse noise stimulus for ephys experiments. To be more specific, a grey display with a defined number of randomly appearing white and black quads. Is there a nice way to modify the pre-built binary noise option of the NoiseStim to give such a display? If not, does anyone have recommendations how to do this correctly? Thank you in advance.

Not sure how to modify the pre-built binary noise option. Maybe the following approach below could help. It creates a numpy array in which only a limited number of pixels are turned on (if that’s the definition of sparse noise), and uses that array as input for an ImageStim object:

# Stimulus properties
width  = 200
height = 200
p      = 0.01 # Proportion of pixels that should be turned on
pixels = width * height

# Numpy array with sparse noise
white_pixels = np.random.choice(range(pixels), int(p*pixels), replace = False)
noise_matrix = -1 * np.ones((pixels))
noise_matrix[white_pixels] = 1
noise_matrix = noise_matrix.reshape((width, height))

# Use numpy array as ImageStim
noise_stim = visual.ImageStim(win, image = noise_matrix, size = (width, height))