Skip to content

Firing field analysis

You can extract various properties of the firing field of a cluster using the get_field_properties method the TrialInterface class. This method returns a FieldProps object which contains various properties of the firing field of a cluster.

ephysiopy.io.recording.TrialInterface.get_field_properties(cluster: int | list, channel: int | list, **kwargs) -> list[FieldProps]

Gets the properties of a given field (area, runs through the field, etc)

Parameters:

Name Type Description Default
cluster int | list

The cluster(s) to get the field properties for

required
channel int | list

The channel(s) to get the field properties for

required
**kwargs

partition : str How the field is separated from the background. This is passed to the fieldproperties function and can be used to specify the partition to use for the field properties.

Valid options are 'simple' and 'fancy'

Other kwargs get passed to get_rate_map and
fieldprops, the most important of which may be
how the runs are split in fieldprops (options are
'field' and 'clump_runs') which differ depending on
if the position data is open-field (field) or linear track
in which case you should probably use 'clunmp_runs'
{}

Returns:

Type Description
list[FieldProps]

A list of FieldProps namedtuples containing the properties of the field

Plot each FieldProps item to get an idea of how well the segmentation worked etc:

ephysiopy.common.fieldcalcs.plot_field_props(field_props: list[FieldProps])

Plots the fields in the list of FieldProps

Parameters:

Name Type Description Default
field_props list of FieldProps

The field properties to plot

required

The underlying objects are described here:

ephysiopy.common.fieldproperties.fieldprops(label_image, binned_data, spike_times, xy, run_aggregation='field', cache=True, *, extra_properties=None, spacing=None, offset=None, **kwargs)

Measure properties of labeled image regions.

Parameters:

Name Type Description Default
label_image (M, N[, P]) np.ndarray

Labeled input image. Labels with value 0 are ignored.

required
xy (2 x n_samples) np.ndarray

The x-y coordinates for all runs through the field corresponding to a particular label

required
binned_data BinnedData instance from ephysiopy.common.utils
required
spike_times ndarray

The spike times for the neuron being analysed

required
method

Method used to calculate region properties:

  • 'field': Standard method using discrete pixel counts based on a segmentation of the rate map into labeled regions (fields). This method is faster, but can be inaccurate for small regions and will not work well for positional data that has been masked for direction of running say (ie linear track)
  • 'clump_runs': Exact method which accounts for filtered data better by looking for contiguous areas of the positional data that are NOT masked (uses np.ma.clump_unmasked) cache : bool, optional Determine whether to cache calculated properties. The computation is much faster for cached properties, whereas the memory consumption increases.
required
extra_properties Iterable of callables

Add extra property computation functions that are not included with skimage. The name of the property is derived from the function name, the dtype is inferred by calling the function on a small sample. If the name of an extra property clashes with the name of an existing property the extra property will not be visible and a UserWarning is issued. A property computation function must take a region mask as its first argument. If the property requires an intensity image, it must accept the intensity image as the second argument.

None
spacing

The pixel spacing along each axis of the image.

None
offset array-like of int, shape `(label_image.ndim,)`

Coordinates of the origin ("top-left" corner) of the label image. Normally this is ([0, ]0, 0), but it might be different if one wants to obtain regionprops of subvolumes within a larger volume.

None
**kwargs keyword arguments

Additional arguments passed to the FieldProps constructor. Legal arguments are: pos_sample_rate : int min_run_length : int

{}

Returns:

Name Type Description
properties list of FieldProps

Each item describes one labeled region, and can be accessed using the attributes listed below.

Notes

The following properties can be accessed as attributes or keys:

area : float Area of the region i.e. number of pixels of the region scaled by pixel-area.

area_bbox : float Area of the bounding box i.e. number of pixels of bounding box scaled by pixel-area.

area_convex : float Area of the convex hull image, which is the smallest convex polygon that encloses the region.

area_filled : float Area of the region with all the holes filled in.

axis_major_length : float The length of the major axis of the ellipse that has the same normalized second central moments as the region.

axis_minor_length : float The length of the minor axis of the ellipse that has the same normalized second central moments as the region.

bbox : tuple Bounding box (min_row, min_col, max_row, max_col). Pixels belonging to the bounding box are in the half-open interval [min_row; max_row) and [min_col; max_col).

centroid : array Centroid coordinate tuple (row, col).

centroid_local : array Centroid coordinate tuple (row, col), relative to region bounding box.

centroid_weighted : array Centroid coordinate tuple (row, col) weighted with intensity image.

centroid_weighted_local : array Centroid coordinate tuple (row, col), relative to region bounding box, weighted with intensity image.

coords_scaled : (K, 2) ndarray Coordinate list (row, col) of the region scaled by spacing.

coords : (K, 2) ndarray Coordinate list (row, col) of the region.

eccentricity : float Eccentricity of the ellipse that has the same second-moments as the region. The eccentricity is the ratio of the focal distance (distance between focal points) over the major axis length. The value is in the interval [0, 1). When it is 0, the ellipse becomes a circle.

