Annotations

This script demonstrates the use of nnsa.Annotation and nnsa.AnnotationSet object. These can be used to store text annotations with a specific time and duration. They are for example used to read annotations from an EDF+ file and may be useful for processing sleep stage annotations.

Author: Tim Hermans (tim-hermans@hotmail.com).

Link to script: annotations.py

import numpy as np
from nnsa import Annotation, AnnotationSet

The Annotation object has 3 properties: onset (int, float), duration (int, float) and text (str) specifying the onset time in seconds, the duration of the annotation in seconds, and the annotation text, respectively. If the duration of an annotation is not applicable, the duration should be set to np.nan.

# We create an Annotation.
annot = Annotation(onset=10.25, duration=100, text='Quiet sleep')

# We can print the annotation:
print(annot)

We may alter the values of the annotation, as long as the value types are valid (float or int for onset and duration, str for text).

# Change the text to 'QS'.
annot.text = 'QS'
print(annot)

Typically we have a collection of annotations for a recording. Such a collection can be contained in an AnnotationSet object.

# We can initiate an AnnotationSet variable to contain a collection of Annotations.
annot_set = AnnotationSet()

# Add annot to the AnnotationSet using the .append method (the .append method checks whether the to be
# appended item is an Annotation object and then appends the item to a list containing all annotations in the
# AnnotationSet).
annot_set.append(annot, inplace=True)

# We can append other annotations to the set (inplace).
annot_set.append(Annotation(110.25, 200, 'AS'), inplace=True)
annot_set.append(Annotation(500, np.nan, 'Lights on'), inplace=True)

# We can print a summary of the annotation set:
print(annot_set)

# We can list the information of all annotations in the annotation set:
annot_set.print_all_annotations()

We can also instantiate an AnnotationSet from an iterable (e.g. a list).

# List of annotations.
annot_list = [
    Annotation(110.25, 200, 'AS'),
    Annotation(500, np.nan, 'Lights on'),
]

# Create AnnotationSet.
annot_set_2 = AnnotationSet(annot_list.copy())
print(annot_set_2)

We may extend the annotation set with a list of annotations.

# Note: if inplace=False (default), then a new object is returned.
annot_set = annot_set.extend(annot_list, inplace=False)
print(annot_set)

Using extend, we can also merge two annotation sets:

annot_set.extend(annot_set_2, inplace=True)
print(annot_set)

There exist a bunch of methods for AnnotationSet that can be handy. See the documentation of AnnotationSet for a list of these methods: https://nnsa.readthedocs.io/en/latest/nnsa.annotations.html#nnsa.annotations.annotation_set.AnnotationSet

An AnnotationSet can be converted to a pandas DataFrame:

df = annot_set.to_df()