how to convert scored events in XML to annotations in MNE

Hi All

I feel dumb for asking this question. I am trying to load the MESA sleep dataset into MNE. The edf files are readily readable. The sleep stage raw data is in an XML file that looks like this:

<ScoredEvent>
<EventType>Stages|Stages</EventType>
<EventConcept>Stage 1 sleep|1</EventConcept>
<Start>5190.0</Start>
<Duration>30.0</Duration>
</ScoredEvent>
<ScoredEvent>
<EventType>Stages|Stages</EventType>
<EventConcept>Wake|0</EventConcept>
<Start>5220.0</Start>
<Duration>90.0</Duration>
</ScoredEvent>

and my code to parse and read the above into a numpy array is below:

ANNOTATIONS = {5: 'Sleep stage W',
               3: 'Sleep stage 1',
               2: 'Sleep stage 2',
               1: 'Sleep stage 3',
               1: 'Sleep stage 4',
               4: 'Sleep stage R'}

STAGE_DICT = {
    "Wake|0": 5,
    "Stage 1 sleep|1": 3,
    "Stage 2 sleep|2": 2,
    "Stage 3 sleep|3": 1,
    "Stage 4 sleep|4": 1,
    "REM sleep|5": 4,
    "Movement|6": 6,
    "Unscored|9": 6
}

        #file 1 is hyp file
        print('processing %s as hypnogram event file' % files[f])
        nsrr = ET.parse(DATA_FOLDER + files[f]).findall('ScoredEvents')
        events = []
        for event in nsrr[0]:
            if not event[0].text == "Stages|Stages":
                continue
            stage = STAGE_DICT[event[1].text]
            start = int(float(event[2].text))
            dur = int(float(event[3].text))
            events.append([start,dur,stage])
        events = np.array(events)
        hngFile = mne.annotations_from_events(events=events,sfreq=256.,event_desc=ANNOTATIONS)

the events array looks like this:

image

but the hngFile is garbage - the durations are all zero and the onset deltas are all in hundredths of a second - which doesn’t match the XML

There is likely something simple that I am doing wrong. If anyone can explain this to me I would be thankful.

regards

Robert

Sorry for the trouble. I figured it out via google search. The answer is simple:

hngFile = mne.Annotations(onset=onsets,duration=durations,description=descriptions)

1 Like

thank you for posting the answer to your own question! :heart:

1 Like