yasa.transition_matrix
-
yasa.transition_matrix(hypno)[source] Create a state-transition matrix from an hypnogram.
New in version 0.1.9.
- Parameters
- hypnoarray_like
Hypnogram. The dtype of
hypnomust be integer (e.g. [0, 2, 2, 1, 1, 1, …]). The sampling frequency must be the original one, i.e. 1 value per 30 seconds if the staging was done in 30 seconds epochs. Using an upsampled hypnogram will result in an incorrect transition matrix. For best results, we recommend using an hypnogram cropped to either the time in bed (TIB) or the sleep period time (SPT).
- Returns
- countsarray
Counts transition matrix (number of transitions from stage X to stage Y).
- probsarray
Conditional probability transition matrix, i.e. given that current state is X, what is the probability that the next state is Y.
probsis a right stochastic matrix, i.e. each row sums to 1.
Examples
>>> from yasa import transition_matrix >>> a = [1, 1, 1, 0, 0, 2, 2, 0, 2, 0, 1, 1, 0, 0] >>> counts, probs = transition_matrix(a) >>> counts 0 1 2 Stage 0 2 1 2 1 2 3 0 2 2 0 1
>>> probs 0 1 2 Stage 0 0.400000 0.2 0.400000 1 0.400000 0.6 0.000000 2 0.666667 0.0 0.333333
We can plot the transition matrix using
seaborn.heatmap():>>> import numpy as np >>> import seaborn as sns >>> import matplotlib.pyplot as plt >>> from yasa import transition_matrix >>> # Calculate probability matrix >>> a = [1, 1, 1, 0, 0, 2, 2, 0, 2, 0, 1, 1, 0, 0] >>> _, probs = transition_matrix(a) >>> # Start the plot >>> grid_kws = {"height_ratios": (.9, .05), "hspace": .1} >>> f, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws, ... figsize=(5, 5)) >>> sns.heatmap(probs, ax=ax, square=False, vmin=0, vmax=1, cbar=True, ... cbar_ax=cbar_ax, cmap='YlOrRd', annot=True, fmt='.2f', ... cbar_kws={"orientation": "horizontal", "fraction": 0.1, ... "label": "Transition probability"}) >>> ax.set_xlabel("To sleep stage") >>> ax.xaxis.tick_top() >>> ax.set_ylabel("From sleep stage") >>> ax.xaxis.set_label_position('top')