equivalent_diameter_area : float The diameter of a circle with the same area as the region.

euler_number : int Euler characteristic of the set of non-zero pixels. Computed as number of connected components subtracted by number of holes (input.ndim connectivity). In 3D, number of connected components plus number of holes subtracted by number of tunnels.

extent : float Ratio of pixels in the region to pixels in the total bounding box. Computed as area / (rows cols)

feret_diameter_max : float Maximum Feret's diameter computed as the longest distance between points around a region's convex hull contour as determined by find_contours. [5]_

image : (H, J) ndarray Sliced binary region image which has the same size as bounding box.

image_convex : (H, J) ndarray Binary convex hull image which has the same size as bounding box.

image_filled : (H, J) ndarray Binary region image with filled holes which has the same size as bounding box.

image_intensity : ndarray Image inside region bounding box.

inertia_tensor : ndarray Inertia tensor of the region for the rotation around its mass.

inertia_tensor_eigvals : tuple The eigenvalues of the inertia tensor in decreasing order.

intensity_max : float Value with the greatest intensity in the region.

intensity_mean : float Value with the mean intensity in the region.

intensity_min : float Value with the least intensity in the region.

intensity_std : float Standard deviation of the intensity in the region.

label : int The label in the labeled input image.

moments : (3, 3) ndarray Spatial moments up to 3rd order::

    m_ij = sum{ array(row, col)  row^i  col^j }

where the sum is over the `row`, `col` coordinates of the region.

moments_central : (3, 3) ndarray Central moments (translation invariant) up to 3rd order::

    mu_ij = sum{ array(row, col)  (row - row_c)^i  (col - col_c)^j }

where the sum is over the `row`, `col` coordinates of the region,
and `row_c` and `col_c` are the coordinates of the region's centroid.

moments_hu : tuple Hu moments (translation, scale and rotation invariant).

moments_normalized : (3, 3) ndarray Normalized moments (translation and scale invariant) up to 3rd order::

    nu_ij = mu_ij / m_00^[(i+j)/2 + 1]

where `m_00` is the zeroth spatial moment.

moments_weighted : (3, 3) ndarray Spatial moments of intensity image up to 3rd order::

    wm_ij = sum{ array(row, col)  row^i  col^j }

where the sum is over the `row`, `col` coordinates of the region.

moments_weighted_central : (3, 3) ndarray Central moments (translation invariant) of intensity image up to 3rd order::

    wmu_ij = sum{ array(row, col)  (row - row_c)^i  (col - col_c)^j }

where the sum is over the `row`, `col` coordinates of the region,
and `row_c` and `col_c` are the coordinates of the region's weighted
centroid.

moments_weighted_hu : tuple Hu moments (translation, scale and rotation invariant) of intensity image.

moments_weighted_normalized : (3, 3) ndarray Normalized moments (translation and scale invariant) of intensity image up to 3rd order::

    wnu_ij = wmu_ij / wm_00^[(i+j)/2 + 1]

where ``wm_00`` is the zeroth spatial moment (intensity-weighted area).

num_pixels : int Number of foreground pixels.

orientation : float Angle between the 0th axis (rows) and the major axis of the ellipse that has the same second moments as the region, ranging from -pi/2 to pi/2 counter-clockwise.

perimeter : float Perimeter of object which approximates the contour as a line through the centers of border pixels using a 4-connectivity.

perimeter_crofton : float Perimeter of object approximated by the Crofton formula in 4 directions.

slice : tuple of slices A slice to extract the object from the source image.

solidity : float Ratio of pixels in the region to pixels of the convex hull image.

Each region also supports iteration, so that you can do::

for prop in region: print(prop, region[prop])

See Also

ephysiopy.common.utils.BinnedData

skimage.measure.regionprops

References

.. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.

.. [2] B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.

.. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.

.. [4] https://en.wikipedia.org/wiki/Image_moment

.. [5] W. Pabst, E. Gregorová. Characterization of particles and particle systems, pp. 27-28. ICT Prague, 2007. https://old.vscht.cz/sil/keramika/Characterization_of_particles/CPPS%20_English%20version_.pdf

Examples:

>>> from skimage import data, util
>>> from skimage.measure import label, regionprops
>>> img = util.img_as_ubyte(data.coins()) > 110
>>> label_img = label(img, connectivity=img.ndim)
>>> props = regionprops(label_img)
>>> # centroid of first labeled object
>>> props[0].centroid
(22.72987986048314, 81.91228523446583)
>>> # centroid of first labeled object
>>> props[0]['centroid']
(22.72987986048314, 81.91228523446583)

Add custom measurements by passing functions as extra_properties

>>> from skimage import data, util
>>> from skimage.measure import label, regionprops
>>> import numpy as np
>>> img = util.img_as_ubyte(data.coins()) > 110
>>> label_img = label(img, connectivity=img.ndim)
>>> def pixelcount(regionmask):
...     return np.sum(regionmask)
>>> props = regionprops(label_img, extra_properties=(pixelcount,))
>>> props[0].pixelcount
7741
>>> props[1]['pixelcount']
42

