Skip to content

muap_comp

Functions to compute MUAP similarity and distance metrics

get_highest_iqr_ch

get_highest_iqr_ch(muap: ndarray) -> np.ndarray

Compute the highest interquartile range (IQR) channels.

Parameters:

Name Type Description Default
muap ndarray

Motor unit action potential with shape (ch_rows, ch_cols, samples)

required

Returns:

Name Type Description
ndarray ndarray

A boolean mask indicating the channels with the highest IQR.

Source code in motor_unit_toolbox/muap_comp.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def get_highest_iqr_ch(muap: np.ndarray) -> np.ndarray:
    """Compute the highest interquartile range (IQR) channels.

    Args:
        muap (ndarray): Motor unit action potential with shape
            (ch_rows, ch_cols, samples)

    Returns:
        ndarray: A boolean mask indicating the channels with the highest IQR.
    """

    peak_amps = np.amax(np.abs(muap), axis=-1)
    peak_amps = np.reshape(peak_amps, (-1))
    q1 = np.percentile(peak_amps, 25)
    q3 = np.percentile(peak_amps, 75)
    iqr = q3 - q1
    whis = 1.5
    outliers = peak_amps > q3 + whis * iqr
    ch_mask = np.reshape(outliers, (muap.shape[0], muap.shape[1]))
    return ch_mask

get_percentile_ch

get_percentile_ch(muap: ndarray, thr: Optional[int] = 90) -> np.ndarray

Compute the channels that exceed a certain percentile threshold.

Parameters:

Name Type Description Default
muap ndarray

Motor unit action potential with shape (ch_rows, ch_cols, samples)

required
thr int

The percentile threshold. Defaults to 90.

90

Returns:

Name Type Description
ndarray ndarray

A boolean mask indicating the channels that exceed the specified percentile threshold.

Source code in motor_unit_toolbox/muap_comp.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def get_percentile_ch(
    muap: np.ndarray,
    thr: Optional[int] = 90
) -> np.ndarray:
    """Compute the channels that exceed a certain percentile threshold.

    Args:
        muap (ndarray): Motor unit action potential with shape
            (ch_rows, ch_cols, samples)
        thr (int, optional): The percentile threshold. Defaults to 90.

    Returns:
        ndarray: A boolean mask indicating the channels that exceed the
            specified percentile threshold.
    """
    peak_amps = np.amax(np.abs(muap), axis=-1)
    peak_amps = np.reshape(peak_amps, (-1))
    outliers = peak_amps > np.percentile(peak_amps, thr)
    ch_mask = np.reshape(outliers, (muap.shape[0], muap.shape[1]))
    return ch_mask

get_highest_iqr_ptp_ch

get_highest_iqr_ptp_ch(muap: ndarray) -> np.ndarray

Compute the channels with the highest peak-to-peak (PTP) amplitude.

Parameters:

Name Type Description Default
muap ndarray

Motor unit action potential with shape (ch_rows, ch_cols, samples)

required

Returns:

Type Description
ndarray

np.ndarray: A boolean mask indicating the channels with the highest PTP amplitude.

Source code in motor_unit_toolbox/muap_comp.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def get_highest_iqr_ptp_ch(muap: np.ndarray) -> np.ndarray:
    """Compute the channels with the highest peak-to-peak (PTP) amplitude.

    Args:
        muap (np.ndarray): Motor unit action potential with shape
            (ch_rows, ch_cols, samples)

    Returns:
        np.ndarray: A boolean mask indicating the channels with the highest
            PTP amplitude.
    """

    peak_amps = np.ptp(muap, axis=-1)
    peak_amps = np.reshape(peak_amps, (-1))
    q1 = np.percentile(peak_amps, 25)
    q3 = np.percentile(peak_amps, 75)
    iqr = q3 - q1
    whis = 1.5
    outliers = peak_amps > q3 + whis * iqr
    ch_mask = np.reshape(outliers, (muap.shape[0], muap.shape[1]))
    return ch_mask

get_highest_amp_ch

get_highest_amp_ch(muap: ndarray) -> np.ndarray

Compute the channels with the highest amplitude.

Parameters:

Name Type Description Default
muap ndarray

Motor unit action potential with shape (ch_rows, ch_cols, samples)

required

Returns:

Name Type Description
ndarray ndarray

A boolean mask indicating the channels with the highest amplitude.

Source code in motor_unit_toolbox/muap_comp.py
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def get_highest_amp_ch(muap: np.ndarray) -> np.ndarray:
    """Compute the channels with the highest amplitude.

    Args:
        muap (ndarray): Motor unit action potential with shape
            (ch_rows, ch_cols, samples)

    Returns:
        ndarray: A boolean mask indicating the channels with the highest
            amplitude.
    """
    peak_amps = np.amax(np.abs(muap), axis=-1)
    amp_thr = 3 * np.std(peak_amps)
    ch_mask = peak_amps > amp_thr
    return ch_mask

get_highest_ptp_ch

get_highest_ptp_ch(muap: ndarray) -> np.ndarray

Compute the channels with the highest peak-to-peak (PTP) amplitude.

Parameters:

Name Type Description Default
muap ndarray

Motor unit action potential with shape (ch_rows, ch_cols, samples)

required

Returns:

Type Description
ndarray

np.ndarray: A boolean mask indicating the channels with the highest PTP amplitude.

Source code in motor_unit_toolbox/muap_comp.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def get_highest_ptp_ch(muap: np.ndarray) -> np.ndarray:
    """Compute the channels with the highest peak-to-peak (PTP) amplitude.

    Args:
        muap (np.ndarray): Motor unit action potential with shape
            (ch_rows, ch_cols, samples)

    Returns:
        np.ndarray: A boolean mask indicating the channels with the highest
            PTP amplitude.
    """
    ptp_amps = np.ptp(muap, axis=-1)
    amp_thr = 2 * np.std(ptp_amps)
    ch_mask = ptp_amps > amp_thr
    return ch_mask

nmse

nmse(muap1: ndarray, muap2: ndarray) -> float

Compute the normalized mean squared error (NMSE) between two MUAPs.

Parameters:

Name Type Description Default
muap1 ndarray

First motor unit action potential with shape (ch_rows, ch_cols, samples).

required
muap2 ndarray

Second motor unit action potential with shape (ch_rows, ch_cols, samples).

required

Returns:

Name Type Description
float float

The NMSE between the two MUAPs.

Source code in motor_unit_toolbox/muap_comp.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def nmse(muap1: np.ndarray, muap2: np.ndarray) -> float:
    """Compute the normalized mean squared error (NMSE) between two MUAPs.

    Args:
        muap1 (np.ndarray): First motor unit action potential with shape
            (ch_rows, ch_cols, samples).
        muap2 (np.ndarray): Second motor unit action potential with shape
            (ch_rows, ch_cols, samples).

    Returns:
        float: The NMSE between the two MUAPs.
    """
    mse = np.power(np.linalg.norm(muap1 - muap2), 2)
    m_energy = np.mean(
        np.power(np.linalg.norm(muap1), 2) + np.power(np.linalg.norm(muap2), 2)
    )

    return mse / m_energy

norm_farina_distance

norm_farina_distance(muap1: ndarray, muap2: ndarray) -> float

Compute the normalized Farina distance between two MUAPs.

Parameters:

Name Type Description Default
muap1 ndarray

First motor unit action potential with shape (ch_rows, ch_cols, samples).

required
muap2 ndarray

Second motor unit action potential with shape (ch_rows, ch_cols, samples).

required

Returns:

Name Type Description
float float

The normalized Farina distance between the two MUAPs.

