Markers

Initialize NeuroAnalyzer
using NeuroAnalyzer
import CairoMakie
# Quarto sets a default figure size (672 × 480 px), which overrides the sizes of
# NeuroAnalyzer figures: remove it
delete!(CairoMakie.Makie.CURRENT_DEFAULT_THEME, :resolution)
using DataFrames

Markers (events, triggers, annotations) mark moments or periods of the recording: stimuli, responses, condition changes, artifacts or notes of the technician. They are used to create event-related epochs (e.g. for ERPs), to select or reject segments of the signal and to document the recording.

Marker Table

Markers are stored in obj.markers, a DataFrame with one row per marker:

Column Type Contents
:type String marker type, e.g. "stim" (see below)
:start Float64 start of the marker in seconds from the start of the recording
:length Float64 duration in seconds (0 or one sample for instantaneous events)
:value String code or condition (used by epoch()), e.g. "s71" or "eyes open"
:channel Vector{String} labels of the channels the marker refers to; empty = all channels

The fixed columns may be followed by extra columns, e.g. trial_type or response_time of a BIDS events.tsv file (imported with the recording); all marker functions keep them, and markers added by NeuroAnalyzer have missing in them.

The type says what kind of marker it is and the value which one (e.g. the trigger code or the condition). All importers use the same marker types:

Type Meaning Examples of sources
stim stimulus onset, trigger BrainVision Stimulus, FIFF and GDF trigger events, EEGLAB events, channel2marker()
response response of the subject BrainVision Response
annotation note, free text EDF+ annotations, MNE annotations, BrainVision Comment
BAD bad segment (of all or some channels) MNE BAD_… annotations, GDF artifact events
boundary discontinuity of the signal trim(), join_epoch(), BrainVision New Segment, EEGLAB boundary, pauses of DigiTrack exams
epoch epoch onset
other other types unknown types of other programs

A face perception experiment recorded in the BrainVision format:

faces = import_recording("files/eeg/s1_faces.vhdr")
first(faces.markers, 6)
6×5 DataFrame
Row type start length value channel
String Float64 Float64 String Array…
1 boundary 0.0 0.00195312 marker String[]
2 stim 0.0 0.00195312 Impedance String[]
3 stim 20.5605 0.00195312 s111 String[]
4 stim 20.9785 0.00195312 s130 String[]
5 stim 21.8242 0.00195312 s71 String[]
6 stim 25.0098 0.00195312 s130 String[]

Number of markers of each value:

combine(groupby(faces.markers, :value), nrow => :n)
9×2 DataFrame
Row value n
String Int64
1 marker 1
2 Impedance 1
3 s111 1
4 s130 200
5 s71 100
6 s70 100
7 s121 1
8 s122 1
9 s102 1

Most formats store events in the file and they are imported automatically, e.g. EDF+ annotations, BrainVision .vmrk files, EEGLAB events and events of MEGIN (FIFF) recordings. EDF+ annotations are often free-text notes of the technician:

eeg = import_edf("files/eeg/eeg-test-edfplus.edf")
first(eeg.markers, 8)
8×5 DataFrame
Row type start length value channel
String Float64 Float64 String Array…
1 annotation 0.0 0.0 REC START BioCal CAL String[]
2 annotation 1.14 0.0 A1+A2 OFF String[]
3 annotation 4.22 0.0 IMP CHECK ON String[]
4 annotation 8.24 0.0 IMP CHECK OFF String[]
5 annotation 10.24 0.0 PAT BioCal EEG String[]
6 annotation 17.07 0.0 PAT 1-Banana EEG String[]
7 annotation 21.64 0.0 Head Straight String[]
8 annotation 23.38 0.0 Awake String[]

view_marker() prints the marker table, and markers are drawn by default in signal plots (vertical lines labelled with the marker type and value); the signal is high-pass filtered here to remove the DC offsets of the raw recording:

faces_hp = NeuroAnalyzer.filter(faces;
                                ch = "eeg",
                                fprototype = :butterworth,
                                ftype = :hp,
                                cutoff = 0.5,
                                order = 4)
NeuroAnalyzer.plot(faces_hp; ch = "eeg", seg = (20, 30), gui = false)