ephysiopy.common.fieldproperties.FieldProps(slice, label, label_image, binned_data, cache, *, extra_properties, spacing, offset, index=0)

Bases: RegionProperties

Describes various properties of a receptive field.

Attributes:

Name Type Description
slice tuple of slice

The slice of the field in the binned data (x slice, y slice)

label int

The label of the field

image_intensity ndarray

The intensity image of the field (in Hz)

runs list of RunProps

The runs through the field

run_slices list of slice

The slices of the runs through the field (slices are position indices)

run_labels ndarray

The labels of the runs

max_index ndarray

The index of the maximum intensity in the field

num_runs int

The number of runs through the field

cumulative_time list of np.ndarray

The cumulative time spent on the field for each run through the field

cumulative_distance list of np.ndarray

The cumulative time spent on the field for each run through the field

runs_speed list of np.ndarray

The speed of each run through the field

runs_observed_spikes ndarray

The observed spikes for each run through the field

spike_index ndarray

The index of the spikes in the position data

xy_at_peak ndarray

The x-y coordinate of the field max

xy ndarray

The x-y coordinates of the field for all runs

xy_relative_to_peak ndarray

The x-y coordinates of the field zeroed with respect to the peak

xy_angle_to_peak ndarray

The angle each x-y coordinate makes to the field peak

xy_dist_to_peak ndarray

The distance of each x-y coordinate to the field peak

bw_perim ndarray

The perimeter of the field as an array of bool

perimeter_coords tuple

The x-y coordinates of the field perimeter

global_perimeter_coords ndarray

The global x-y coordinates of the field perimeter

perimeter_minus_field_max ndarray

The x-y coordinates of the field perimeter minus the field max

perimeter_angle_from_peak ndarray

The angle each point on the perimeter makes to the field peak

perimeter_dist_from_peak ndarray

The distance of each point on the perimeter to the field peak

bin_coords ndarray

The x-y coordinates of the field in the binned data

phi ndarray

The angular distance between the mean direction of each run and each position samples direction to the field centre

rho ndarray

The distance of each position sample to the field max (1 is furthest)

pos_xy ndarray

The cartesian x-y coordinates of each position sample

pos_phi ndarray

The angular distance between the mean direction of each run and each position samples direction to the field centre

pos_r ndarray

The ratio of the distance from the field peak to the position sample and the distance from the field peak to the point on the perimeter that is most colinear with the position sample

r_and_phi_to_x_and_y ndarray

Converts rho and phi to x and y coordinates

r_per_run ndarray

The polar radial distance for each run

current_direction ndarray

The direction projected onto the mean run direction

cumulative_distance list of np.ndarray

The cumulative distance for each run

projected_direction ndarray

The direction projected onto the mean run direction

intensity_max float

The maximum intensity of the field (i.e. field peak rate)

intensity_mean float

The mean intensity of the field

intensity_min float

The minimum intensity of the field

intensity_std float

The standard deviation of the field intensity

Methods:

Name Description
__str__

Override the string representation printed to the console

mean_spiking_var

Get the mean value of a variable at the posiition of

overdispersion

Calculate the overdispersion for each run through the field

runs_expected_spikes

Calculate the expected number of spikes along each run given the

smooth_runs

Smooth in x and y in preparation for converting the smoothed cartesian

spiking_var

Get the value of a variable at the position of

compressed_phase: np.ndarray property

The phases of the LFP signal for all runs through this field compressed into a single array

n_spikes: int property

The total number of spikes emitted on all runs through the field

normalized_position: list property

Only makes sense to run this on linear track data unless we want to pass the unit circle distance or something...

Get the normalized position for each run through the field.

Normalized position is the position of the run relative to the start of the field (0) to the end of the field (1).

phase: list property

The phases of the LFP signal for all runs through this field

phi: np.ndarray property

Calculate the angular distance between the mean direction of each run and each position samples direction to the field centre

pos_phi: np.ndarray property

Calculate the angular distance between the mean direction of each run and each position samples direction to the field centre

pos_r: np.ndarray property

Calculate the ratio of the distance from the field peak to the position sample and the distance from the field peak to the point on the perimeter that is most colinear with the position sample

NB The values just before being returned can be >= 1 so these are capped to 1

projected_direction: np.ndarray property

direction projected onto the mean run direction is just the x-coord when cartesian x and y is converted to from polar rho and phi

__str__()

Override the string representation printed to the console

mean_spiking_var(var='current_direction')

Get the mean value of a variable at the posiition of the spikes for all runs through this field when multiple spikes occur in a single theta cycle

Parameters:

Name Type Description Default
var str

the variable to get the mean value of at the position of spikes

'current_direction'

Returns:

Type Description
ndarray

the mean value of the variable at the position of spikes for all runs through this field

overdispersion(spikes: np.ndarray, fs: int = 50) -> np.ndarray

Calculate the overdispersion for each run through the field

Parameters:

