To import NoiseStim, you can either use:
`python
from psychopy_visionscience.noise import NoiseStim
`
or, any time after psychopy.plugins.activatePlugins has been called:
`python
from psychopy.visual import NoiseStim
`
A stimulus with 2 textures: a random noise sample and a mask
Example:
noise1 = noise = visual.NoiseStim(
win=win, name='noise',units='pix',
noiseImage='testImg.jpg', mask='circle',
ori=1.0, pos=(0, 0), size=(512, 512), sf=None, phase=0,
color=[1,1,1], colorSpace='rgb', opacity=1, blendmode='add', contrast=1.0,
texRes=512, filter='None', imageComponent='Phase'
noiseType='Gabor', noiseElementSize=4, noiseBaseSf=32.0/512,
noiseBW=1.0, noiseBWO=30, noiseFractalPower=-1,noiseFilterLower=3/512, noiseFilterUpper=8.0/512.0,
noiseFilterOrder=3.0, noiseClip=3.0, filter=False, interpolate=False, depth=-1.0)
# gives a circular patch of noise made up of scattered Gabor elements with peak frequency = 32.0/512 cycles per pixel,
# orientation = 0 , frequency bandwidth = 1 octave and orientation bandwidth 30 degrees
Types of noise available
Binary, Normal, Uniform - pixel based noise samples drawn from a binary (blank and white), normal or uniform distribution respectively. Binary noise is always exactly zero mean, Normal and Uniform are approximately so. Parameters:
noiseElementSize - (can be a tuple) defines the size of the noise elements in the components units.
noiseClip the values in normally distributed noise are divided by noiseClip to limit excessively high or low values. However, values can still go out of range -1 to 1 whih will throw a soft error message high values of noiseClip are recommended if using ‘Normal’
Gabor, Isotropic: Effectively a dense scattering of Gabor elements with random amplitude and fixed orientation for Gabor or random orientation for Isotropic noise. In practice the desired amplitude spectrum for the noise is built in Fourier space with a random phase spectrum. DC term is set to zero - ie zero mean. Parameters:
noiseBaseSf - centre spatial frequency in the component units.
noiseBW - spatial frequency bandwidth full width half height in octaves.
ori - center orientation for Gabor noise (works as for gratingStim so twists the final image at render time).
noiseBWO - orientation bandwidth for Gabor noise full width half height in degrees.
noiseOri - alternative center orientation for Gabor which sets the orientation during the image build rather than at render time. Useful for setting the orientation of a filter to be applied to some other noise type with a different base orientation.
Filtered - A white noise sample that has been filtered with a low, high or bandpass Butterworth filter. The initial sample can have its spectrum skewed towards low or high frequencies. The contrast of the noise falls by half its maximum (3dB) at the cutoff frequencies. Parameters:
noiseFilterUpper - upper cutoff frequency - if greater than texRes/2 cycles per image low pass filter used.
noiseFilterLower - Lower cutoff frequency - if zero low pass filter used.
noiseFilterOrder - The order of the filter controls the steepness of the falloff outside the passband is zero no filter is applied.
noiseFractalPower - spectrum = f^noiseFractalPower - determines the spatial frequency bias of the initial noise sample. 0 = flat spectrum, negative = low frequency bias, positive = high frequency bias, -1 = fractal or brownian noise.
noiseClip - determines clipping values and rescaling factor such that final rms contrast is close to that requested by contrast parameter while keeping pixel values in range -1, 1.
White - A short cut to obtain noise with a flat, unfiltered spectrum. In practice the desired amplitude spectrum is built in the Fourier Domain with a random phase spectrum. DC term is set to zero - ie zero mean Note despite name the noise contains all grey levels. Parameters:
noiseClip - determines clipping values and rescaling factor such that final rms contrast is close to that requested by contrast parameter while keeping pixel values in range -1, 1.
Image: A noise sample whose spatial frequency spectrum is taken from the supplied image. In practice the desired amplitude spectrum is taken from the image and paired with a random phase spectrum. DC term is set to zero - ie zero mean. Parameters:
noiseImage name of ndarray or image file from which to take spectrum - should be same size as largest side requested for component if units is pix or texRes x texRes otherwise
imageComponent: ‘Phase’ randomizes the phase spectrum leaving the amplitude spectrum untouched. ‘Amplitude’ randomizes the amplitude spectrum leaving the phase spectrum untouched - retains spatial structure of image. ‘Neither’ keeps the image as is - but you can now apply a spatial filter to the image.
noiseClip - determines clipping values and rescaling factor such that final rms contrast is close to that requested by contrast parameter while keeping pixel values in range -1, 1.
Filter parameter
Butterworth: a spectral filter defined by the filtered noise parameters will be applied to the other noise types.
Gabor: a spectral filter defined by the Gabor noise parameters will be applied to the other noise types.
Isotropic: then a spectral filter defined by the Isotropic noise parameters will be applied to the other noise types.
Updating noise samples and timing
The noise is rebuilt at next call of the draw function whenever a parameter starting ‘noise’ is notionally changed even if the value does not actually change every time. eg. setting a parameter to update every frame will cause a new noise sample on every frame but see below. A rebuild can also be forced at any time using the buildNoise() function. The updateNoise() function can be used at any time to produce a new random saple of noise without doing a full build. ie it is quicker than a full build. Both buildNoise and updateNoise can be slow for large samples. Samples of Binary, Normal or Uniform noise can usually be made at frame rate using noiseUpdate. Updating or building other noise types at frame rate may result in dropped frames. An alternative is to build a large sample of noise at the start of the routien and place it off the screen then cut a samples out of this at random locations and feed that as a numpy array into the texture of a visible gratingStim.
Notes on size If units = pix and noiseType = Binary, Normal or Uniform will make noise sample of requested size. If units = pix and noiseType is Gabor, Isotropic, Filtered, White, Coloured or Image will make square noise sample with side length equal that of the largest dimetions requested. if units is not pix will make square noise sample with side length equal to texRes then rescale to present.
Notes on interpolation For pixel based noise interpolation = nearest is usually best. For other noise types linear is better if the size of the noise sample does not match the final size of the image well.
Notes on frequency Frequencies for cutoffs etc are converted between units for you but can be counter intuitive. 1/size is always 1 cycle per image. For the sf (final spatial frequency) parameter itself 1/size (or None for units pix) will faithfully represent the image without further scaling.
Filter cuttoff and Gabor/Isotropic base frequencies should not be too high you should aim to keep them below 0.5 c/pixel on the screen. The function will produce an error when it can’t draw the stimulus in the buffer but it may still be wrong when displayed.
Notes on orientation and phase The ori parameter twists the final image so the samples in noiseType Binary, Normal or Uniform will no longer be aligned to the sides of the monitor if ori is not a multiple of 90. Most other noise types look broadly the same for all values of ori but the specific sample shown can be made to rotate by changing ori. The dominant orientation for Gabor noise is determined by ori at render time, not before.
The phase parameter similarly shifts the sample around within the display window at render time and will not choose new random phases for the noise sample.
Legacy property for setting the foreground color of a stimulus in RGB, instead use obj._foreColor.rgb
DEPRECATED
Determines whether the stimulus should be automatically drawn on every frame flip.
Value should be: True or False. You do NOT need to set this on every frame flip!
Whether every change in this stimulus should be auto logged.
Value should be: True or False. Set to False if your stimulus is updating frequently (e.g. updating its position every frame) and you want to avoid swamping the log file with messages that aren’t likely to be useful.
Alternative way of setting fillColor
Deprecated, please use colorSpace to set color space for the entire object.
Legacy property for setting the fill color of a stimulus in RGB, instead use obj._fillColor.rgb
DEPRECATED
Alternative way of setting fillColor
The OpenGL mode in which the stimulus is draw
Can the ‘avg’ or ‘add’. Average (avg) places the new stimulus over the old one with a transparency given by its opacity. Opaque stimuli will hide other stimuli transparent stimuli won’t. Add performs the arithmetic sum of the new stimulus and the ones already present.
Deprecated, please use colorSpace to set color space for the entire object
Legacy property for setting the border color of a stimulus in RGB, instead use obj._borderColor.rgb
DEPRECATED
build a new noise sample. Required to act on changes to any noise parameters or texRes.
Clear all textures associated with the stimulus.
As of v1.61.00 this is called automatically during garbage collection of your stimulus, so doesn’t need calling explicitly by the user.
Alternative way of setting foreColor.
The name of the color space currently being used
Value should be: a string or None
For strings and hex values this is not needed. If None the default colorSpace for the stimulus is used (defined during initialisation).
Please note that changing colorSpace does not change stimulus parameters. Thus you usually want to specify colorSpace before setting the color. Example:
# A light green text
stim = visual.TextStim(win, 'Color me!',
color=(0, 1, 0), colorSpace='rgb')
# An almost-black text
stim.colorSpace = 'rgb255'
# Make it light green again
stim.color = (128, 255, 128)
Returns True if a point x,y is inside the stimulus’ border.
two separate args, x and y
one arg (list, tuple or array) containing two vals (x,y)
as a Mouse
.
Returns True if the point is within the area defined either by its border attribute (if one defined), or its vertices attribute if there is no .border. This method handles complex shapes, including concavities and self-crossings.
Note that, if your stimulus uses a mask (such as a Gaussian) then this is not accounted for by the contains method; the extent of the stimulus is determined purely by the size, position (pos), and orientation (ori) settings (and by the vertices for shape stimuli).
See Coder demos: shapeContains.py See Coder demos: shapeContains.py
A value that is simply multiplied by the color.
Operations supported.
Set the contrast of the stimulus, i.e. scales how far the stimulus deviates from the middle grey. You can also use the stimulus opacity to control contrast, but that cannot be negative.
Examples:
stim.contrast = 1.0 # unchanged contrast
stim.contrast = 0.5 # decrease contrast
stim.contrast = 0.0 # uniform, no contrast
stim.contrast = -0.5 # slightly inverted
stim.contrast = -1.0 # totally inverted
Setting contrast outside range -1 to 1 is permitted, but may produce strange results if color values exceeds the monitor limits.:
stim.contrast = 1.2 # increases contrast
stim.contrast = -1.2 # inverts with increased contrast
DEPRECATED, depth is now controlled simply by drawing order.
If this stimulus is draggable, do the necessary actions on a frame flip to drag it.
Can this stimulus be dragged by a mouse click?
Draw the stimulus in its relevant window. You must call this method after every MyWin.flip() if you want the stimulus to appear on that frame and then update the screen again.
Set the fill color for the shape.
Deprecated, please use colorSpace to set color space for the entire object.
Legacy property for setting the fill color of a stimulus in RGB, instead use obj._fillColor.rgb
DEPRECATED
If True apply spatial frequency filter to noise.
1x2 array for flipping vertices along each axis; set as True to flip or False to not flip. If set as a single value, will duplicate across both axes. Accessing the protected attribute (._flip) will give an array of 1s and -1s with which to multiply vertices.
Alternative way of setting foreColor.
Foreground color of the stimulus
string: to specify a colorNames. Any of the standard html/X11 color names <http://www.w3schools.com/html/html_colornames.asp> can be used.
hexColors
other colorspaces. For these, operations are supported.
When color is specified using numbers, it is interpreted with respect to the stimulus’ current colorSpace. If color is given as a single value (scalar) then this will be applied to all 3 channels.
Examples
For whatever stim you have:
stim.color = 'white'
stim.color = 'RoyalBlue' # (the case is actually ignored)
stim.color = '#DDA0DD' # DDA0DD is hexadecimal for plum
stim.color = [1.0, -1.0, -1.0] # if stim.colorSpace='rgb':
# a red color in rgb space
stim.color = [0.0, 45.0, 1.0] # if stim.colorSpace='dkl':
# DKL space with elev=0, azimuth=45
stim.color = [0, 0, 255] # if stim.colorSpace='rgb255':
# a blue stimulus using rgb255 space
stim.color = 255 # interpreted as (255, 255, 255)
# which is white in rgb255.
Operations work as normal for all numeric colorSpaces (e.g. ‘rgb’, ‘hsv’ and ‘rgb255’) but not for strings, like named and hex. For example, assuming that colorSpace=’rgb’:
stim.color += [1, 1, 1] # increment all guns by 1 value
stim.color *= -1 # multiply the color by -1 (which in this
# space inverts the contrast)
stim.color *= [0.5, 0, 1] # decrease red, remove green, keep blue
You can use setColor if you want to set color and colorSpace in one line. These two are equivalent:
stim.setColor((0, 128, 255), 'rgb255')
# ... is equivalent to
stim.colorSpace = 'rgb255'
stim.color = (0, 128, 255)
Deprecated, please use colorSpace to set color space for the entire object.
Legacy property for setting the foreground color of a stimulus in RGB, instead use obj._foreColor.rgb
DEPRECATED
Which component of an image to randomise, amplitude or phase.
Whether to interpolate (linearly) the texture in the stimulus.
If set to False then nearest neighbour will be used when needed, otherwise some form of interpolation will be used.
Alternative way of setting borderColor.
Deprecated, please use colorSpace to set color space for the entire object
Legacy property for setting the border color of a stimulus in RGB, instead use obj._borderColor.rgb
DEPRECATED
The alpha mask (forming the shape of the image).
‘circle’, ‘gauss’, ‘raisedCos’, ‘cross’
None (resets to default)
the name of an image file (most formats supported)
a numpy array (1xN or NxN) ranging -1:1
Various types of input. Default to None.
This is used to pass additional parameters to the mask if those are needed.
- For ‘gauss’ mask, pass dict {‘sd’: 5} to control
standard deviation.
- For the ‘raisedCos’ mask, pass a dict: {‘fringeWidth’:0.2},
where ‘fringeWidth’ is a parameter (float, 0-1), determining the proportion of the patch that will be blurred by the raised cosine edge.
The name (str) of the object to be using during logged messages about this stim. If you have multiple stimuli in your experiment this really helps to make sense of log files!
If name = None your stimulus will be called “unnamed <type>”, e.g. visual.TextStim(win) will be called “unnamed TextStim” in the logs.
Spatial frequency bandwidth for Gabor or Isotropic noise, full width at half height in octaves.
Orientation bandwidth for Gabor noise, full width at half height in degrees
Spatial frequency for Gabor or Isotropic noise in cycles per unit. Eg c/deg if units = degrees.
Ignored for types ‘Binary and Uniform’. For ‘Normal’ noise pixel values are divided by noiseClip to limit the standard deviation of the noise values.
For all other noise types noiseClip determines the level at which pixel values are cliped and subsequently re-scaled so as to produce a final image appraching the desired RMS contrast. High values will tend to reduce the ultimate RMS contrast but increase fidelity of appearance. Low values prioritise accurate final contrast but result in a binarised or thresholded appearance.
noiseClip is used to scale the luminance values as above whenever a filter is applied to the noise sample, regardless of the initial type of noise requested.
Noise element size for Binary, Normal or Uniform noise. In the units of the stimulus.
Lower cuttoff for filtered noise. In cycles/unit eg c/deg when units is degrees. Zero creates low pass filter.
Order of Butterworth filter for filtered noise. High = fast fall off withfrequency outside pass band.
Upper cuttoff for filtered noise. In cycles/unit eg c/deg when units is degrees. > size/2 creates high pass filter.
Exponent for ‘coloured’ noise. Amplitide spectrum = f^noiseFractalPower. -1 gives pink noise. Note power spectrum of a pink noise image should fall as f^-2. But as power spectrum = amplitude spectrum squared this is achieved by setting amplitude spectrum to f^-1.
Image from which to derive the amplitude or phase spectrum of noise type Image.
Type of noise to generate ‘Binary, Normal and Uniform’ produce pixel based random samples from the indicated distribitions.
Binary has zero mean lumiannce, Normal and Uniform approximate this.
fixed (Gabor) or random (Isotropic) orientations. Zero mean lumiannce.
‘White’ produces white noise with a flat amplitude spectrum. Zero mean lumiannce. ‘Filtered’ Produces white noise filtered by a low-, high- or band-pass filter. Zero mean lumiannce.
Use the noiseFractalPower attribute to skew the spectrum of filtered noise.
‘Image’ produces noise with the same spectrum as the supplied image but with mean lumiance set to zero.
Determines how visible the stimulus is relative to background.
The value should be a single float ranging 1.0 (opaque) to 0.0 (transparent). Operations are supported. Precisely how this is used depends on the blendMode.
The orientation of the stimulus (in degrees).
Should be a single value (scalar). Operations are supported.
Orientation convention is like a clock: 0 is vertical, and positive values rotate clockwise. Beyond 360 and below zero values wrap appropriately.
Returns True if this stimulus intersects another one.
If polygon is another stimulus instance, then the vertices and location of that stimulus will be used as the polygon. Overlap detection is typically very good, but it can fail with very pointy shapes in a crossed-swords configuration.
Note that, if your stimulus uses a mask (such as a Gaussian blob) then this is not accounted for by the overlaps method; the extent of the stimulus is determined purely by the size, pos, and orientation settings (and by the vertices for shape stimuli).
See coder demo, shapeContains.py
Phase of the stimulus in each dimension of the texture.
Should be an x,y-pair or scalar
NB phase has modulus 1 (rather than 360 or 2*pi) This is a little unconventional but has the nice effect that setting phase=t*n drifts a stimulus at n Hz.
The position of the center of the stimulus in the stimulus units
value should be an x,y-pair. Operations are also supported.
Example:
stim.pos = (0.5, 0) # Set slightly to the right of center
stim.pos += (0.5, -1) # Increment pos rightwards and upwards.
Is now (1.0, -1.0)
stim.pos *= 0.2 # Move stim towards the center.
Is now (0.2, -0.2)
Tip: If you need the position of stim in pixels, you can obtain it like this:
from psychopy.tools.monitorunittools import posToPix
posPix = posToPix(stim)
Sets autoDraw. Usually you can use ‘stim.attribute = value’ syntax instead, but use this method to suppress the log message.
Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.
DEPRECATED: Legacy setter for fill RGB, instead set obj._fillColor.rgb
DEPRECATED. Use ‘stim.parameter = value’ syntax instead
Hard setter for fillColor, allows suppression of the log message, simultaneous colorSpace setting and calls update methods.
DEPRECATED: Legacy setter for border RGB, instead set obj._borderColor.rgb
Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message
DEPRECATED since v1.60.05: Please use the color attribute
Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message
Hard setter for fillColor, allows suppression of the log message, simultaneous colorSpace setting and calls update methods.
DEPRECATED: Legacy setter for fill RGB, instead set obj._fillColor.rgb
Hard setter for foreColor, allows suppression of the log message, simultaneous colorSpace setting and calls update methods.
DEPRECATED: Legacy setter for foreground RGB, instead set obj._foreColor.rgb
DEPRECATED since v1.60.05: Please use the color attribute
DEPRECATED: Legacy setter for border RGB, instead set obj._borderColor.rgb
Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.
Hard setter for opacity, allows the suppression of log messages and calls the update method
Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message
DEPRECATED. Use ‘stim.parameter = value’ syntax instead
Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.
DEPRECATED: Legacy setter for foreground RGB, instead set obj._foreColor.rgb
DEPRECATED. Use ‘stim.parameter = value’ syntax instead
Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message
DEPRECATED. Use ‘stim.parameter = value’ syntax instead
Spatial frequency of the grating texture.
Should be a x,y-pair or scalar or None. If units == ‘deg’ or ‘cm’ units are in cycles per deg or cm as appropriate. If units == ‘norm’ then sf units are in cycles per stimulus (and so SF scales with stimulus size). If texture is an image loaded from a file then sf=None defaults to 1/stimSize to give one cycle of the image.
The size (width, height) of the stimulus in the stimulus units
Value should be x,y-pair, scalar (applies to both dimensions) or None (resets to default). Operations are supported.
Sizes can be negative (causing a mirror-image reversal) and can extend beyond the window.
Example:
stim.size = 0.8 # Set size to (xsize, ysize) = (0.8, 0.8)
print(stim.size) # Outputs array([0.8, 0.8])
stim.size += (0.5, -0.5) # make wider and flatter: (1.3, 0.3)
Tip: if you can see the actual pixel range this corresponds to by looking at stim._sizeRendered
Texture to used on the stimulus as a grating (aka carrier).
‘sin’,’sqr’, ‘saw’, ‘tri’, None (resets to default)
the name of an image file (most formats supported)
a numpy array (1xN or NxN) ranging -1:1
If specifying your own texture using an image or numpy array you should ensure that the image has square power-of-two dimensions (e.g. 256 x 256). If not then PsychoPy will up-sample your stimulus to the next larger power of two.
Power-of-two int. Sets the resolution of the mask and texture. maybe used as the side length for generating the noise texture but is not used if units = pix.
Operations supported.
Placeholder method to update colours when set externally, for example updating the pallette attribute of a textbox
Updates the noise sample. Does not change any of the noise parameters but choses a new random sample given the previously set parameters.
Placeholder method to update colours when set externally, for example updating the pallette attribute of a textbox.
This determines the coordinates of the vertices for the current stimulus in pixels, accounting for size, ori, pos and units
The Window
object in which the
stimulus will be rendered by default. (required)
Example, drawing same stimulus in two different windows and display simultaneously. Assuming that you have two windows and a stimulus (win1, win2 and stim):
stim.win = win1 # stimulus will be drawn in win1
stim.draw() # stimulus is now drawn to win1
stim.win = win2 # stimulus will be drawn in win2
stim.draw() # it is now drawn in win2
win1.flip(waitBlanking=False) # do not wait for next
# monitor update
win2.flip() # wait for vertical blanking.
Note that this just changes default window for stimulus.
You could also specify window-to-draw-to when drawing:
stim.draw(win1)
stim.draw(win2)