Editing Markers

Markers are added, edited and deleted with add_marker!(), edit_marker!() and delete_marker!() (or their non-mutating versions). A single marker is referred to by its row number:

e = crop(eeg; seg = (60, 120))
e.markers = e.markers[1:0, :]
add_marker!(e; type = "annotation", start = 10, len = 0.5,
            value = "eyes open")
add_marker!(e; type = "annotation", start = 40, len = 0.5,
            value = "eyes closed")
edit_marker!(e; n = 2, start = 45)
view_marker(e)
n    type          start [s]   length [s]  value                   channel
1    annotation    10.0        0.5         'eyes open'             all
2    annotation    45.0        0.5         'eyes closed'           all

A marker applies to all channels unless channels are given with ch (a label or a vector of labels), e.g. a bad segment of two channels:

add_marker!(e; type = "BAD", start = 20, len = 2, value = "artifact",
            ch = ["Fp1", "Fp2"])
view_marker(e)
n    type          start [s]   length [s]  value                   channel
1    annotation    10.0        0.5         'eyes open'             all
2    BAD           20.0        2.0         'artifact'              Fp1;Fp2
3    annotation    45.0        0.5         'eyes closed'           all

The marker channels are labels, so they follow the channels when channels are renamed (rename_channel(), re-referencing, e.g. Fp1 becomes Fp1-avg after reference_avg()) or deleted (a deleted channel is removed from the markers; a marker of deleted channels only is removed).

delete_marker!(e; n = 1)
println("markers: ", nrow(e.markers))
markers: 2

add_markers() replaces the whole marker table with a DataFrame of the same columns:

m = DataFrame(:type => ["stim", "stim"],
              :start => [5.0, 15.0],
              :length => [0.0, 0.0],
              :value => ["A", "B"],
              :channel => [String[], ["O1", "O2"]])
add_markers!(e; markers = m)
e.markers
2×5 DataFrame
Row type start length value channel
String Float64 Float64 String Array…
1 stim 5.0 0.0 A String[]
2 stim 15.0 0.0 B ["O1", "O2"]

Editing many markers at once

edit_marker() and delete_marker() select the markers by number (n, a number, a vector or a range), or by value and type (value, type: a string, a vector of strings or a regex; with both, markers matching both are selected). Without a selection, edit_marker() edits all markers. The changes are given with new_value, new_type, start (one marker only), len, ch and shift.

Merging several values into one, e.g. the codes of all target stimuli:

m = DataFrame(:type => ["stim", "stim", "stim", "response"],
              :start => [5.0, 15.0, 25.0, 25.6],
              :length => zeros(4),
              :value => ["11", "12", "21", "1"],
              :channel => [String[] for _ in 1:4])
add_markers!(e; markers = m)
edit_marker!(e; value = ["11", "12"], new_value = "target")
e.markers[!, [:type, :start, :value]]
4×3 DataFrame
Row type start value
String Float64 String
1 stim 5.0 target
2 stim 15.0 target
3 stim 25.0 21
4 response 25.6 1

Renaming values with a dictionary of old => new values (other values are not changed):

edit_marker!(e; new_value = Dict("21" => "standard", "1" => "button"))
e.markers[!, [:type, :start, :value]]
4×3 DataFrame
Row type start value
String Float64 String
1 stim 5.0 target
2 stim 15.0 target
3 stim 25.0 standard
4 response 25.6 button

Shifting markers by a fixed delay, e.g. to correct the latency of the trigger (the delay between the trigger and the stimulus on the screen, measured with a photodiode), here 23 ms for the stimulus markers only:

edit_marker!(e; type = "stim", shift = 0.023)
e.markers[!, [:type, :start, :value]]
4×3 DataFrame
Row type start value
String Float64 String
1 stim 5.023 target
2 stim 15.023 target
3 stim 25.023 standard
4 response 25.6 button

Different delays for different marker values, e.g. when the stimuli are presented on different devices (a dictionary of value => delay; markers with other values are not shifted):