Name Type Description Default
spikes ndarray

the spike train (spikes binned up by position) for the whole trial. Same length as the trial n_samples

required
fs int

the sample rate of the position data

50

Returns:

Type Description
ndarray

the overdispersion for each run through the field

runs_expected_spikes(expected_rate: np.ndarray, sample_rate: int = 50) -> np.ndarray

Calculate the expected number of spikes along each run given the whole ratemap.

Parameters:

Name Type Description Default
expected_rate ndarray

the rate seen at each xy position of the whole trial

required
sample_rate int

the sample rate of the position data

50

Returns:

Type Description
ndarray

the expected rate at each xy position for each run

Examples:

The expected spikes should be calculated from the smoothed ratemap and the xy position data using np.digitize:

>>> xbins = np.digitize(xy[0], binned_data.bin_edges[1][:-1]) - 1
>>> ybins = np.digitize(xy[1], binned_data.bin_edges[0][:-1]) - 1
>>> expected_rate_at_pos = binned_data.binned_data[0][ybins, xbins]
>>> exptd_spks = fieldprops.runs_expected_spikes(expected_rate_at_pos)

smooth_runs(k: float, spatial_lp_cut: int, sample_rate: int)

Smooth in x and y in preparation for converting the smoothed cartesian coordinates to polar ones

Parameters:

Name Type Description Default
k float

smoothing constant for the instantaneous firing rate

required
spatial_lp_cut int

spatial lowpass cut off

required
sample_rate int

position sample rate in Hz

required

spiking_var(var='current_direction')

Get the value of a variable at the position of spikes for all runs through this field

Parameters:

Name Type Description Default
var str

the variable to get the value of at the position of spikes

'current_direction'

Returns:

Type Description
ndarray

the value of the variable at the position of spikes for all runs through this field

ephysiopy.common.fieldproperties.RunProps(parent, label: int, slice: slice, spike_times: np.ndarray, mask: np.ndarray, xy_coords: np.ndarray, speed: np.ndarray, peak_xy: np.ndarray, max_index: np.ndarray, perimeter_coords: np.ndarray, sample_rate: float = 50)

Bases: SpikingProperty, object

A custom class for holding information about runs through a receptive field

Each run needs to have some information about the field to which it belongs so the constructor takes in the peak x-y coordinate of the field and its index as well as the coordinates of the perimeter of the field

Attributes:

Name Type Description
label int

the run id

slice slice

the slice of the position data for a run

xy ndarray

the x-y coordinates for a run (global coordinates)

speed ndarray

the speed at each xy coordinate

peak_xy tuple[float, float]

the fields max rate xy location

max_index int

the index into the arrays of the field max

perimeter_coords ndarray

xy coordinates of the field perimeter

hdir ndarray

the heading direction

min_speed float

the minimum speed

cumulative_time ndarray

the cumulative time spent on a run

duration float

the total duration of a run in seconds

n_spikes int

the total number of spikes emitted on a run

run_start int

the position index of the run start

run_stop int

the position index of the run stop

mean_direction float

the mean direction of a run

current_direction ndarray

the current direction of a run

cumulative_distance ndarray

the cumulative distance covered in a run

spike_index ndarray

the index into the position data of the spikes on a run

observed_spikes ndarray

the observed spikes on a run (binned by position samples)

xy_angle_to_peak ndarray

the xy angle to the peak (radians)

xy_dist_to_peak ndarray

the distance to the field max

xy_dist_to_peak_normed ndarray

normalised distance to field max

pos_xy ndarray

cartesian xy coordinates but normalised on a unit circle

pos_phi ndarray

the angular distance between a runs main direction and the direction to the peak for each position sample

rho ndarray

the polar radial distance (1 = field edge)

phi ndarray

the polar angle (radians)

r_and_phi_to_x_and_y ndarray

converts rho and phi to x and y coordinates (range = -1 -> +1)

tortuosity ndarray

the tortuosity for a run (closer to 1 = a straighter run)

xy_is_smoothed bool

whether the xy data has been smoothed

label : int the field label the run belongs to slice : slice the slice into the position array that holds all the position data spike_times: np.ndarray the spike times for this run xy_coords : np.ndarray the xy data for this run (global coordinates) hdir : np.ndarray the heading direction for this run speed : np.ndarray the speed for this run peak_xy : np.ndarray the peak location of the field for the this run max_index : np.ndarray the index (r,c) of the maximum of the firing field perimeter_coords : np.ndarray the xy coordinates of the perimeter of the field

Methods:

Name Description
expected_spikes

Calculates the expected number of spikes along this run given the

mean_spiking_var

Get the mean value of a variable at the posiition of

overdispersion

The overdispersion map for this run

smooth_xy

Smooth in x and y in preparation for converting the smoothed cartesian

spiking_var

Get the value of a variable at the position of

current_direction: ma.MaskedArray property

Supposed to calculate current direction wrt to field centre?

ndim property

Return the dimensionality of the data

For 1 x n linear track data dimensionality = 1 for 2 x n open field (or other) data dimensionality = 2

