LabeledArray

class LabeledArray(input_array, labels: list[tuple[str, ...], ...] = (), delimiter: str = '-', **kwargs)[source][source]

A numpy array with labeled dimensions, acting like a dictionary.

A numpy array with labeled dimensions. This class is useful for storing data that is not easily represented in a tabular format. It acts as a nested dictionary but its values map to elements of a stored numpy array.

Parameters:
  • input_array (array_like) – The array to store in the LabeledArray.

  • labels (tuple[tuple[str, ], ], optional) – The labels for each dimension of the array, by default ().

  • delimiter (str, optional) – The delimiter to use when combining labels, by default ‘-’

  • **kwargs – Additional arguments to pass to np.asarray.

Variables:
  • labels (tuple[tuple[str, ], ]) – The labels for each dimension of the array.

  • array (np.ndarray) – The array stored in the LabeledArray.

Examples

>>> import numpy as np
>>> np.set_printoptions(legacy='1.21')
>>> from ieeg.arrays.label import LabeledArray
>>> arr = np.ones((2, 3, 4), dtype=int)
>>> labels = (('a', 'b'), ('c', 'd', 'e'), ('f', 'g', 'h', 'i'))
>>> la = LabeledArray(arr, labels)
>>> la
array([[[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]],

       [[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]]])
labels(['a', 'b']
       ['c', 'd', 'e']
       ['f', 'g', 'h', 'i'])
>>> la.to_dict()
{'a': {'c': {'f': 1, 'g': 1, 'h': 1, 'i': 1}, 'd': {'f': 1, 'g': 1,...
>>> la['a', 'c', 'f'] = 2
>>> la['a', 'c', 'f']
2
>>> la['a', 'c']
array([2, 1, 1, 1])
labels(['f', 'g', 'h', 'i'])
>>> la['a'].labels
[['c', 'd', 'e'], ['f', 'g', 'h', 'i']]
>>> la['a','d'] = np.array([3,3,3,3])
>>> la[('a','b'), :]
array([[[2, 1, 1, 1],
        [3, 3, 3, 3],
        [1, 1, 1, 1]],

       [[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]]])
labels(['a', 'b']
       ['c', 'd', 'e']
       ['f', 'g', 'h', 'i'])
>>> la[np.array([False, True]),]
array([[[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]]])
labels(['b']
       ['c', 'd', 'e']
       ['f', 'g', 'h', 'i'])
>>> la[(0, 1)]
array([3, 3, 3, 3])
labels(['f', 'g', 'h', 'i'])
>>> la[0, 1]
array([3, 3, 3, 3])
labels(['f', 'g', 'h', 'i'])
>>> la[(0, 1),].labels
[['a', 'b'], ['c', 'd', 'e'], ['f', 'g', 'h', 'i']]
>>> np.nanmean(la, axis=(-2, -1))
array([1.75, 1.  ])
labels(['a', 'b'])
>>> arr = np.arange(24).reshape((2, 3, 4))
>>> labels = (('a', 'b'), ('c', 'd', 'e'), ('f', 'g', 'h', 'i'))
>>> ad = LabeledArray(arr, labels)
>>> ad[None, 'a'].labels
[['1'], ['c', 'd', 'e'], ['f', 'g', 'h', 'i']]
>>> ad['b', 0, np.array([[1,2], [0,3]])]
array([[13, 14],
       [12, 15]])
labels(['g-h', 'f-i']
       ['f-g', 'h-i'])
>>> ad[:, ('d','e'),][..., ('g', 'h'),].labels
[['a', 'b'], ['d', 'e'], ['g', 'h']]
>>> ad['a', 'd', ('g', 'i', 'f'),]
array([5, 7, 4])
labels(['g', 'i', 'f'])

Notes

Multiple sequence advanced indices objects are not supported. If you want

to use multiple sequence indices, you should use them one at a time.

References

[1] https://numpy.org/doc/stable/user/basics.subclassing.html [2] https://numpy.org/doc/stable/user/basics.indexing.html

property T[source]

View of the transposed array.

Same as self.transpose().

Examples

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
       [3, 4]])
>>> a.T
array([[1, 3],
       [2, 4]])
>>> a = np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> a.T
array([1, 2, 3, 4])

See also

transpose

__getitem__(orig_keys)[source][source]

Return self[key].

combine(levels: tuple[int, int]) LabeledArray[source][source]

Combine any levels of a LabeledArray into the lower level

Takes the input LabeledArray and rearranges its dimensions.

Parameters:
  • levels (tuple[int, int]) – The levels to combine, e.g. (0, 1) will combine the 1st and 2nd level of the array labels into one level at the 2nd level.

  • delim (str, optional) – The delimiter to use when combining labels, by default ‘-’

Returns:

The combined LabeledArray

Return type:

LabeledArray

Examples

>>> data = {'a': {'b': {'c': 1}}}
>>> ad = LabeledArray.from_dict(data, dtype=int)
>>> ad.combine((0, 2))
array([[1]])
labels(['b']
       ['a-c'])
>>> ad2 = LabeledArray([[[1,2],[3,4]],[[5,6],[7,8]]],
... labels=[('a', 'b'), ('c', 'd'), ('e', 'f')])
>>> ad2['a', : , 'e']
array([1, 3])
labels(['c', 'd'])
>>> ad2.combine((0, 2))
array([[1, 2, 5, 6],
       [3, 4, 7, 8]])
labels(['c', 'd']
       ['a-e', 'a-f', 'b-e', 'b-f'])
>>> np.mean(ad2.combine((0, 2)), axis=1)
array([3.5, 5.5])
labels(['c', 'd'])
>>> np.mean(ad2, axis=(0, 2))
array([3.5, 5.5])
labels(['c', 'd'])
concatenate(other: LabeledArray, axis: int = 0, mismatch: str = 'raise', ids: tuple[str, str] = ('0', '1'), **kwargs) LabeledArray[source][source]

Concatenate two LabeledArrays along an axis.

Parameters:
  • other (LabeledArray) – The LabeledArray to concatenate with.

  • axis (int, optional) – The axis to concatenate along, by default 0.

  • mismatch (str, optional) – What to do if the number of labels are not the same, ‘raise’ (default) will raise a ValueError, ‘shrink’ will shrink the labels to the smallest size, and ‘expand’ (not implemented) will expand the labels to the largest size, filling in with NaNs.

  • ids (tuple[str, str], optional) – The identifiers for the two arrays, used to create unique labels

  • kwargs (dict) – Additional keyword arguments to pass to np.concatenate.

Returns:

The concatenated LabeledArray.

Return type:

LabeledArray

Examples

>>> arr1 = LabeledArray([[1, 2],[3, 4]],
... labels=[('a', 'b'), ('c', 'd')])
>>> arr2 = LabeledArray([[5, 6],[7, 8]],
... labels=[('a', 'b'), ('c', 'd')])
>>> arr1.concatenate(arr2, axis=0)
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])
labels(['a-0', 'b-0', 'a-1', 'b-1']
       ['c', 'd'])