edit_marker!(e; shift = Dict("target" => 0.008, "standard" => 0.004))
e.markers[!, [:type, :start, :value]]
4×3 DataFrame
Row type start value
String Float64 String
1 stim 5.031 target
2 stim 15.031 target
3 stim 25.027 standard
4 response 25.6 button

Markers moved outside the signal are deleted (with a warning), markers ending after the end of the signal are shortened.

Deleting markers by value, type or regex:

delete_marker!(e; type = "response")
delete_marker!(e; value = r"^stand")
e.markers[!, [:type, :start, :value]]
2×3 DataFrame
Row type start value
String Float64 String
1 stim 5.031 target
2 stim 15.031 target

Markers stored in a separate EDF+ annotations file are imported with import_edf_annotations(), which returns such a table. A marker table with times in samples (e.g. from another program) is converted to seconds with markers_s2t():

m_samples = DataFrame(:type => ["stim"],
                      :start => [2561],
                      :length => [256],
                      :value => ["A"],
                      :channel => [String[]])
markers_s2t(m_samples; fs = 256)
1×5 DataFrame
Row type start length value channel
String Float64 Float64 String Array…
1 stim 10.0 1.0 A String[]

Markers are exported to a CSV file with export_markers() (the channel labels are written separated by ;, empty: all channels) and imported with import_markers(), which returns a marker table for add_markers():

f = tempname() * ".csv"
export_markers(e; file_name = f)
m = import_markers(f)
add_markers!(e; markers = m)
e.markers
2×5 DataFrame
Row type start length value channel
String Float64 Float64 String Array…
1 stim 5.031 0.0 target String[]
2 stim 15.031 0.0 target String[]

import_markers() also reads BIDS events.tsv files: onset and duration give the start and length, trial_type and value the marker type and value, and the other columns (e.g. response_time) are kept as extra marker columns.

Markers from an Event Channel

Some systems record events as pulses (trigger codes) in a dedicated channel, e.g. the stimulus channels (STI …) of MEGIN MEG systems. A trigger channel of a MEG recording contains several event codes:

meg = import_fiff("files/meg/test_raw.fif")
sti = extract_channel(meg; ch = "STI 014")
println("event codes: ", Int.(sort(unique(sti))))
event codes: [0, 1, 2, 3, 4, 5, 32]

channel2marker() converts the pulses of one code (v) into markers; the marker start is the first sample of the pulse and its length the duration of the pulse:

m = channel2marker(meg; ch = "STI 014", v = 1, value = "STI 014: 1")
println("events with code 1 in STI 014:       ",
        sum(m.markers.value .== "STI 014: 1"))
println("imported markers with value 1 (FIFF): ",
        sum(meg.markers.value .== "1"))
events with code 1 in STI 014:       7
imported markers with value 1 (FIFF): 7

For FIFF recordings the events are also imported automatically from the event table of the file; both give the same events.

Using Markers

Event-related epochs

epoch() creates epochs time-locked to the markers of a given value (marker_type limits them to one type, e.g. marker_type = "stim"): offset is the time before the marker and ep_len the epoch length (seconds):

ep71 = epoch(faces; marker_value = "s71", offset = 0.2, ep_len = 1.0)
println("epochs: ", nepochs(ep71), ", epoch time: ", ep71.epoch_time[1],
        " … ", round(ep71.epoch_time[end]; digits = 3), " s")
epochs: 100, epoch time: -0.2 … 0.798 s

Markers of the epochs whose window would extend beyond the signal are skipped. All markers that fall inside the epochs (of any value) are kept and moved to the timeline of the epoched object. Averaging these epochs gives the event-related potential; see ERP.

Several markers and conditions

marker_value may also be a list of values or a regular expression; each epoch gets a condition label, stored in the epoch metadata (obj.epochs). By default the condition is the marker value; condition takes the name of another marker column (e.g. "trial_type" of BIDS events) or a dictionary of values and labels (e.g. Dict("s70" => "A", "s71" => "A") joins two marker values into one condition):

ep = epoch(faces; marker_value = ["s70", "s71", "s130"], offset = 0.2,
           ep_len = 1.0)
combine(groupby(ep.epochs, :condition), nrow => :n)
3×2 DataFrame
Row condition n
String Int64
1 s130 200
2 s71 100
3 s70 100