normed_x: np.ndarray property

Normalise the x data to lie between -1 and 1 with respect to the field limits of the parent field and the run direction such that -1 is entry and +1 is exit

phi: ma.MaskedArray property

Values lie between 0 and 2pi

pos_phi: ma.MaskedArray property

Values lie between 0 and 2pi

pos_r: ma.MaskedArray property

Values lie between 0 and 1

raw_spike_times property

Return the spike times that fall within the slice without masking

rho: ma.MaskedArray property

Values lie between 0 and 1

spike_index: np.ndarray property

Get the index into the LFP data of the spikes for this segment

Returns:

Type Description
ndarray

the index into the LFP data of the spikes for this segment

xy_dist_to_peak_normed: ma.MaskedArray property

Values lie between 0 and 1

expected_spikes(expected_rate_at_pos: np.ndarray, sample_rate: int = 50) -> np.ndarray

Calculates the expected number of spikes along this run given the whole ratemap.

Parameters:

Name Type Description Default
expected_rate_at_pos ndarray

the rate seen at each xy position of the whole trial

required

Returns:

Name Type Description
expected_rate ndarray

the expected rate at each xy position of this run

mean_spiking_var(var='current_direction')

Get the mean value of a variable at the posiition of the spikes for all runs through this field when multiple spikes occur in a single theta cycle

overdispersion(spike_train: np.ndarray, fs: int = 50) -> float

The overdispersion map for this run

Parameters:

Name Type Description Default
spike_train mdarray

the spike train (spikes binned up by position) for the whole trial. Same length as the trial n_samples

required
fs int

the sample rate of the position data

50

smooth_xy(k: float, spatial_lp: int, sample_rate: int) -> None

Smooth in x and y in preparation for converting the smoothed cartesian coordinates to polar ones

Parameters:

Name Type Description Default
k float

smoothing constant for the instantaneous firing rate

required
spatial_lp int

spatial lowpass cut off

required
sample_rate int

position sample rate in Hz

required

spiking_var(var='current_direction')

Get the value of a variable at the position of spikes for this run

ephysiopy.common.fieldproperties.LFPSegment(parent, field_label: int, run_label: int, slice: slice, spike_times: np.ndarray, mask: np.ndarray, signal: np.ndarray, filtered_signal: np.ndarray, phase: np.ndarray, cycle_label: np.ndarray, sample_rate: float | int)

Bases: SpikingProperty, object

A custom class for dealing with segments of an LFP signal and how they relate to specific runs through a receptive field (see RunProps and FieldProps below)

Attributes:

Name Type Description
field_label int

The field id

run_label int

The run id

slice slice

slice into the LFP data for a segment

spike_times ndarray

the times in seconds spikes occurred for a segment

spike_count ndarray

spikes binned into lfp samples for a segment

signal ndarray

raw signal for a segment

filtered_signal ndarray

bandpass filtered signal for a segment

phase ndarray

phase data for a segment

amplitude ndarray

amplitude for a segment

sample_rate (float, int)

sample rate for the LFP segment

filter_band tuple[int, int]

the bandpass filter values

field_label : int the field id to which this LFP segment belongs run_label : int the run id through the field to which this LFP segment belongs slice : slice the slice corresponding the pos sample I think spike_count : np.ndarray spikes binned into lfp samples signal, filtered_signal, phase, : np.ndarray the raw, filtered, and phase of the LFP for a given segment sample_rate : int, float the sample rate for the LFP signal filter_band : tuple the bandpass filter giving filtered_signal

Methods:

Name Description
mean_spiking_var

Get the mean value of a variable at the posiition of

spiking_var

Get the value of a variable at the position of

raw_spike_times property

Return the spike times that fall within the slice without masking

spike_index: np.ndarray property

Get the index into the LFP data of the spikes for this segment

Returns:

Type Description
ndarray

the index into the LFP data of the spikes for this segment

mean_spiking_var(var='phase')

Get the mean value of a variable at the posiition of the spikes for all runs through this field when multiple spikes occur in a single theta cycle

spiking_var(var='phase')

Get the value of a variable at the position of spikes for this run

These methods are available to operate on the output of fieldprops (or similarly the get_field_properties() method of the TrialInterface class).

ephysiopy.common.fieldcalcs.sort_fields_by_attr(field_props: list[FieldProps], attr='area', reverse=True)

Sorts the fields in the list by attribute

Notes

In the default case will sort by area, largest first

ephysiopy.common.fieldcalcs.get_all_phase(field_props: list[FieldProps]) -> np.ndarray

Get all the phases from the field properties

Parameters:

Name Type Description Default
field_props list of FieldProps

The field properties to search through

required

Returns:

Type Description
ndarray

An array of all the phases from all runs in all fields

ephysiopy.common.fieldcalcs.get_run_times(field_props: list[FieldProps]) -> list

Get the run start and stop times in seconds for all runs through all fields in the field_props list

ephysiopy.common.fieldcalcs.get_run(field_props: list[FieldProps], run_num: int) -> RunProps