>>> arr3 = LabeledArray([[5, 6, 9],[7, 8, 10]],
... labels=[('a', 'b'), ('c', 'd', 'e')])
>>> arr4 = LabeledArray([[1, 2, 3],[3, 4, 5]],
... labels=[('a', 'b'), ('c', 'e', 'd')])
>>> arr3.concatenate(arr4, axis=0)
array([[ 5,  6,  9],
       [ 7,  8, 10],
       [ 1,  3,  2],
       [ 3,  5,  4]])
labels(['a-0', 'b-0', 'a-1', 'b-1']
       ['c', 'd', 'e'])
>>> arr2.concatenate(arr4, axis=0)
Traceback (most recent call last):
...
ValueError: When mismatch is 'raise', the base array must the same s...
>>> arr2.concatenate(arr4, 0, mismatch='shrink')
array([[5, 6],
       [7, 8],
       [1, 3],
       [3, 5]])
labels(['a-0', 'b-0', 'a-1', 'b-1']
       ['c', 'd'])
>>> arr3.concatenate(arr1, 0, mismatch='shrink')
Traceback (most recent call last):
...
NotImplementedError: Base array must the same size or smaller than i...
Base size:(2, 3), Input size: (2, 2)
>>> arr1.concatenate(arr3, 0, mismatch='expand')
array([[ 1.,  2., nan],
       [ 3.,  4., nan],
       [ 5.,  6.,  9.],
       [ 7.,  8., 10.]])
labels(['0-a', '0-b', '1-a', '1-b']
       ['c', 'd', 'e'])
dropna() LabeledArray[source][source]

Remove all nan values from the array.

Scans each column along any axis and removes all rows that contain only nan values.

Returns:

The array with all nan values removed.

Return type:

LabeledArray

Examples

>>> data = {'a': {'b': {'c': 1., 'd': np.nan}}}
>>> ad = LabeledArray.from_dict(data)
>>> ad.dropna()
array([[[1.]]])
labels(['a']
       ['b']
       ['c'])