Source code in motor_unit_toolbox/muap_comp.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def norm_farina_distance(muap1: np.ndarray, muap2: np.ndarray) -> float:
    """Compute the normalized Farina distance between two MUAPs.

    Args:
        muap1 (np.ndarray): First motor unit action potential with shape
            (ch_rows, ch_cols, samples).
        muap2 (np.ndarray): Second motor unit action potential with shape
            (ch_rows, ch_cols, samples).

    Returns:
        float: The normalized Farina distance between the two MUAPs.
    """
    # Check dimensions
    if len(muap1.shape) == 1:
        muap1 = np.expand_dims(muap1, axis=0)
    if len(muap2.shape) == 1:
        muap2 = np.expand_dims(muap2, axis=0)

    # Compute means
    muap1_mean = np.mean(muap1, axis=-1)
    muap2_mean = np.mean(muap2, axis=-1)

    # Compute norms
    muap1_l2 = np.linalg.norm(muap1, 2)
    muap2_l2 = np.linalg.norm(muap2, 2)

    # Normalise muaps
    muap1_norm = (muap1 - muap1_mean[:, None]) / muap1_l2
    muap2_norm = (muap2 - muap2_mean[:, None]) / muap2_l2

    # Compute energy
    muap1_energy = np.sum(np.power(muap1_norm, 2))
    muap2_energy = np.sum(np.power(muap2_norm, 2))

    # Compute normalized farina distance
    muaps_nfd = (2 * np.sum(np.power(muap1_norm - muap2_norm, 2))) / (
        muap1_energy + muap2_energy
    )

    return muaps_nfd

get_alignment

get_alignment(muap1: ndarray, muap2: ndarray, flag_debug: Optional[bool] = False) -> int

Compute the alignment lag between two MUAPs.

Parameters:

Name Type Description Default
muap1 ndarray

First motor unit action potential with shape (ch_rows, ch_cols, samples).

required
muap2 ndarray

Second motor unit action potential with shape (ch_rows, ch_cols, samples).

required
flag_debug bool

Flag to enable debug mode. Defaults to False.

False

Returns:

Name Type Description
int int

The alignment lag between the two MUAPs.