Get a specific run from the field properties

Parameters:

Name Type Description Default
field_props list of FieldProps

The field properties to search through

required
run_num int

The run number to search for

required

Returns:

Type Description
RunProps

The run properties for the specified run number

ephysiopy.common.fieldcalcs.filter_runs(field_props: list[FieldProps], attributes, ops, vals, **kwargs) -> list[FieldProps]

Filter out runs that are too short, too slow or have too few spikes

Parameters:

Name Type Description Default
field_props list of FieldProps
required
attributes list of str

attributes of RunProps to filter on

required
ops list of str

operations to use for filtering. Supported operations are np.less and np.greater

required
vals list of float

values to filter on

required

Returns:

Type Description
list of FieldProps
Notes

this modifies the input list

Example

field_props = filter_runs(field_props, ['n_spikes'], [np.greater], [5])

field_props now only contains runs with more than 5 spikes

ephysiopy.common.fieldcalcs.filter_for_speed(field_props: list[FieldProps], min_speed: float) -> list[FieldProps]

Mask for low speeds across the list of fields / runs

Parameters:

Name Type Description Default
field_props list of FieldProps

The field properties to filter

required
min_speed float

The minimum speed to keep a run

required

Returns:

Type Description
list of FieldProps

The filtered field properties

ephysiopy.common.fieldcalcs.infill_ratemap(rmap: np.ndarray) -> np.ndarray

The ratemaps used in the phasePrecession2D class are a) super smoothed and b) very large i.e. the bins per cm is low. This results in firing fields that have lots of holes (nans) in them. We want to smooth over these holes so we can construct measures such as the expected rate in a given bin whilst also preserving whatever 'geometry' of the environment exists in the ratemap as a result of where position has been sampled. That is, if non-sampled positions are designated with nans, we want to smooth over those that in theory could have been sampled and keep those that never could have been.

Parameters:

Name Type Description Default
rmap ndarray

The ratemap to be filled

required

Returns:

Type Description
ndarray

The filled ratemap

ephysiopy.common.fieldcalcs.get_peak_coords(rmap, labels)

Get the peak coordinates of the firing fields in the ratemap

ephysiopy.common.fieldcalcs.simple_partition(binned_data: BinnedData, rate_threshold_prc: int = 200, **kwargs) -> tuple[np.ndarray]

Simple partitioning of fields based on mean firing rate. Only returns a single field (the highest firing rate field) per binned_data instance

The default is to limit to fields that have a mean firing rate greater than twice the mean firing rate of the entire ratemap

Parameters:

Name Type Description Default
binned_data BinnedData

an instance of ephysiopy.common.utils.BinnedData

required
rate_threshold_prc int

removes pixels in a field that fall below this percent of the mean firing rate

200

Returns:

Type Description
tuple of np.ndarray

peaksXY - The xy coordinates of the peak rates in the highest firing field peaksRate - The peak rates in peaksXY labels - An array of the labels corresponding to the highest firing field rmap_filled - The filled ratemap of the tetrode / cluster

Notes

This is a simple method to partition fields that only returns a single field - the one with the highest mean firing rate.

ephysiopy.common.fieldcalcs.fancy_partition(binned_data: BinnedData, field_threshold_percent: int | float = 50, area_threshold_percent: float = 10) -> tuple[np.ndarray, ...]

Another partitioning method

Parameters:

Name Type Description Default
binned_data BinnedData
required
field_threshold_percent int | float

pixels below this are set to zero and ignored

50
area_threshold_percent float

the expected minimum size of a receptive field

10

ephysiopy.common.fieldcalcs.get_mean_resultant(ego_boundary_map: np.ndarray) -> np.complex128 | float

Calculates the mean resultant vector of a boundary map in egocentric coordinates

Parameters:

Name Type Description Default
ego_boundary_map ndarray

The egocentric boundary map

required

Returns:

Type Description
float

The mean resultant vector of the egocentric boundary map

Notes

See Hinman et al., 2019 for more details

ephysiopy.common.fieldcalcs.get_mean_resultant_length(ego_boundary_map: np.ndarray, **kwargs) -> float

Calculates the length of the mean resultant vector of a boundary map in egocentric coordinates

Parameters:

Name Type Description Default
ego_boundary_map ndarray

The egocentric boundary map

required

Returns:

Type Description
float

The length of the mean resultant vector of the egocentric boundary map

Notes

See Hinman et al., 2019 for more details

ephysiopy.common.fieldcalcs.get_mean_resultant_angle(ego_boundary_map: np.ndarray, **kwargs) -> float

Calculates the angle of the mean resultant vector of a boundary map in egocentric coordinates

Parameters:

Name Type Description Default
ego_boundary_map ndarray

The egocentric boundary map

required

Returns:

Type Description
float

The angle mean resultant vector of the egocentric boundary map

Notes

See Hinman et al., 2019 for more details

ephysiopy.common.fieldcalcs.border_score(A, shape='square', fieldThresh=0.3, circumPrc=0.2, binSize=3.0, minArea=20)