>>> ad2 = LabeledArray([[[1,2],[3,4]],[[4,5],[6,7]],
... [[np.nan, np.nan], [np.nan, np.nan]]])
>>> ad2.dropna()
array([[[1., 2.],
        [3., 4.]],

       [[4., 5.],
        [6., 7.]]])
labels(['0', '1']
       ['0', '1']
       ['0', '1'])
classmethod from_dict(data: dict, **kwargs) LabeledArray[source][source]

Create a LabeledArray from a dictionary.

Parameters:

data (dict) – The dictionary to convert to a LabeledArray.

Returns:

The LabeledArray created from the dictionary.

Return type:

LabeledArray

Examples

>>> data = {'a': {'b': {'c': 1}}}
>>> LabeledArray.from_dict(data, dtype=int)
array([[[1]]])
labels(['a']
       ['b']
       ['c'])
>>> data = {'a': {'b': {'c': 1}}, 'd': {'b': {'c': 2, 'e': 3}}}
>>> LabeledArray.from_dict(data)
array([[[ 1., nan]],

       [[ 2.,  3.]]])
labels(['a', 'd']
       ['b']
       ['c', 'e'])
>>> data = {'a': {'b': np.array([[1, 2, 3]]), 'c' : [[4, 5], [6, 7]]},}
>>> LabeledArray.from_dict(data)
array([[[[ 1.,  2.,  3.],
         [nan, nan, nan]],

        [[ 4.,  5., nan],
         [ 6.,  7., nan]]]])
labels(['a']
       ['b', 'c']
       ['0', '1']
       ['0', '1', '2'])
>>> data = {'b': {'c': 1, 'd': 2, 'e': 3}, 'f': {'c': 4, 'e': 6}}
>>> LabeledArray.from_dict(data)
array([[ 1.,  2.,  3.],
       [ 4., nan,  6.]])
labels(['b', 'f']
       ['c', 'd', 'e'])
classmethod from_signal(sig: BaseRaw | BaseEpochs | Evoked, **kwargs) LabeledArray[source][source]

Create a LabeledArray from a Signal.

Parameters:

sig (Signal) – The Signal to convert to a LabeledArray.

Returns:

The LabeledArray created from the Signal.

Return type:

LabeledArray

Examples

>>> from bids import BIDSLayout
>>> from ieeg.io import raw_from_layout
>>> from ieeg.navigate import trial_ieeg
>>> import sys
>>> bids_root = mne.datasets.epilepsy_ecog.data_path()
>>> layout = BIDSLayout(bids_root)
>>> with mne.use_log_level(0):
...     raw = raw_from_layout(layout, subject="pt1", preload=True,
...     extension=".vhdr", verbose=False)
>>> LabeledArray.from_signal(raw, dtype=float)
array([[-8.98329883e-06,  8.20419238e-06,  7.42294287e-06, ...,
         1.07177293e-09,  1.07177293e-09,  1.07177293e-09],
       [ 2.99222000e-04,  3.03518844e-04,  2.96878250e-04, ...,
         3.64667153e-09,  3.64667153e-09,  3.64667153e-09],
       [ 2.44140953e-04,  2.30078469e-04,  2.19140969e-04, ...,
         3.85053724e-10,  3.85053724e-10,  3.85053724e-10],
       ...,
       [ 1.81263844e-04,  1.74232594e-04,  1.56263875e-04, ...,
         1.41283798e-08,  1.41283798e-08,  1.41283798e-08],
       [ 2.25390219e-04,  2.16015219e-04,  1.91405859e-04, ...,
        -2.91418821e-10, -2.91418821e-10, -2.91418821e-10],
       [ 3.14092313e-04,  3.71123375e-04,  3.91826437e-04, ...,
         3.07457047e-08,  3.07457047e-08,  3.07457047e-08]])