Source code in motor_unit_toolbox/muap_comp.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def get_alignment(
        muap1: np.ndarray,
        muap2: np.ndarray,
        flag_debug: Optional[bool] = False
        ) -> int:
    """Compute the alignment lag between two MUAPs.

    Args:
        muap1 (np.ndarray): First motor unit action potential with shape
            (ch_rows, ch_cols, samples).
        muap2 (np.ndarray): Second motor unit action potential with shape
            (ch_rows, ch_cols, samples).
        flag_debug (bool, optional): Flag to enable debug mode. Defaults to
            False.

    Returns:
        int: The alignment lag between the two MUAPs.
    """
    # Get the muap length
    muap_length = muap1.shape[-1]

    # Flatten muaps for the correlation
    muap1_flat = muap1.flatten()
    muap2_flat = muap2.flatten()

    # Compute correlation and lags
    corr = signal.correlate(muap1_flat, muap2_flat, mode="full")
    lags = signal.correlation_lags(len(muap1_flat), len(muap2_flat), mode="full")

    # Bound both to half the muap length in each direction
    boundary_mask = np.nonzero(
        np.logical_and(lags >= -muap_length // 2, lags <= muap_length // 2)
    )[0]
    bounded_corr = corr[boundary_mask]
    bounded_lags = lags[boundary_mask]
    muaps_lag = bounded_lags[np.argmax(np.abs(bounded_corr))].astype(int)

    if not np.isscalar(muaps_lag):
        # If there is more than one possible lag, choose the minimum
        muaps_lag = np.amin(muaps_lag)

    if flag_debug:
        _, axs = plt.subplots(3, 1)

        axs[0].plot(bounded_lags, bounded_corr)
        axs[0].plot(muaps_lag, bounded_corr[np.argmax(np.abs(bounded_corr))], "ro")
        axs[0].set_ylabel("Correlation")
        axs[0].set_xlabel("Lags")
        axs[0].grid(True)
        axs[0].set_xlim([bounded_lags[0], bounded_lags[-1]])
        axs[0].set_title(f"max_corr = {np.amax(bounded_corr):.3f} at lag = {muaps_lag}")

        axs[1].plot(muap1_flat)
        axs[1].plot(muap2_flat)
        axs[1].grid(True)
        axs[1].set_xlim([0, len(muap1_flat)])
        axs[1].set_title("Before alignment")

        axs[2].plot(muap1_flat)
        axs[2].plot(np.roll(muap2_flat, muaps_lag, axis=-1))
        axs[2].grid(True)
        axs[2].set_xlim([0, len(muap1_flat)])
        axs[2].set_title(f"After alignment (lag = {muaps_lag})")

        plt.tight_layout()
        plt.show()

    return muaps_lag

compute_muaps_similarity

compute_muaps_similarity(muap1: ndarray, muap2: ndarray, sel_chs_by: Literal['iqr', 'iqr_ptp', 'max_abs', 'ptp'] = 'iqr', metric: Literal['corr', 'cosine', 'nmse', 'nfd'] = 'nmse') -> Tuple[float, int]

Compute the similarity between two MUAPs.

Parameters:

Name Type Description Default
muap1 ndarray

First motor unit action potential with shape (ch_rows, ch_cols, samples).

required
muap2 ndarray

Second motor unit action potential with shape (ch_rows, ch_cols, samples).

required
sel_chs_by str

Method for selecting significant amplitude channels: "iqr", "iqr_ptp", "max_abs" or "ptp". Defaults to "iqr".

'iqr'
metric str

Similarity metric to compute: "corr", "cosine", "nmse" or "nfd". Defaults to "nmse".

'nmse'

Returns:

Type Description
Tuple[float, int]

Tuple[float, int]: The similarity between the two MUAPs and the alignment lag.

Source code in motor_unit_toolbox/muap_comp.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
def compute_muaps_similarity(
    muap1: np.ndarray,
    muap2: np.ndarray,
    sel_chs_by: Literal["iqr", "iqr_ptp", "max_abs", "ptp"] = "iqr",
    metric: Literal["corr", "cosine", "nmse", "nfd"] = "nmse"
) -> Tuple[float, int]:
    """Compute the similarity between two MUAPs.

    Args:
        muap1 (np.ndarray): First motor unit action potential with shape
            (ch_rows, ch_cols, samples).
        muap2 (np.ndarray): Second motor unit action potential with shape
            (ch_rows, ch_cols, samples).
        sel_chs_by (str, optional): Method for selecting significant
            amplitude channels: "iqr", "iqr_ptp", "max_abs" or "ptp". Defaults to "iqr".
        metric (str, optional): Similarity metric to compute:
            "corr", "cosine", "nmse" or "nfd". Defaults to "nmse".

    Returns:
        Tuple[float, int]: The similarity between the two MUAPs and the
            alignment lag.
    """
    # Get significant amplitude channels
    if sel_chs_by == "max_abs":
        muap1_ch_mask = get_highest_amp_ch(muap1)
        muap2_ch_mask = get_highest_amp_ch(muap2)
    elif sel_chs_by == "ptp":
        muap1_ch_mask = get_highest_ptp_ch(muap1)
        muap2_ch_mask = get_highest_ptp_ch(muap2)
    elif sel_chs_by == "iqr":
        muap1_ch_mask = get_highest_iqr_ch(muap1)
        muap2_ch_mask = get_highest_iqr_ch(muap2)
    elif sel_chs_by == "iqr_ptp":
        muap1_ch_mask = get_highest_iqr_ptp_ch(muap1)
        muap2_ch_mask = get_highest_iqr_ptp_ch(muap2)

    # Check if channel masks are empty
    if not np.any(muap1_ch_mask):
        muap1_ch_mask = np.empty(muap1.shape[0:2])
    if not np.any(muap2_ch_mask):
        muap2_ch_mask = np.empty(muap2.shape[0:2])

    # Apply the channel selection to the muaps and correct for the lag
    sel_chs = np.nonzero(np.logical_or(muap1_ch_mask, muap2_ch_mask))
    if not np.any(sel_chs):
        sel_chs = np.ones_like(muap1).astype(bool)

    muap1_sel = np.array(muap1[sel_chs])
    muap2_sel = np.array(muap2[sel_chs])

    # Align signals based on the selected channels
    muaps_lag = get_alignment(muap1_sel, muap2_sel)
    muap2_sel = np.roll(muap2_sel, muaps_lag, axis=-1)

    # Compute metric
    if metric == "corr":
        muaps_sim = stats.pearsonr(muap1_sel.flatten(), muap2_sel.flatten())[0]
    elif metric == "cosine":
        muaps_sim = 1 - spatial.distance.cosine(
            muap1_sel.flatten(), muap2_sel.flatten()
        )
    elif metric == "nmse":
        muaps_sim = 1 - nmse(muap1_sel.flatten(), muap2_sel.flatten())
    elif metric == "nfd":
        muaps_sim = 1 - norm_farina_distance(muap1_sel.flatten(), muap2_sel.flatten())

    return muaps_sim, muaps_lag

compute_muaps_dist

compute_muaps_dist(muap1: ndarray, muap2: ndarray, sel_chs_by: Literal['iqr', 'iqr_ptp', 'max_abs', 'ptp'] = 'iqr', metric: Literal['corr', 'cosine', 'nmse', 'nfd'] = 'nmse') -> Tuple[float, int]

Compute the distance between two MUAPs.

Parameters:

Name Type Description Default
muap1 ndarray

First motor unit action potential with shape (ch_rows, ch_cols, samples).

required
muap2 ndarray

Second motor unit action potential with shape (ch_rows, ch_cols, samples).

required
sel_chs_by str

Method for selecting significant amplitude channels: "iqr", "iqr_ptp", "max_abs" or "ptp". Defaults to "iqr".

'iqr'
metric str

Distance metric to compute: "corr", "cosine", "nmse" or "nfd". Defaults to "nmse".

'nmse'

Returns:

Type Description
Tuple[float, int]

Tuple[float, int]: The distance between the two MUAPs and the alignment lag.

Source code in motor_unit_toolbox/muap_comp.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def compute_muaps_dist(
        muap1: np.ndarray,
        muap2: np.ndarray,
        sel_chs_by: Literal["iqr", "iqr_ptp", "max_abs", "ptp"] = "iqr",
        metric: Literal["corr", "cosine", "nmse", "nfd"] = "nmse"
        ) -> Tuple[float, int]:
    """Compute the distance between two MUAPs.

    Args:
        muap1 (np.ndarray): First motor unit action potential with shape
            (ch_rows, ch_cols, samples).
        muap2 (np.ndarray): Second motor unit action potential with shape
            (ch_rows, ch_cols, samples).
        sel_chs_by (str, optional): Method for selecting significant
            amplitude channels: "iqr", "iqr_ptp", "max_abs" or "ptp". Defaults to "iqr".
        metric (str, optional): Distance metric to compute:
            "corr", "cosine", "nmse" or "nfd". Defaults to "nmse".

    Returns:
        Tuple[float, int]: The distance between the two MUAPs and the
            alignment lag.
    """

    # Get significant amplitude channels
    if sel_chs_by == "max_abs":
        muap1_ch_mask = get_highest_amp_ch(muap1)
        muap2_ch_mask = get_highest_amp_ch(muap2)
    elif sel_chs_by == "ptp":
        muap1_ch_mask = get_highest_ptp_ch(muap1)
        muap2_ch_mask = get_highest_ptp_ch(muap2)
    elif sel_chs_by == "iqr":
        muap1_ch_mask = get_highest_iqr_ch(muap1)
        muap2_ch_mask = get_highest_iqr_ch(muap2)
    elif sel_chs_by == "iqr_ptp":
        muap1_ch_mask = get_highest_iqr_ptp_ch(muap1)
        muap2_ch_mask = get_highest_iqr_ptp_ch(muap2)

    # Check if channel masks are empty
    if not np.any(muap1_ch_mask):
        muap1_ch_mask = np.empty(muap1.shape[0:2])
    if not np.any(muap2_ch_mask):
        muap2_ch_mask = np.empty(muap2.shape[0:2])

    # Apply the channel selection to the muaps and correct for the lag
    sel_chs = np.nonzero(np.logical_or(muap1_ch_mask, muap2_ch_mask))
    if not np.any(sel_chs):
        sel_chs = np.ones_like(muap1).astype(bool)

    muap1_sel = np.array(muap1[sel_chs])
    muap2_sel = np.array(muap2[sel_chs])

    # Align signals based on the selected channels
    muaps_lag = get_alignment(muap1_sel, muap2_sel)
    muap2_sel = np.roll(muap2_sel, muaps_lag, axis=-1)

    # Compute metric
    if metric == "corr":
        muaps_dist = 1 - stats.pearsonr(muap1_sel.flatten(), muap2_sel.flatten())[0]
    elif metric == "cosine":
        muaps_dist = spatial.distance.cosine(muap1_sel.flatten(), muap2_sel.flatten())
    elif metric == "nmse":
        muaps_dist = nmse(muap1_sel.flatten(), muap2_sel.flatten())
    elif metric == "nfd":
        muaps_dist = norm_farina_distance(muap1_sel.flatten(), muap2_sel.flatten())

    return muaps_dist, muaps_lag

compute_muaps_dist_sets

compute_muaps_dist_sets(muaps1: ndarray, muaps2: ndarray, dist_metric: Literal['corr', 'cosine', 'nmse', 'nfd'] = 'nmse', sel_chs_method: Literal['iqr', 'iqr_ptp', 'max_abs', 'ptp'] = 'iqr') -> Tuple[np.ndarray, np.ndarray]

Compute the distance between sets of MUAPs.

Parameters:

Name Type Description Default
muaps1 ndarray

First set of motor unit action potentials with shape (n_units1, ch_rows, ch_cols, samples).

required
muaps2 ndarray

Second set of motor unit action potentials with shape (n_units2, ch_rows, ch_cols, samples).

required
dist_metric str

Distance metric to compute: "corr", "cosine", "nmse" or "nfd". Defaults to "nmse".

'nmse'
sel_chs_method str

Method for selecting significant amplitude channels: "iqr", "iqr_ptp", "max_abs" or "ptp". Defaults to "iqr".

'iqr'

Returns:

Type Description
Tuple[ndarray, ndarray]

Tuple[np.ndarray, np.ndarray]: The distance matrix between the two sets of MUAPs and the alignment lag matrix.

Source code in motor_unit_toolbox/muap_comp.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
def compute_muaps_dist_sets(
    muaps1: np.ndarray,
    muaps2: np.ndarray,
    dist_metric: Literal["corr", "cosine", "nmse", "nfd"] = "nmse",
    sel_chs_method: Literal["iqr", "iqr_ptp", "max_abs", "ptp"] = "iqr"
) -> Tuple[np.ndarray, np.ndarray]:
    """Compute the distance between sets of MUAPs.

    Args:
        muaps1 (np.ndarray): First set of motor unit action potentials with shape
            (n_units1, ch_rows, ch_cols, samples).
        muaps2 (np.ndarray): Second set of motor unit action potentials with shape
            (n_units2, ch_rows, ch_cols, samples).
        dist_metric (str, optional): Distance metric to compute:
            "corr", "cosine", "nmse" or "nfd". Defaults to "nmse".
        sel_chs_method (str, optional): Method for selecting significant
            amplitude channels: "iqr", "iqr_ptp", "max_abs" or "ptp". Defaults to "iqr".

    Returns:
        Tuple[np.ndarray, np.ndarray]: The distance matrix between the two sets of
            MUAPs and the alignment lag matrix.
    """

    # Check muaps size
    if np.any([len(muaps1) == 0, len(muaps2) == 0]):
        # No units
        all_muaps_dist = np.empty(0)
        all_muaps_lags = np.empty(0)
    else:
        # Check units sizes
        if len(muaps1.shape) < 4:
            muaps1 = np.expand_dims(muaps1, axis=0)

        if len(muaps2.shape) < 4:
            muaps2 = np.expand_dims(muaps2, axis=0)

        # Initialise variables
        n_units1 = muaps1.shape[0]
        n_units2 = muaps2.shape[0]

        # Initialise output
        all_muaps_dist = np.zeros((n_units1, n_units2))
        all_muaps_lags = np.zeros((n_units1, n_units2))

        # Fill correlation matrix for each unique pair comparison
        for unit1, unit2 in itertools.product(range(n_units1), range(n_units2)):

            # Select motor units
            muap1 = muaps1[unit1]
            muap2 = muaps2[unit2]

            # Compute correlation and lags
            curr_muaps_dist, curr_muaps_lag = compute_muaps_dist(
                muap1, muap2, sel_chs_by=sel_chs_method, metric=dist_metric
            )

            # Fill matrices
            all_muaps_dist[unit1, unit2] = curr_muaps_dist
            all_muaps_lags[unit1, unit2] = curr_muaps_lag

    return all_muaps_dist, all_muaps_lags.astype(int)

compute_all_muaps_dist

compute_all_muaps_dist(muaps: ndarray, dist_metric: Literal['corr', 'cosine', 'nmse', 'nfd'] = 'nmse', sel_chs_method: Literal['iqr', 'iqr_ptp', 'max_abs', 'ptp'] = 'iqr') -> Tuple[np.ndarray, np.ndarray]

Compute the distance between all pairs of MUAPs.

Parameters:

Name Type Description Default
muaps ndarray

Motor unit action potentials with shape (n_units, ch_rows, ch_cols, samples).

required
dist_metric str

Distance metric to compute: "corr", "cosine", "nmse" or "nfd". Defaults to "nmse".

'nmse'
sel_chs_method str

Method for selecting significant amplitude channels: "iqr", "iqr_ptp", "max_abs" or "ptp". Defaults to "iqr".

'iqr'

Returns:

Type Description
Tuple[ndarray, ndarray]

Tuple[np.ndarray, np.ndarray]: The distance matrix between all pairs of MUAPs and the alignment lag matrix.

Source code in motor_unit_toolbox/muap_comp.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def compute_all_muaps_dist(
    muaps: np.ndarray,
    dist_metric: Literal["corr", "cosine", "nmse", "nfd"] = "nmse",
    sel_chs_method: Literal["iqr", "iqr_ptp", "max_abs", "ptp"] = "iqr"
    ) -> Tuple[np.ndarray, np.ndarray]:
    """Compute the distance between all pairs of MUAPs.

    Args:
        muaps (np.ndarray): Motor unit action potentials with shape
            (n_units, ch_rows, ch_cols, samples).
        dist_metric (str, optional): Distance metric to compute:
            "corr", "cosine", "nmse" or "nfd". Defaults to "nmse".
        sel_chs_method (str, optional): Method for selecting significant
            amplitude channels: "iqr", "iqr_ptp", "max_abs" or "ptp". Defaults to "iqr".

    Returns:
        Tuple[np.ndarray, np.ndarray]: The distance matrix between all pairs of MUAPs
            and the alignment lag matrix.
    """

    # Check muaps size
    if len(muaps) == 0:
        # No units
        all_muaps_dist = np.empty(0)
        all_muaps_lags = np.empty(0)
    else:
        # There are units
        if len(muaps.shape) < 4:
            muaps = np.expand_dims(muaps, axis=0)

        # Initialise variables
        n_units = muaps.shape[0]

        if n_units == 1:
            # Only one unit
            all_muaps_dist = np.array([0])
            all_muaps_lags = np.array([0])
        else:
            # More than one unit, so initialise pair combinations
            pairs = itertools.combinations(range(n_units), 2)
            all_muaps_dist = np.zeros((n_units, n_units))
            all_muaps_lags = np.zeros((n_units, n_units))

            # Fill correlation matrix for each unique pair comparison
            for pair in pairs:
                # Select motor units
                muap1 = muaps[pair[0]]
                muap2 = muaps[pair[1]]

                # Compute correlation and lags
                curr_muaps_dist, curr_muaps_lag = compute_muaps_dist(
                    muap1, muap2, sel_chs_by=sel_chs_method, metric=dist_metric
                )

                # Fill matrices
                all_muaps_dist[pair[0], pair[1]] = curr_muaps_dist
                all_muaps_dist[pair[1], pair[0]] = curr_muaps_dist

                all_muaps_lags[pair[0], pair[1]] = curr_muaps_lag
                all_muaps_lags[pair[1], pair[0]] = curr_muaps_lag

    return all_muaps_dist, all_muaps_lags.astype(int)

mask_within_trial_dist

mask_within_trial_dist(all_muaps_dist: ndarray, trial_labels: ndarray, fill_value: Optional[float] = None) -> np.ndarray

Set the distance between different MUAPs of the same trial to a large value.

Units identified in the same trial that are different motor units, should not be matched together. The diagonal (each unit with itself) is left at 0.

Parameters:

Name Type Description Default
all_muaps_dist ndarray

Distance matrix between all pairs of MUAPs with shape (n_units, n_units).

required
trial_labels ndarray

Trial label of each MUAP, with shape (n_units).

required
fill_value float

Distance assigned to pairs from the same trial. Defaults to 1 + the largest distance in the matrix.

None

Returns:

Type Description
ndarray

np.ndarray: A masked copy of the distance matrix. The input is not modified.

Source code in motor_unit_toolbox/muap_comp.py
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
def mask_within_trial_dist(
    all_muaps_dist: np.ndarray,
    trial_labels: np.ndarray,
    fill_value: Optional[float] = None,
) -> np.ndarray:
    """Set the distance between different MUAPs of the same trial to a large value.

    Units identified in the same trial that are different motor units, should
    not be matched together. The diagonal (each unit with itself) is left at 0.

    Args:
        all_muaps_dist (np.ndarray): Distance matrix between all pairs of MUAPs
            with shape (n_units, n_units).
        trial_labels (np.ndarray): Trial label of each MUAP, with shape (n_units).
        fill_value (float, optional): Distance assigned to pairs from the same
            trial. Defaults to 1 + the largest distance in the matrix.

    Returns:
        np.ndarray: A masked copy of the distance matrix. The input is not modified.
    """
    trial_labels = np.asarray(trial_labels)
    if trial_labels.shape != (all_muaps_dist.shape[0],):
        raise ValueError(
            f"trial_labels has shape {trial_labels.shape}, expected "
            f"({all_muaps_dist.shape[0]},) to match the distance matrix."
        )
    if fill_value is None:
        fill_value = np.nanmax(all_muaps_dist) + 1

    same_trial = trial_labels[:, None] == trial_labels[None, :]
    np.fill_diagonal(same_trial, False)

    masked_dist = np.array(all_muaps_dist, dtype=float)
    masked_dist[same_trial] = fill_value
    return masked_dist

cluster_muaps

cluster_muaps(all_muaps_dist: ndarray, cluster_method: Literal['single', 'complete', 'average', 'weighted', 'centroid', 'median', 'ward'] = 'ward', dist_metric: Literal['corr', 'cosine', 'nmse', 'nfd'] = 'corr', sel_chs_method: Literal['iqr', 'iqr_ptp', 'max_abs', 'ptp'] = 'iqr_ptp', thr_vals: Optional[ndarray] = np.arange(0, 2.0001, 0.001), flag_plot: Optional[bool] = True, *, trial_labels: Optional[ndarray] = None) -> Tuple[pd.DataFrame, Dict[str, np.ndarray]]

Cluster MUAPs based on distance matrix.

Parameters:

Name Type Description Default
all_muaps_dist ndarray

Distance matrix between all pairs of MUAPs.

required
cluster_method str

Linkage method passed to scipy.cluster.hierarchy.linkage. Defaults to "ward".

'ward'
dist_metric str

Distance metric used to build all_muaps_dist (stored in the output only). Defaults to "corr".

'corr'
sel_chs_method str

Channel selection method used to build all_muaps_dist (stored in the output only). Defaults to "iqr_ptp".

'iqr_ptp'
thr_vals ndarray

Threshold values for clustering. Defaults to np.arange(0, 2.0001, 0.001).

arange(0, 2.0001, 0.001)
flag_plot bool

Flag to plot clustering metrics. Defaults to True.

True
trial_labels ndarray

Trial label of each MUAP, with shape (n_units). If given, MUAPs from the same trial are made maximally distant before clustering (see mask_within_trial_dist), so they are not grouped together. Only "complete" linkage guarantees this; with other methods a warning lists any same-trial units merged at the selected threshold. The clustering metrics are always computed on the original distances. Defaults to None (no trial constraint).

None

Returns:

Type Description
Tuple[DataFrame, Dict[str, ndarray]]

Tuple[pd.DataFrame, Dict[str, np.ndarray]]: Optimal threshold information and clustering metrics. The dictionary contains the following keys: - "cluster_method" (str): The clustering method used. - "dist_metric" (str): The distance metric used. - "sel_chs_method" (str): The method used for selecting significant amplitude channels. - "labels" (np.ndarray): The cluster labels for each threshold value. - "n_clusters" (np.ndarray): The number of clusters for each threshold value. - "sil" (np.ndarray): The silhouette scores for each threshold value. - "chi" (np.ndarray): The Calinski-Harabasz scores for each threshold value. - "dbi" (np.ndarray): The Davies-Bouldin scores for each threshold value. - "w_dist_mean" (np.ndarray): The mean within-cluster distances for each threshold value. - "w_dist_std" (np.ndarray): The standard deviation of within-cluster distances for each threshold value. - "b_dist_mean" (np.ndarray): The mean between-cluster distances for each threshold value. - "b_dist_std" (np.ndarray): The standard deviation of between-cluster distances for each threshold value.

Source code in motor_unit_toolbox/muap_comp.py
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
def cluster_muaps(
    all_muaps_dist: np.ndarray,
    cluster_method: Literal[
        "single", "complete", "average", "weighted", "centroid", "median", "ward"
    ] = "ward",
    dist_metric: Literal["corr", "cosine", "nmse", "nfd"] = "corr",
    sel_chs_method: Literal["iqr", "iqr_ptp", "max_abs", "ptp"] = "iqr_ptp",
    thr_vals: Optional[np.ndarray] = np.arange(0, 2.0001, 0.001),  # noqa: B008 (read-only)
    flag_plot: Optional[bool] = True,
    *,
    trial_labels: Optional[np.ndarray] = None,
) -> Tuple[pd.DataFrame, Dict[str, np.ndarray]]:
    """Cluster MUAPs based on distance matrix.

    Args:
        all_muaps_dist (np.ndarray): Distance matrix between all pairs of MUAPs.
        cluster_method (str, optional): Linkage method passed to
            scipy.cluster.hierarchy.linkage. Defaults to "ward".
        dist_metric (str, optional): Distance metric used to build
            all_muaps_dist (stored in the output only). Defaults to "corr".
        sel_chs_method (str, optional): Channel selection method used to
            build all_muaps_dist (stored in the output only). Defaults to "iqr_ptp".
        thr_vals (np.ndarray, optional): Threshold values for clustering. Defaults to
            np.arange(0, 2.0001, 0.001).
        flag_plot (bool, optional): Flag to plot clustering metrics. Defaults to True.
        trial_labels (np.ndarray, optional): Trial label of each MUAP, with shape
            (n_units). If given, MUAPs from the same trial are made maximally distant
            before clustering (see `mask_within_trial_dist`), so they are not grouped
            together. Only "complete" linkage guarantees this; with other methods a
            warning lists any same-trial units merged at the selected threshold.
            The clustering metrics are always computed on the original distances.
            Defaults to None (no trial constraint).

    Returns:
        Tuple[pd.DataFrame, Dict[str, np.ndarray]]: Optimal threshold information and
            clustering metrics. The dictionary contains the following keys:
            - "cluster_method" (str): The clustering method used.
            - "dist_metric" (str): The distance metric used.
            - "sel_chs_method" (str): The method used for selecting significant amplitude
                channels.
            - "labels" (np.ndarray): The cluster labels for each threshold value.
            - "n_clusters" (np.ndarray): The number of clusters for each threshold value.
            - "sil" (np.ndarray): The silhouette scores for each threshold value.
            - "chi" (np.ndarray): The Calinski-Harabasz scores for each threshold value.
            - "dbi" (np.ndarray): The Davies-Bouldin scores for each threshold value.
            - "w_dist_mean" (np.ndarray): The mean within-cluster distances for each
                threshold value.
            - "w_dist_std" (np.ndarray): The standard deviation of within-cluster distances
                for each threshold value.
            - "b_dist_mean" (np.ndarray): The mean between-cluster distances for each
                threshold value.
            - "b_dist_std" (np.ndarray): The standard deviation of between-cluster distances
                for each threshold value.
    """

    # Initialise variables
    n_units = all_muaps_dist.shape[0]

    # Keep units from the same trial apart (only affects the linkage, not the metrics)
    link_dist = all_muaps_dist
    if trial_labels is not None:
        trial_labels = np.asarray(trial_labels)
        link_dist = mask_within_trial_dist(
            all_muaps_dist,
            trial_labels,
            fill_value=max(np.nanmax(all_muaps_dist), np.max(thr_vals)) + 1,
        )

    # Transform distance from redundant form into condensed form
    all_muaps_dist_cond = spatial.distance.squareform(link_dist)

    # Build linkage between
    link = cluster.hierarchy.linkage(all_muaps_dist_cond, method=cluster_method)

    # Initialise outputs
    cluster_out = {
        "cluster_method": cluster_method,
        "dist_metric": dist_metric,
        "sel_chs_method": sel_chs_method,
        "labels": np.empty((len(thr_vals), n_units)),
        "n_clusters": np.empty(len(thr_vals)),
        "sil": np.empty(len(thr_vals)),
        "chi": np.empty(len(thr_vals)),
        "dbi": np.empty(len(thr_vals)),
        "w_dist_mean": np.empty(len(thr_vals)),
        "w_dist_std": np.empty(len(thr_vals)),
        "b_dist_mean": np.empty(len(thr_vals)),
        "b_dist_std": np.empty(len(thr_vals)),
    }

    for i, thr in enumerate(thr_vals):

        # Apply hierarchical/agglomerative clustering
        cluster_out["labels"][i] = cluster.hierarchy.fcluster(
            link, t=thr, criterion="distance"
        )

        # Number of clusters
        cluster_out["n_clusters"][i] = np.amax(cluster_out["labels"][i])

        # Clustering metrics
        if (cluster_out["n_clusters"][i] > 1) & (
            cluster_out["n_clusters"][i] < n_units
        ):
            cluster_out["sil"][i] = metrics.silhouette_score(
                all_muaps_dist, cluster_out["labels"][i], metric="precomputed"
            )
            cluster_out["chi"][i] = metrics.calinski_harabasz_score(
                all_muaps_dist, cluster_out["labels"][i]
            )
            cluster_out["dbi"][i] = metrics.davies_bouldin_score(
                all_muaps_dist, cluster_out["labels"][i]
            )
        else:
            cluster_out["sil"][i] = np.nan
            cluster_out["chi"][i] = np.nan
            cluster_out["dbi"][i] = np.nan

        # Between and within cluster distance stats
        w_dist_mean = []
        w_dist_std = []
        b_dist_mean = []
        b_dist_std = []
        np.fill_diagonal(all_muaps_dist, np.nan)

        for curr_cluster in np.unique(cluster_out["labels"][i]):
            curr_cluster_mask = cluster_out["labels"][i] == curr_cluster

            # Single-unit clusters have no within distances and a single cluster has
            # no between distances: these are NaN (skipped quietly, not warned about)
            within_dists = all_muaps_dist[np.ix_(curr_cluster_mask, curr_cluster_mask)]
            between_dists = all_muaps_dist[
                np.ix_(curr_cluster_mask, np.logical_not(curr_cluster_mask))
            ]
            w_dist_mean.append(_nanmean_or_nan(within_dists))
            w_dist_std.append(_nanstd_or_nan(within_dists))
            b_dist_mean.append(_nanmean_or_nan(between_dists))
            b_dist_std.append(_nanstd_or_nan(between_dists))

        cluster_out["w_dist_mean"][i] = _nanmean_or_nan(w_dist_mean)
        cluster_out["w_dist_std"][i] = _nanmean_or_nan(w_dist_std)
        cluster_out["b_dist_mean"][i] = _nanmean_or_nan(b_dist_mean)
        cluster_out["b_dist_std"][i] = _nanmean_or_nan(b_dist_std)

        np.fill_diagonal(all_muaps_dist, 0)

    # Find maximum sil
    opt_sil_idx = np.nanargmax(cluster_out["sil"])
    opt_thr = thr_vals[opt_sil_idx]
    opt_sil = cluster_out["sil"][opt_sil_idx]
    opt_n_clusters = cluster_out["n_clusters"][opt_sil_idx]

    # Check the trial constraint held at the selected threshold
    if trial_labels is not None:
        _warn_same_trial_clusters(cluster_out["labels"][opt_sil_idx], trial_labels, opt_thr)

    # Store output in a dataframe
    opt_thr_info = pd.DataFrame(
        {
            "cluster_method": [cluster_method],
            "dist_metric": [dist_metric],
            "sel_chs_method": [sel_chs_method],
            "opt_sil": [opt_sil],
            "opt_idx": [opt_sil_idx],
            "opt_thr": [opt_thr],
            "opt_n_clusters": [opt_n_clusters],
        }
    )

    if flag_plot:
        # Plot metrics
        _, axs = plt.subplots(6, 1, figsize=(10, 10))
        axs = np.ravel(axs)

        cluster.hierarchy.dendrogram(
            link.tolist(),
            ax=axs[0],
            color_threshold=opt_thr_info["opt_thr"].values[0],
            leaf_font_size=12,
        )
        axs[0].set_title(
            f"{cluster_method}" +
            f"max sil = {opt_thr_info['opt_sil'].values[0]:.3f}, " +
            f"thr = {opt_thr_info['opt_thr'].values[0]:.3f}"
        )
        axs[0].set_xlabel("Motor units")
        axs[0].set_ylabel("Linkage distance")

        axs[1].plot(thr_vals, cluster_out["n_clusters"])
        axs[1].axvline(opt_thr_info["opt_thr"].values[0], color="r")
        axs[1].grid(True)
        axs[1].set_xlim([thr_vals[0], thr_vals[-1]])
        axs[1].set_xlabel("Distance thresholds")
        axs[1].set_ylabel("Number of clusters")

        axs[2].plot(thr_vals, cluster_out["w_dist_mean"], "-", label="w_dist")
        axs[2].fill_between(
            thr_vals,
            cluster_out["w_dist_mean"] - cluster_out["w_dist_std"],
            cluster_out["w_dist_mean"] + cluster_out["w_dist_std"],
            alpha=0.2,
            label=None,
        )
        axs[2].plot(thr_vals, cluster_out["b_dist_mean"], "-", label="b_dist")
        axs[2].fill_between(
            thr_vals,
            cluster_out["b_dist_mean"] - cluster_out["b_dist_std"],
            cluster_out["b_dist_mean"] + cluster_out["b_dist_std"],
            alpha=0.2,
            label=None,
        )
        axs[2].axvline(opt_thr_info["opt_thr"].values[0], color="r", label="opt_thr")
        axs[2].legend(bbox_to_anchor=(1.1, 1))
        axs[2].grid(True)
        axs[2].set_xlim([thr_vals[0], thr_vals[-1]])
        axs[2].set_xlabel("Distance thresholds")
        axs[2].set_ylabel("Distance")

        axs[3].plot(thr_vals, cluster_out["sil"])
        axs[3].plot(
            opt_thr_info["opt_thr"].values[0],
            opt_thr_info["opt_sil"].values[0],
            "ro",
            markersize=6,
        )
        axs[3].axvline(opt_thr_info["opt_thr"].values[0], color="r")
        axs[3].grid(True)
        axs[3].set_xlim([thr_vals[0], thr_vals[-1]])
        axs[3].set_xlabel("Distance thresholds")
        axs[3].set_ylabel("silhouette\n(maximise)")

        axs[4].plot(thr_vals, cluster_out["dbi"])
        axs[4].axvline(opt_thr_info["opt_thr"].values[0], color="r")
        axs[4].grid(True)
        axs[4].set_xlim([thr_vals[0], thr_vals[-1]])
        axs[4].set_xlabel("Distance thresholds")
        axs[4].set_ylabel("Davies-Bouldin\n(minimise)")

        axs[5].plot(thr_vals, cluster_out["chi"])
        axs[5].axvline(opt_thr_info["opt_thr"].values[0], color="r")
        axs[5].grid(True)
        axs[5].set_xlim([thr_vals[0], thr_vals[-1]])
        axs[5].set_xlabel("Distance thresholds")
        axs[5].set_ylabel("Calinski-Harabasz\n(maximise)")

        plt.tight_layout()
        plt.show()

    return opt_thr_info, cluster_out

pairwise

pairwise(iterable: Iterable) -> Iterable[Tuple]

pairwise(iterable) --> AB BC CD DE EF FG

Returns an iterable of tuples containing adjacent pairs of elements from the input iterable.

Parameters:

Name Type Description Default
iterable Iterable

The input iterable.

required

Yields:

Type Description
Iterable[Tuple]

A tuple containing adjacent pairs of elements from the input iterable.

Example

list(pairwise('ABCDEFG')) [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')]

Source code in motor_unit_toolbox/muap_comp.py
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
def pairwise(iterable: Iterable) -> Iterable[Tuple]:
    """
    pairwise(iterable) --> AB BC CD DE EF FG

    Returns an iterable of tuples containing adjacent pairs of elements from the input iterable.

    Args:
        iterable: The input iterable.

    Yields:
        A tuple containing adjacent pairs of elements from the input iterable.

    Example:
        >>> list(pairwise('ABCDEFG'))
        [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')]
    """
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b, strict=False)

mark_groups

mark_groups(rows: List[int], cols: List[int], idx_i: List[int], idx_j: List[int], curr_dist_mat: ndarray, trial_labels: List[int], out_dict: Dict, graph: DiGraph) -> Tuple[Dict, nx.DiGraph]

Mark groups based on the given rows and columns.

Parameters:

Name Type Description Default
rows List[int]

The list of row indices.

required
cols List[int]

The list of column indices.

required
idx_i List[int]

The list of unit indices for rows.

required
idx_j List[int]

The list of unit indices for columns.

required
curr_dist_mat ndarray

The current distance matrix.

required
trial_labels List[int]

The list of trial labels.

required
out_dict Dict

The output dictionary containing the following keys: - "unit1" (List[int]): The list of unit indices from the first group. - "unit2" (List[int]): The list of unit indices from the second group. - "label1" (List[int]): The list of trial labels for the units in the first group. - "label2" (List[int]): The list of trial labels for the units in the second group. - "link_dist" (List[float]): The list of linkage distances between the units. - "no_link_dist" (List[List[float]]): The list of distances between each unit and all other units in the same group.

required
graph DiGraph

The directed graph.

required

Returns:

Type Description
Tuple[Dict, DiGraph]

Tuple[Dict, nx.DiGraph]: The updated output dictionary and graph.

Source code in motor_unit_toolbox/muap_comp.py
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
def mark_groups(
    rows: List[int],
    cols: List[int],
    idx_i: List[int],
    idx_j: List[int],
    curr_dist_mat: np.ndarray,
    trial_labels: List[int],
    out_dict: Dict,
    graph: nx.DiGraph
) -> Tuple[Dict, nx.DiGraph]:
    """
    Mark groups based on the given rows and columns.

    Args:
        rows (List[int]): The list of row indices.
        cols (List[int]): The list of column indices.
        idx_i (List[int]): The list of unit indices for rows.
        idx_j (List[int]): The list of unit indices for columns.
        curr_dist_mat (np.ndarray): The current distance matrix.
        trial_labels (List[int]): The list of trial labels.
        out_dict (Dict): The output dictionary containing the following keys:
            - "unit1" (List[int]): The list of unit indices from the first group.
            - "unit2" (List[int]): The list of unit indices from the second group.
            - "label1" (List[int]): The list of trial labels for the units in the
                first group.
            - "label2" (List[int]): The list of trial labels for the units in the
                second group.
            - "link_dist" (List[float]): The list of linkage distances between the
                units.
            - "no_link_dist" (List[List[float]]): The list of distances between
                each unit and all other units in the same group.
        graph (nx.DiGraph): The directed graph.

    Returns:
        Tuple[Dict, nx.DiGraph]: The updated output dictionary and graph.
    """

    if len(rows) < 1 or len(cols) < 1:
        return out_dict, graph

    for row, col in zip(rows, cols, strict=True):
        #  Get dist_mat values
        row_list, col_list = list(range(len(idx_i))), list(range(len(idx_j)))
        row_list.remove(row)
        col_list.remove(col)
        no_link_dist = np.concatenate(
            (curr_dist_mat[row_list, col], curr_dist_mat[row, col_list])
        )

        #  Update output
        out_dict['unit1'].append(idx_i[row])
        out_dict['unit2'].append(idx_j[col])
        out_dict['label1'].append(trial_labels[idx_i[row]])
        out_dict['label2'].append(trial_labels[idx_j[col]])
        out_dict['link_dist'].append(curr_dist_mat[row, col])
        out_dict['no_link_dist'].append(no_link_dist.tolist())

        # Update graph
        graph.add_edge(idx_i[row], idx_j[col], weight=curr_dist_mat[row, col])

    return out_dict, graph

generate_group_sets

generate_group_sets(graph: DiGraph) -> List[List[int]]

Generate group sets based on the given directed graph.

Parameters:

Name Type Description Default
graph DiGraph

A directed graph representing the connections between units.

required

Returns:

Type Description
List

A list of group sets, where each group set is a list of unit indices.

Example

graph = nx.DiGraph() graph.add_edge(1, 2) graph.add_edge(2, 3) graph.add_edge(3, 4) generate_group_sets(graph) [[1, 2, 3, 4]]

Source code in motor_unit_toolbox/muap_comp.py
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
def generate_group_sets(graph: nx.DiGraph) -> List[List[int]]:
    """
    Generate group sets based on the given directed graph.

    Args:
        graph (nx.DiGraph): A directed graph representing the connections between
            units.

    Returns:
        (List): A list of group sets, where each group set is a list of unit indices.

    Example:
        >>> graph = nx.DiGraph()
        >>> graph.add_edge(1, 2)
        >>> graph.add_edge(2, 3)
        >>> graph.add_edge(3, 4)
        >>> generate_group_sets(graph)
        [[1, 2, 3, 4]]
    """

    # Get all possible sources
    possible_sources = [node for node, in_degree in graph.in_degree() if in_degree == 0]

    #  Initialise group sets
    group_sets = []
    for source in possible_sources:
        #  Get successors
        curr_successor = list(graph.successors(source))

        #  If there are no successors, just add the source
        if len(curr_successor) < 1:
            group_sets.append([source])
            continue

        #  While the are successors add them to the path
        path = [source, curr_successor[0]]
        while list(graph.successors(curr_successor[0])):
            curr_successor = list(graph.successors(curr_successor[0]))
            path.append(curr_successor[0])
        #  Append path to set
        group_sets.append(path)

    # Sort by size
    group_counts = list(map(len, group_sets))
    idxs = np.argsort(group_counts)[::-1]

    return [group_sets[i] for i in idxs]

generate_group_labels

generate_group_labels(group_sets: List[List[int]]) -> List[int]

Generate group labels based on the given group sets.

Parameters:

Name Type Description Default
group_sets List

A list of group sets, where each group set is a list of unit indices. Unit indices must be 0-based and cover every unit (0 to n_units - 1), as produced by generate_group_sets.

required

Returns:

Type Description
List

A list of group labels (starting at 1), where each label corresponds to a unit index.

Example

generate_group_labels([[0, 2, 3], [1]]) [1, 2, 1, 1]

Source code in motor_unit_toolbox/muap_comp.py
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
def generate_group_labels(group_sets: List[List[int]]) -> List[int]:
    """
    Generate group labels based on the given group sets.

    Args:
        group_sets (List): A list of group sets, where each group set is a list of
            unit indices. Unit indices must be 0-based and cover every unit
            (0 to n_units - 1), as produced by generate_group_sets.

    Returns:
        (List): A list of group labels (starting at 1), where each label
            corresponds to a unit index.

    Example:
        >>> generate_group_labels([[0, 2, 3], [1]])
        [1, 2, 1, 1]
    """
    units = len(np.concatenate(group_sets))
    groups = np.zeros(units).astype(int)
    for i, path in enumerate(group_sets):
        groups[path] = i + 1
    tracker = np.amax(groups) + 1
    idxs = np.nonzero(groups == 0)[0]
    for i, idx in enumerate(idxs):
        groups[idx] = tracker + i
    return groups

apply_hungarian_algorithm

apply_hungarian_algorithm(curr_dist_mat: ndarray, dist_thr: float) -> Tuple[np.ndarray, np.ndarray]

Apply the Hungarian algorithm for association based on the given distance matrix.

Parameters:

Name Type Description Default
curr_dist_mat ndarray

The distance matrix.

required
dist_thr float

The distance threshold.

required

Returns:

Type Description
Tuple

containing the rows and columns that meet the distance threshold.

Example

apply_hungarian_algorithm(curr_dist_mat, dist_thr) (array([0, 1, 2]), array([0, 1, 2]))

Source code in motor_unit_toolbox/muap_comp.py
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
def apply_hungarian_algorithm(
    curr_dist_mat: np.ndarray,
    dist_thr: float
) -> Tuple[np.ndarray, np.ndarray]:
    """
    Apply the Hungarian algorithm for association based on the given distance matrix.

    Args:
        curr_dist_mat (np.ndarray): The distance matrix.
        dist_thr (float): The distance threshold.

    Returns:
        (Tuple): containing the rows and columns that meet the distance threshold.

    Example:
        >>> apply_hungarian_algorithm(curr_dist_mat, dist_thr)
        (array([0, 1, 2]), array([0, 1, 2]))
    """
    rows, cols = optimize.linear_sum_assignment(curr_dist_mat)

    # Keep only the rows and cols that meet the threshold
    valid_idxs = curr_dist_mat[rows, cols] <= dist_thr
    rows, cols = rows[valid_idxs], cols[valid_idxs]
    return rows, cols
apply_sorted_grid_search(curr_dist_mat: ndarray, dist_thr: float) -> Tuple[List[int], List[int]]

Apply a sorted grid search to find possible matches for each row in the distance matrix.

Parameters:

Name Type Description Default
curr_dist_mat ndarray

The distance matrix.

required
dist_thr float

The distance threshold.

required

Returns:

Type Description
Tuple

containing the rows and columns that meet the distance threshold.

Example

apply_sorted_grid_search(curr_dist_mat, dist_thr) ([0, 1, 2], [0, 1, 2])

Source code in motor_unit_toolbox/muap_comp.py
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
def apply_sorted_grid_search(
        curr_dist_mat: np.ndarray,
        dist_thr: float,
) -> Tuple[List[int], List[int]]:
    """
    Apply a sorted grid search to find possible matches for each row in the
    distance matrix.

    Args:
        curr_dist_mat (np.ndarray): The distance matrix.
        dist_thr (float): The distance threshold.

    Returns:
        (Tuple): containing the rows and columns that meet the distance threshold.

    Example:
        >>> apply_sorted_grid_search(curr_dist_mat, dist_thr)
        ([0, 1, 2], [0, 1, 2])
    """

    #  Search for possible matches for each row
    rows, cols = [], []
    for i in range(curr_dist_mat.shape[0]):

        # Get the minimum distance for that row
        min_dist_i = np.min(curr_dist_mat[i, :])
        if min_dist_i > dist_thr:
            continue

        # If it is a valid hit, make sure it is also the best assignment for the column
        j = np.argmin(curr_dist_mat[i, :])
        if min_dist_i > np.min(curr_dist_mat[:, j]):
            continue

        #  If it is, then mark it as a match
        rows.append(i)
        cols.append(j)

    return rows, cols

assign_muaps_across_seq_trials

assign_muaps_across_seq_trials(dist_mat: ndarray, trial_labels: ndarray, trial_set: List[int], assign_method: Literal['hungarian', 'grid-search'] = 'grid-search', dist_thr: Optional[float] = 0.3) -> Tuple[Dict[str, List], nx.DiGraph, np.ndarray]

Assign MUAPs across sequential trials based on the given distance matrix.

Parameters:

Name Type Description Default
dist_mat ndarray

The distance matrix.

required
trial_labels ndarray

All trial labels.

required
trial_set List[int]

The trial labels present in the distance matrix.

required
assign_method str

The method to use for assignment: "hungarian" or "grid-search". Defaults to "grid-search".

'grid-search'
dist_thr float

The distance threshold. Defaults to 0.3.

0.3

Returns:

Type Description
Tuple[Dict[str, List], DiGraph, ndarray]

Tuple[Dict[str, List], nx.DiGraph, np.ndarray]: A tuple containing the output dictionary, the graph, and the updated distance matrix.

Source code in motor_unit_toolbox/muap_comp.py
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
def assign_muaps_across_seq_trials(
    dist_mat: np.ndarray,
    trial_labels: np.ndarray,
    trial_set: List[int],
    assign_method: Literal["hungarian", "grid-search"] = "grid-search",
    dist_thr: Optional[float] = 0.3
) -> Tuple[Dict[str, List], nx.DiGraph, np.ndarray]:
    """
    Assign MUAPs across sequential trials based on the given distance matrix.

    Args:
        dist_mat (np.ndarray): The distance matrix.
        trial_labels (np.ndarray): All trial labels.
        trial_set (List[int]): The trial labels present in the distance matrix.
        assign_method (str, optional): The method to use for assignment:
            "hungarian" or "grid-search". Defaults to "grid-search".
        dist_thr (float, optional): The distance threshold. Defaults to 0.3.

    Returns:
        Tuple[Dict[str, List], nx.DiGraph, np.ndarray]: A tuple containing the
            output dictionary, the graph, and the updated distance matrix.
    """

    #  Initialise outputs
    keys = ["unit1", "unit2", "label1", "label2", "group", "link_dist", "no_link_dist"]
    out_dict = edict({key: [] for key in keys})

    # Generate nodes
    subset_sizes = [np.sum(trial_labels == trial) for trial in trial_set]
    extents = nx.utils.pairwise(itertools.accumulate([0,] + subset_sizes))
    layers = [range(start, end) for start, end in extents]

    #  Generate graph
    graph = nx.DiGraph()
    for trial, layer in zip(trial_set, layers, strict=True):
        graph.add_nodes_from(layer, layer=trial)

    # Find adjacent neighbours
    # ------------------------
    for trial_i, trial_j in pairwise(trial_set):

        # Get indexes of the trials
        idx_i = np.nonzero(trial_labels == trial_i)[0]
        idx_j = np.nonzero(trial_labels == trial_j)[0]

        #  If there are no units in any of the trials, skip
        if len(idx_i) < 1 or len(idx_j) < 1:
            continue

        #  Assign units
        curr_dist_mat = dist_mat[np.ix_(idx_i, idx_j)]
        if assign_method == "hungarian":
            rows, cols = apply_hungarian_algorithm(curr_dist_mat, dist_thr)
        elif assign_method == "grid-search":
            rows, cols = apply_sorted_grid_search(curr_dist_mat, dist_thr)

        #  If there are no valid matches, all units are unique
        if len(rows) < 1:
            continue

        #  Mark the groups
        out_dict, graph = mark_groups(
            rows, cols, idx_i, idx_j, curr_dist_mat, trial_labels, out_dict, graph
        )

        # Once a trial has been explored, mask it
        dist_mat[np.ix_(idx_i, idx_j)] = 2

    return out_dict, graph, dist_mat

assign_muaps_all_trials

assign_muaps_all_trials(muaps: ndarray, trial_labels: ndarray, trial_set: List[int], assign_method: Literal['hungarian', 'grid-search'] = 'hungarian', dist_metric: Literal['corr', 'cosine', 'nmse', 'nfd'] = 'nmse', dist_thr: float = 0.3, sel_chs_method: Literal['iqr', 'iqr_ptp', 'max_abs', 'ptp'] = 'iqr') -> Tuple[List[int], List[List[int]], pd.DataFrame, nx.DiGraph]

Assign MUAPs across all trials based on the given distance matrix.

Parameters:

Name Type Description Default
muaps ndarray

MUAPs with shape (units, ch_rows, ch_cols, samples).

required
trial_labels ndarray

All trial labels.

required
trial_set List[int]

The trial labels of the MUAPs.

required
assign_method str

The method to use for assignment: "hungarian" or "grid-search". Defaults to "hungarian".

'hungarian'
dist_metric str

The distance metric: "corr", "cosine", "nmse" or "nfd". Defaults to "nmse".

'nmse'
dist_thr float

The distance threshold. Defaults to 0.3.

0.3
sel_chs_method str

The method to use for selecting channels: "iqr", "iqr_ptp", "max_abs" or "ptp". Defaults to "iqr".

'iqr'

Returns:

Type Description
Tuple[List[int], List[List[int]], DataFrame, DiGraph]

Tuple[List[int], List[List[int]], pd.DataFrame, nx.DiGraph]: A tuple containing the group labels, group sets, link information dataframe, and the graph.

Source code in motor_unit_toolbox/muap_comp.py
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
def assign_muaps_all_trials(
    muaps: np.ndarray,
    trial_labels: np.ndarray,
    trial_set: List[int],
    assign_method: Literal["hungarian", "grid-search"] = "hungarian",
    dist_metric: Literal["corr", "cosine", "nmse", "nfd"] = "nmse",
    dist_thr: float = 0.3,
    sel_chs_method: Literal["iqr", "iqr_ptp", "max_abs", "ptp"] = "iqr",
) -> Tuple[List[int], List[List[int]], pd.DataFrame, nx.DiGraph]:
    """
    Assign MUAPs across all trials based on the given distance matrix.

    Args:
        muaps (np.ndarray): MUAPs with shape (units, ch_rows, ch_cols, samples).
        trial_labels (np.ndarray): All trial labels.
        trial_set (List[int]): The trial labels of the MUAPs.
        assign_method (str, optional): The method to use for assignment:
            "hungarian" or "grid-search". Defaults to "hungarian".
        dist_metric (str, optional): The distance metric: "corr", "cosine", "nmse" or "nfd".
            Defaults to "nmse".
        dist_thr (float, optional): The distance threshold. Defaults to 0.3.
        sel_chs_method (str, optional): The method to use for selecting
            channels: "iqr", "iqr_ptp", "max_abs" or "ptp". Defaults to "iqr".

    Returns:
        Tuple[List[int], List[List[int]], pd.DataFrame, nx.DiGraph]: A tuple
            containing the group labels, group sets, link information dataframe,
            and the graph.
    """

    #  Compute distances between muaps
    #  -------------------------------
    dist_mat, _ = compute_all_muaps_dist(
        muaps, sel_chs_method=sel_chs_method, dist_metric=dist_metric
    )

    # Discard connections between the same trial
    idx_tril = np.tril_indices(dist_mat.shape[0])
    dist_mat[idx_tril] = 2
    for trial in np.unique(trial_labels):
        trial_idxs = np.nonzero(trial_labels == trial)[0]
        dist_mat[np.ix_(trial_idxs, trial_idxs)] = 2

    # fig, axs = plt.subplots(1,3, figsize=(12,4), layout='constrained', dpi=200)
    # g = sns.heatmap(dist_mat, annot=False, ax=axs[0])
    # g.set(title='Initial')

    out_dict, graph, dist_mat = assign_muaps_across_seq_trials(
        dist_mat, trial_labels, trial_set, assign_method, dist_thr
    )

    # g = sns.heatmap(dist_mat, annot=False, ax=axs[1])
    # g.set(title='After adjacent')

    # Find distant neighbours
    # -----------------------
    #  Find distant hits
    rows, cols = np.nonzero(dist_mat <= dist_thr)
    distant_dists = dist_mat[rows, cols]

    #  Sort based on distant metric
    sort_idxs = np.argsort(distant_dists)
    rows, cols = rows[sort_idxs], cols[sort_idxs]

    # Get the unique trial combinations to perform the hungarian algorithm
    distant_trials = [
        (trial_labels[row], trial_labels[col]) for row, col in zip(rows, cols, strict=True)
    ]
    trial_comb = list(dict.fromkeys(distant_trials))

    #  Apply hungarian algorithm
    for trial_i, trial_j in trial_comb:

        # Get indexes of the trials
        idx_i = np.nonzero(trial_labels == trial_i)[0]
        idx_j = np.nonzero(trial_labels == trial_j)[0]

        #  Select source units within trial_i (no output edges)
        idx_i = [idx for idx in idx_i if graph.out_degree(idx) == 0]
        #  Select target units within trial_j (no input edges)
        idx_j = [idx for idx in idx_j if graph.in_degree(idx) == 0]

        if len(idx_i) < 1 or len(idx_j) < 1:
            # Once a trial has been explored, mask it
            dist_mat[np.ix_(idx_i, idx_j)] = 2
            continue

        #  Assign units
        curr_dist_mat = dist_mat[np.ix_(idx_i, idx_j)]
        if assign_method == "hungarian":
            rows, cols = apply_hungarian_algorithm(curr_dist_mat, dist_thr)
        elif assign_method == "grid-search":
            rows, cols = apply_sorted_grid_search(curr_dist_mat, dist_thr)

        #  If there are no valid matches, all units are unique
        if len(rows) < 1:
            continue

        #  Mark the groups
        out_dict, graph = mark_groups(
            rows, cols, idx_i, idx_j, curr_dist_mat, trial_labels, out_dict, graph
        )

        # Once a trial has been explored, mask it
        dist_mat[np.ix_(idx_i, idx_j)] = 2

    # g = sns.heatmap(dist_mat, annot=False, ax=axs[2])
    # g.set(title='After distant')
    # plt.show()

    #  Generate group sets and labels
    group_sets = generate_group_sets(graph)
    group_labels = generate_group_labels(group_sets)

    #  Fill groups in out_dict
    for unit in out_dict.unit1:
        out_dict.group.append(group_labels[unit])
    df_link_info = pd.DataFrame(out_dict)

    return group_labels, group_sets, df_link_info, graph