get_epochs() returns the epoch numbers of a condition (without the epochs marked as rejected by epoch_reject!()), e.g. for keep_epoch() or the statistical functions that take epoch numbers; average_epochs() averages the epochs of one condition:

println("s130 epochs: ", length(get_epochs(ep; condition = "s130")))
erp130 = average_epochs(ep; condition = "s130")
println("averaged epochs: ", nepochs(erp130) - 1)
s130 epochs: 200
averaged epochs: 200

Selecting segments

Markers can be used to select parts of the recording, e.g. the signal between two markers:

t1 = faces.markers[findfirst(==("s111"), faces.markers.value), :start]
t2 = faces.markers[findlast(==("s70"), faces.markers.value), :start]
task = crop(faces; seg = (t1, t2))
println("task: ", round(t1; digits = 2), " … ", round(t2; digits = 2),
        " s, duration ", round(signal_duration(task); digits = 2), " s")
task: 20.56 … 792.07 s, duration 771.51 s

Marker Timing

Marker times are stored in seconds, not in samples. Their precision is therefore not tied to the sampling rate, and they keep their values when the sampling rate changes. Whenever an operation must place a marker at a sample, the time is rounded to the nearest sample (never rounded down):

\[ \text{sample} = \text{round}(t \cdot f_s) + 1 \]

(sample 1 is at \(t = 0\)). Rounding to the nearest sample, rather than truncating, also prevents floating-point errors (e.g. \(0.3 \times 10 = 3.0000000000000004\)) from shifting a marker by one sample.

t2s() and s2t() convert between time and sample number, t2n() and n2t() between a duration and a number of samples:

fs = sr(faces)
t = faces.markers[3, :start]
s = t2s(t, fs)
println("marker at ", t, " s → sample ", s, " → ", s2t(s, fs), " s")
println("1 s = ", t2n(1, fs), " samples, 512 samples = ", n2t(512, fs), " s")
marker at 20.560546875 s → sample 10528 → 20.560546875 s
1 s = 512 samples, 512 samples = 1.0 s

What happens to the markers in different operations

Operation Markers
import times converted to seconds as stored in the file
resample(), upsample(), downsample() unchanged (times in seconds); a marker may fall between two samples of the new sampling rate
epoch() (by markers), trim(), crop() moved: converted to the nearest sample, shifted and converted back to seconds (snapped to the sample grid)
filtering, referencing and other processing unchanged

Resampling a 512 Hz recording to 128 Hz, then cropping it:

faces128 = resample(faces; new_sr = 128)
c = crop(faces128; seg = (10, 60))
idx = findfirst(==("s111"), faces.markers.value)
t_orig = faces.markers[idx, :start]
t_rs = faces128.markers[idx, :start]
t_crop = c.markers[findfirst(==("s111"), c.markers.value), :start]
println("original (512 Hz):   ", t_orig, " s")
println("resampled (128 Hz):  ", t_rs, " s = sample ",
        t_rs * 128 + 1, " (between samples)")
println("cropped from 10 s:   ", t_crop, " s (exact: ", t_orig - 10, " s)")
println("difference:          ",
        round(1000 * (t_crop - (t_orig - 10)); digits = 2), " ms")
original (512 Hz):   20.560546875 s
resampled (128 Hz):  20.560546875 s = sample 2632.75 (between samples)
cropped from 10 s:   10.5625 s (exact: 10.560546875 s)
difference:          1.95 ms

Resampling keeps the marker time; cropping places it at the nearest sample of the 128 Hz signal.

A marker therefore loses at most half a sampling interval of precision, and only when it is moved:

Sampling rate Sampling interval Maximum marker shift
128 Hz 7.8 ms 3.9 ms
250 Hz 4 ms 2 ms
512 Hz 1.95 ms 0.98 ms
1000 Hz 1 ms 0.5 ms

Tip: Resampling to a lower sampling rate before epoching or trimming coarsens the timing of events to the new sampling interval. When the timing of events matters (e.g. ERP latencies), epoch the signal at the original sampling rate, or keep a sampling rate high enough for the required precision.