labels(['G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9', ...
>>> epochs = trial_ieeg(raw, "AD1-4, ATT1,2", (-1, 2), preload=True,
... verbose=False)
>>> LabeledArray.from_signal(epochs, dtype=float)
array([[[ 0.00021563,  0.00021563,  0.00020703, ..., -0.00051211,
         -0.00051445, -0.00050351],
        [-0.00030586, -0.00030625, -0.00031171, ..., -0.00016054,
         -0.00015976, -0.00015664],
        [-0.00010781, -0.00010469, -0.00010859, ...,  0.00026719,
          0.00027695,  0.00030156],
        ...,
        [-0.00021483, -0.00021131, -0.00023084, ..., -0.00034295,
         -0.00032381, -0.00031444],
        [-0.00052188, -0.00052852, -0.00053125, ..., -0.00046211,
         -0.00047148, -0.00047891],
        [-0.00033708, -0.00028005, -0.00020934, ..., -0.00040934,
         -0.00042341, -0.00040973]]])
...
classmethod fromfile(file: str, **kwargs) LabeledArray[source][source]

Create a LabeledArray from a file.

Parameters:
  • file (str) – The file to load the LabeledArray from.

  • **kwargs – Additional arguments to pass to np.load.

Returns:

The LabeledArray created from the file.

Return type:

LabeledArray

Examples

>>> arr = np.arange(24).reshape((2, 3, 4))
>>> labels = (('a', 'b'), ('c', 'd', 'e'), ('f', 'g', 'h', 'i'))
>>> la = LabeledArray(arr, labels)
>>> la.tofile('data')
>>> la2 = LabeledArray.fromfile('data')
>>> la == la2
True
swapaxes(axis1, axis2)[source][source]

Return a view of the array with axis1 and axis2 interchanged.

Refer to numpy.swapaxes for full documentation.

See also

numpy.swapaxes

equivalent function

take(indices, axis=None, **kwargs)[source][source]

Take elements from an array along an axis.

This function does not support the out argument.

Parameters:
  • indices (array_like) – The indices of the values to extract.

  • axis (int, optional) – The axis over which to select values, by default None.

  • kwargs (dict) – Additional keyword arguments to pass to np.take.

Returns:

The LabeledArray with the selected elements.

Return type:

LabeledArray

Examples

>>> arr = np.arange(24).reshape((2, 3, 4))
>>> labels = [('a', 'b'), ('c', 'd', 'e'), ('f', 'g', 'h', 'i')]
>>> ad = LabeledArray(arr, labels)
>>> ad.take([0, 2], axis=1).labels
[['a', 'b'], ['c', 'e'], ['f', 'g', 'h', 'i']]
>>> np.take_along_axis(ad, np.array([[[0, 1]]]), axis=2).labels
[['a', 'b'], ['c', 'd', 'e'], ['f', 'g']]
>>> np.take(ad, np.array([[0,2], [1,3]]), axis=2).labels
[['a', 'b'], ['c', 'd', 'e'], ['f-h', 'g-i'], ['f-g', 'h-i']]
>>> np.take(ad, np.array(['f','g']), axis=2)
array([[[ 0,  1],
        [ 4,  5],
        [ 8,  9]],

       [[12, 13],
        [16, 17],
        [20, 21]]])
labels(['a', 'b']
       ['c', 'd', 'e']
       ['f', 'g'])
>>> np.take(ad, 'f', axis=2).labels
[['a', 'b'], ['c', 'd', 'e']]
>>> np.take(ad, ('c','e'), axis=1).labels
[['a', 'b'], ['c', 'e'], ['f', 'g', 'h', 'i']]
to_dict() dict[source][source]

Convert to a dictionary.

Return type:

dict

tofile(fid: str, **kwargs) None[source][source]

Save the LabeledArray to a file.

Parameters:
  • file (str) – The file to save the LabeledArray to.

  • **kwargs – Additional arguments to pass to np.save.

  • fid (str)

Return type:

None

Examples

>>> arr = np.arange(24).reshape((2, 3, 4))
>>> labels = (('a', 'b'), ('c', 'd', 'e'), ('f', 'g', 'h', 'i'))
>>> la = LabeledArray(arr, labels)
>>> la.tofile('data')
>>> la2 = LabeledArray.fromfile('data')
>>> la == la2
True
transpose(*axes)[source][source]

Returns a view of the array with axes transposed.

Refer to numpy.transpose for full documentation.

Parameters:

axes (None, tuple of ints, or n ints) –

  • None or no argument: reverses the order of the axes.

  • tuple of ints: i in the j-th place in the tuple means that the array’s i-th axis becomes the transposed array’s j-th axis.

  • n ints: same as an n-tuple of the same ints (this form is intended simply as a “convenience” alternative to the tuple form).

Returns:

p – View of the array with its axes suitably permuted.

Return type:

ndarray

See also

transpose

Equivalent function.

ndarray.T

Array property returning the array transposed.

ndarray.reshape

Give a new shape to an array without changing its data.

Examples

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
       [3, 4]])
>>> a.transpose()
array([[1, 3],
       [2, 4]])
>>> a.transpose((1, 0))
array([[1, 3],
       [2, 4]])
>>> a.transpose(1, 0)
array([[1, 3],
       [2, 4]])
>>> a = np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> a.transpose()
array([1, 2, 3, 4])

Examples using ieeg.arrays.label.LabeledArray

PCA-LDA Decoding

PCA-LDA Decoding