Calculates a border score totally dis-similar to that calculated in Solstad et al (2008)

Parameters:

Name Type Description Default
A ndarray

the ratemap

required
B ndarray

This should be a boolean mask where True (1) is equivalent to the presence of a border and False (0) is equivalent to 'open space'. Naievely this will be the edges of the ratemap but could be used to take account of boundary insertions/ creations to check tuning to multiple environmental boundaries. Default None: when the mask is None then a mask is created that has 1's at the edges of the ratemap i.e. it is assumed that occupancy = environmental shape

None
shape str

description of environment shape. Currently only 'square' or 'circle' accepted. Used to calculate the proportion of the environmental boundaries to examine for firing

'square'
fieldThresh float

Between 0 and 1 this is the percentage amount of the maximum firing rate to remove from the ratemap (i.e. to remove noise)

0.3
circumPrc float

The percentage amount of the circumference of the environment that the field needs to be to count as long enough to make it through

0.2
binSize float

bin size in cm

3.0
minArea float

min area for a field to be considered

20

Returns:

Type Description
float

the border score

Notes

If the cell is a border cell (BVC) then we know that it should fire at a fixed distance from a given boundary (possibly more than one). In essence this algorithm estimates the amount of variance in this distance i.e. if the cell is a border cell this number should be small. This is achieved by first doing a bunch of morphological operations to isolate individual fields in the ratemap (similar to the code used in phasePrecession.py - see the fancy_partition method therein). These partitioned fields are then thinned out (using skimage's skeletonize) to a single pixel wide field which will lie more or less in the middle of the (highly smoothed) sub-field. It is the variance in distance from the nearest boundary along this pseudo-iso-line that is the boundary measure

Other things to note are that the pixel-wide field has to have some minimum length. In the case of a circular environment this is set to 20% of the circumference; in the case of a square environment markers this is at least half the length of the longest side

ephysiopy.common.fieldcalcs.plot_field_props(field_props: list[FieldProps])

Plots the fields in the list of FieldProps

Parameters:

Name Type Description Default
field_props list of FieldProps

The field properties to plot

required

ephysiopy.common.fieldcalcs.kl_spatial_sparsity(pos_map: BinnedData) -> float

Calculates the spatial sampling of an arena by comparing the observed spatial sampling to an expected uniform one using kl divergence

Data in pos_map should be unsmoothed (not checked) and the MapType should be POS (checked)

Parameters:

Name Type Description Default
pos_map BinnedData

The position map

required

Returns:

Type Description
float

The spatial sparsity of the position map

ephysiopy.common.fieldcalcs.spatial_sparsity(rate_map: np.ndarray, pos_map: np.ndarray) -> float

Calculates the spatial sparsity of a rate map as defined by Markus et al (1994)

For example, a sparsity score of 0.10 indicates that the cell fired on 10% of the maze surface

Parameters:

Name Type Description Default
rate_map ndarray

The rate map

required
pos_map ndarray

The occupancy map

required

Returns:

Type Description
float

The spatial sparsity of the rate map

References

Markus, E.J., Barnes, C.A., McNaughton, B.L., Gladden, V.L. & Skaggs, W.E. Spatial information content and reliability of hippocampal CA1 neurons: effects of visual input. Hippocampus 4, 410–421 (1994).

ephysiopy.common.fieldcalcs.kldiv_dir(polarPlot: np.ndarray) -> float

Returns a kl divergence for directional firing: measure of directionality. Calculates kl diveregence between a smoothed ratemap (probably should be smoothed otherwise information theoretic measures don't 'care' about position of bins relative to one another) and a pure circular distribution. The larger the divergence the more tendancy the cell has to fire when the animal faces a specific direction.

Parameters:

Name Type Description Default
polarPlot ndarray

The binned and smoothed directional ratemap

required

Returns:

Type Description
float

The divergence from circular of the 1D-array from a uniform circular distribution

ephysiopy.common.fieldcalcs.kldiv(X: np.ndarray, pvect1: np.ndarray, pvect2: np.ndarray, variant: str = '') -> float

Calculates the Kullback-Leibler or Jensen-Shannon divergence between two distributions.

Parameters:

Name Type Description Default
X ndarray

Vector of M variable values

required
pvect1 ndarray

Length-M vectors of probabilities representing distribution 1 and 2

required
pvect2 ndarray

Length-M vectors of probabilities representing distribution 1 and 2

required
variant str

If 'sym', returns a symmetric variant of the Kullback-Leibler divergence, given by [KL(P1,P2)+KL(P2,P1)]/2 If 'js', returns the Jensen-Shannon divergence, given by [KL(P1,Q)+KL(P2,Q)]/2, where Q = (P1+P2)/2

'sym'

Returns:

Type Description
float

The Kullback-Leibler divergence or Jensen-Shannon divergence

Notes

The Kullback-Leibler divergence is given by:

.. math:: KL(P1(x),P2(x)) = sum_[P1(x).log(P1(x)/P2(x))]

If X contains duplicate values, there will be an warning message, and these values will be treated as distinct values. (I.e., the actual values do not enter into the computation, but the probabilities for the two duplicate values will be considered as probabilities corresponding to two unique values.). The elements of probability vectors P1 and P2 must each sum to 1 ± .00001.

This function is taken from one on the Mathworks file exchange

See Also

Cover, T.M. and J.A. Thomas. "Elements of Information Theory," Wiley, 1991.

https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence

ephysiopy.common.fieldcalcs.skaggs_info(ratemap: np.ndarray, dwelltimes: np.ndarray, **kwargs)

Calculates Skaggs information measure

Parameters:

Name Type Description Default
ratemap ndarray

The binned up ratemap and dwelltimes. Must be the same size

required
dwelltimes ndarray

The binned up ratemap and dwelltimes. Must be the same size

required

Returns:

Type Description
float

Skaggs information score in bits spike

Notes

The ratemap data should have undergone adaptive binning as per the original paper. See getAdaptiveMap() in binning class

The estimate of spatial information in bits per spike:

.. math:: I = sum_{x} p(x).r(x).log(r(x)/r)

ephysiopy.common.fieldcalcs.grid_field_props(A: BinnedData, maxima='centroid', allProps=True, **kwargs)

Extracts various measures from a spatial autocorrelogram

Parameters:

Name Type Description Default
A BinnedData

object containing the spatial autocorrelogram (SAC) in A.binned_data[0]

required
maxima
Legal values are 'single' and 'centroid'. Default 'centroid'
'centroid'
allProps bool default=True

Whether to return a dictionary that contains the attempt to fit an ellipse around the edges of the central size peaks. See below

True

Returns:

Type Description
dict

Measures of the SAC. Keys include: * gridness score * scale * orientation * coordinates of the peaks (nominally 6) closest to SAC centre * a binary mask around the extent of the 6 central fields * values of the rotation procedure used to calculate gridness * ellipse axes and angle (if allProps is True and the it worked)

Notes

The output from this method can be used as input to the show() method of this class. When it is the plot produced will display a lot more informative. The coordinate system internally used is centred on the image centre.

See Also

ephysiopy.common.binning.autoCorr2D()

ephysiopy.common.fieldcalcs.gridness(image, step=30) -> tuple

Calculates the gridness score in a grid cell SAC.

The data in image is rotated in step amounts and each rotated array is correlated with the original. The maximum of the values at 30, 90 and 150 degrees is the subtracted from the minimum of the values at 60, 120 and 180 degrees to give the grid score.

Parameters:

Name Type Description Default
image ndarray

The spatial autocorrelogram

required
step int

The amount to rotate the SAC in each step of the rotational correlation procedure

30

Returns:

Type Description
3 - tuple

The gridscore, the correlation values at each step and the rotational array

Notes

The correlation performed is a Pearsons R. Some rescaling of the values in image is performed following rotation.

See Also

skimage.transform.rotate : for how the rotation of image is done skimage.exposure.rescale_intensity : for the resscaling following rotation

ephysiopy.common.fieldcalcs.basic_gridscore(A: np.ndarray, **kwargs) -> float

Calculates the grid score of a spatial autocorrelogram

Parameters:

Name Type Description Default
A ndarray

The spatial autocorrelogram

required

Returns:

Type Description
float

The grid score of the SAC

ephysiopy.common.fieldcalcs.expanding_circle_gridscore(A: np.ndarray, **kwargs)

Calculates the gridscore for each circular sub-region of image A where the circles are centred on the image centre and expanded to the edge of the image. The maximum of the get_basic_gridscore() for each of these circular sub-regions is returned as the gridscore

Parameters:

Name Type Description Default
A ndarray

The SAC

required

Returns:

Type Description
float

The maximum grid score of the circular sub regions of the SAC

ephysiopy.common.fieldcalcs.deformed_sac_gridscore(A: np.ndarray) -> float

Deforms a non-circular SAC into a circular SAC (circular meaning the ellipse drawn around the edges of the 6 nearest peaks to the SAC centre) and returns get_basic_griscore() calculated on the deformed (or re-formed?!) SAC

Parameters:

Name Type Description Default
A ndarray

The SAC

required

Returns:

Type Description
float

The gridscore of the deformed SAC

ephysiopy.common.fieldcalcs.thigmotaxis_score(xy: np.ndarray, shape: str = 'circle') -> float

Returns a score which is the ratio of the time spent in the inner portion of an environment to the time spent in the outer portion. The portions are allocated so that they have equal area.

Parameters:

Name Type Description Default
xy ndarray

The xy coordinates of the animal's position. 2 x nsamples

required
shape str

The shape of the environment. Legal values are 'circle' and 'square'

'circle'

Returns:

Type Description
float

Values closer to 1 mean more time was spent in the inner portion of the environment. Values closer to -1 mean more time in the outer portion of the environment. A value of 0 indicates the animal spent equal time in both portions of the environment.