utils.py 45.9 KB
Newer Older
lucas_miranda's avatar
lucas_miranda committed
1
# @author lucasmiranda42
2
3
4
5
6
7
8
9
# encoding: utf-8
# module deepof

"""

Functions and general utilities for the deepof package. See documentation for details

"""
10
11
12
13

import cv2
import matplotlib.pyplot as plt
import multiprocessing
14
import networkx as nx
15
import numpy as np
lucas_miranda's avatar
lucas_miranda committed
16
import os
17
import pandas as pd
18
import regex as re
19
import seaborn as sns
20
from copy import deepcopy
21
from itertools import combinations, product
22
23
from joblib import Parallel, delayed
from scipy import spatial
24
from scipy import stats
25
from sklearn import mixture
26
from tqdm import tqdm
lucas_miranda's avatar
lucas_miranda committed
27
from typing import Tuple, Any, List, Union, NewType
28
29
30
31

# DEFINE CUSTOM ANNOTATED TYPES #


32
Coordinates = NewType("Coordinates", Any)
33
34


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# CONNECTIVITY FOR DLC MODELS


def connect_mouse_topview(animal_id=None) -> nx.Graph:
    """Creates a nx.Graph object with the connectivity of the bodyparts in the
    DLC topview model for a single mouse. Used later for angle computing, among others

        Parameters:
            - animal_id (str): if more than one animal is tagged,
            specify the animal identyfier as a string

        Returns:
            - connectivity (nx.Graph)"""

    connectivity = {
        "Nose": ["Left_ear", "Right_ear", "Spine_1"],
        "Left_ear": ["Right_ear", "Spine_1"],
        "Right_ear": ["Spine_1"],
        "Spine_1": ["Center", "Left_fhip", "Right_fhip"],
        "Center": ["Left_fhip", "Right_fhip", "Spine_2", "Left_bhip", "Right_bhip"],
        "Spine_2": ["Left_bhip", "Right_bhip", "Tail_base"],
        "Tail_base": ["Tail_1", "Left_bhip", "Right_bhip"],
        "Tail_1": ["Tail_2"],
        "Tail_2": ["Tail_tip"],
    }

    connectivity = nx.Graph(connectivity)

    if animal_id:
        mapping = {
            node: "{}_{}".format(animal_id, node) for node in connectivity.nodes()
        }
        nx.relabel_nodes(connectivity, mapping, copy=False)

    return connectivity


72
# QUALITY CONTROL AND PREPROCESSING #
73

74

lucas_miranda's avatar
lucas_miranda committed
75
76
77
78
79
80
81
82
83
84
def likelihood_qc(dframe: pd.DataFrame, threshold: float = 0.9) -> np.array:
    """Returns a DataFrame filtered dataframe, keeping only the rows entirely above the threshold.

        Parameters:
            - dframe (pandas.DataFrame): DeepLabCut output, with positions over time and associated likelihhod
            - threshold (float): minimum acceptable confidence

        Returns:
            - filt_mask (np.array): mask on the rows of dframe"""

85
86
    Likes = np.array([dframe[i]["likelihood"] for i in list(dframe.columns.levels[0])])
    Likes = np.nan_to_num(Likes, nan=1.0)
lucas_miranda's avatar
lucas_miranda committed
87
88
89
    filt_mask = np.all(Likes > threshold, axis=0)

    return filt_mask
90
91


92
93
94
95
96
97
98
99
100
def bp2polar(tab: pd.DataFrame) -> pd.DataFrame:
    """Returns the DataFrame in polar coordinates.

        Parameters:
            - tab (pandas.DataFrame):Table with cartesian coordinates

        Returns:
            - polar (pandas.DataFrame): Equivalent to input, but with values in polar coordinates"""

101
102
103
104
105
106
107
    tab_ = np.array(tab)
    complex_ = tab_[:, 0] + 1j * tab_[:, 1]
    polar = pd.DataFrame(np.array([abs(complex_), np.angle(complex_)]).T)
    polar.rename(columns={0: "rho", 1: "phi"}, inplace=True)
    return polar


108
109
110
111
112
113
114
115
116
def tab2polar(cartesian_df: pd.DataFrame) -> pd.DataFrame:
    """Returns a pandas.DataFrame in which all the coordinates are polar.

        Parameters:
            - cartesian_df (pandas.DataFrame):DataFrame containing tables with cartesian coordinates

        Returns:
            - result (pandas.DataFrame): Equivalent to input, but with values in polar coordinates"""

117
    result = []
118
119
    for df in list(cartesian_df.columns.levels[0]):
        result.append(bp2polar(cartesian_df[df]))
120
121
    result = pd.concat(result, axis=1)
    idx = pd.MultiIndex.from_product(
122
123
        [list(cartesian_df.columns.levels[0]), ["rho", "phi"]],
        names=["bodyparts", "coords"],
124
125
126
127
128
    )
    result.columns = idx
    return result


129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def compute_dist(
    pair_array: np.array, arena_abs: int = 1, arena_rel: int = 1
) -> pd.DataFrame:
    """Returns a pandas.DataFrame with the scaled distances between a pair of body parts.

        Parameters:
            - pair_array (numpy.array): np.array of shape N * 4 containing X,y positions
            over time for a given pair of body parts
            - arena_abs (int): diameter of the real arena in cm
            - arena_rel (int): diameter of the captured arena in pixels

        Returns:
            - result (pd.DataFrame): pandas.DataFrame with the
            absolute distances between a pair of body parts"""

lucas_miranda's avatar
lucas_miranda committed
144
145
    lim = 2 if pair_array.shape[1] == 4 else 1
    a, b = pair_array[:, :lim], pair_array[:, lim:]
146
    ab = a - b
lucas_miranda's avatar
lucas_miranda committed
147

148
    dist = np.sqrt(np.einsum("...i,...i", ab, ab))
149
150
151
    return pd.DataFrame(dist * arena_abs / arena_rel)


152
153
154
155
156
157
158
159
160
161
def bpart_distance(
    dataframe: pd.DataFrame, arena_abs: int = 1, arena_rel: int = 1
) -> pd.DataFrame:
    """Returns a pandas.DataFrame with the scaled distances between all pairs of body parts.

        Parameters:
            - dataframe (pandas.DataFrame): pd.DataFrame of shape N*(2*bp) containing X,y positions
        over time for a given set of bp body parts
            - arena_abs (int): diameter of the real arena in cm
            - arena_rel (int): diameter of the captured arena in pixels
162

163
164
165
166
167
        Returns:
            - result (pd.DataFrame): pandas.DataFrame with the
            absolute distances between all pairs of body parts"""

    indexes = combinations(dataframe.columns.levels[0], 2)
168
169
170
171
172
173
174
    dists = []
    for idx in indexes:
        dist = compute_dist(np.array(dataframe.loc[:, list(idx)]), arena_abs, arena_rel)
        dist.columns = [idx]
        dists.append(dist)

    return pd.concat(dists, axis=1)
175
176


177
178
179
180
181
182
183
def angle(a: np.array, b: np.array, c: np.array) -> np.array:
    """Returns a numpy.array with the angles between the provided instances.

        Parameters:
            - a (2D np.array): positions over time for a bodypart
            - b (2D np.array): positions over time for a bodypart
            - c (2D np.array): positions over time for a bodypart
lucas_miranda's avatar
lucas_miranda committed
184

185
186
187
        Returns:
            - ang (1D np.array): angles between the three-point-instances"""

lucas_miranda's avatar
lucas_miranda committed
188
189
190
    ba = a - b
    bc = c - b

191
    cosine_angle = np.einsum("...i,...i", ba, bc) / (
lucas_miranda's avatar
lucas_miranda committed
192
193
        np.linalg.norm(ba, axis=1) * np.linalg.norm(bc, axis=1)
    )
194
195
196
197
198
199
200
    ang = np.arccos(cosine_angle)

    return ang


def angle_trio(bpart_array: np.array) -> np.array:
    """Returns a numpy.array with all three possible angles between the provided instances.
lucas_miranda's avatar
lucas_miranda committed
201

202
203
        Parameters:
            - bpart_array (2D numpy.array): positions over time for a bodypart
lucas_miranda's avatar
lucas_miranda committed
204

205
206
        Returns:
            - ang_trio (2D numpy.array): all-three angles between the three-point-instances"""
lucas_miranda's avatar
lucas_miranda committed
207

208
209
    a, b, c = bpart_array
    ang_trio = np.array([angle(a, b, c), angle(a, c, b), angle(b, a, c)])
lucas_miranda's avatar
lucas_miranda committed
210

211
    return ang_trio
lucas_miranda's avatar
lucas_miranda committed
212
213


214
215
216
217
def rotate(
    p: np.array, angles: np.array, origin: np.array = np.array([0, 0])
) -> np.array:
    """Returns a numpy.array with the initial values rotated by angles radians
lucas_miranda's avatar
lucas_miranda committed
218

219
220
221
222
223
224
225
        Parameters:
            - p (2D numpy.array): array containing positions of bodyparts over time
            - angles (2D numpy.array): set of angles (in radians) to rotate p with
            - origin (2D numpy.array): rotation axis (zero vector by default)

        Returns:
            - rotated (2D numpy.array): rotated positions over time"""
lucas_miranda's avatar
lucas_miranda committed
226

227
228
229
230
231
    R = np.array([[np.cos(angles), -np.sin(angles)], [np.sin(angles), np.cos(angles)]])

    o = np.atleast_2d(origin)
    p = np.atleast_2d(p)

232
233
234
235
    rotated = np.squeeze((R @ (p.T - o.T) + o.T).T)

    return rotated

236

237
238
239
def align_trajectories(data: np.array, mode: str = "all") -> np.array:
    """Returns a numpy.array with the positions rotated in a way that the center (0 vector)
    and the body part in the first column of data are aligned with the y axis.
240

241
242
243
244
245
        Parameters:
            - data (3D numpy.array): array containing positions of body parts over time, where
            shape is N (sliding window instances) * m (sliding window size) * l (features)
            - mode (string): specifies if *all* instances of each sliding window get
            aligned, or only the *center*
246

247
248
        Returns:
            - aligned_trajs (2D np.array): aligned positions over time"""
249

lucas_miranda's avatar
lucas_miranda committed
250
251
    print(data.shape, mode)

252
    angles = np.zeros(data.shape[0])
253
    data = deepcopy(data)
254
    dshape = data.shape
255

256
257
258
259
    if mode == "center":
        center_time = (data.shape[1] - 1) // 2
        angles = np.arctan2(data[:, center_time, 0], data[:, center_time, 1])
    elif mode == "all":
lucas_miranda's avatar
lucas_miranda committed
260
        data = data.reshape(-1, dshape[-1], order="C")
261
        angles = np.arctan2(data[:, 0], data[:, 1])
lucas_miranda's avatar
lucas_miranda committed
262
263
264
    elif mode == "none":
        data = data.reshape(-1, dshape[-1], order="C")
        angles = np.zeros(data.shape[0])
265
266
267
268
269

    aligned_trajs = np.zeros(data.shape)

    for frame in range(data.shape[0]):
        aligned_trajs[frame] = rotate(
lucas_miranda's avatar
lucas_miranda committed
270
271
            data[frame].reshape([-1, 2], order="C"), angles[frame],
        ).reshape(data.shape[1:], order="C")
272

lucas_miranda's avatar
lucas_miranda committed
273
274
    if mode == "all" or mode == "none":
        aligned_trajs = aligned_trajs.reshape(dshape, order="C")
275

276
277
278
    return aligned_trajs


279
280
281
282
283
284
285
286
287
def smooth_boolean_array(a: np.array) -> np.array:
    """Returns a boolean array in which isolated appearances of a feature are smoothened

        Parameters:
            - a (1D numpy.array): boolean instances

        Returns:
            - a (1D numpy.array): smoothened boolean instances"""

288
289
290
291
292
293
    for i in range(1, len(a) - 1):
        if a[i - 1] == a[i + 1]:
            a[i] = a[i - 1]
    return a == 1


294
295
296
def rolling_window(a: np.array, window_size: int, window_step: int) -> np.array:
    """Returns a 3D numpy.array with a sliding-window extra dimension

297
298
        Parameters:
            - a (2D np.array): N (instances) * m (features) shape
299

300
301
302
        Returns:
            - rolled_a (3D np.array):
            N (sliding window instances) * l (sliding window size) * m (features)"""
303

304
305
    shape = (a.shape[0] - window_size + 1, window_size) + a.shape[1:]
    strides = (a.strides[0],) + a.strides
306
307
    rolled_a = np.lib.stride_tricks.as_strided(
        a, shape=shape, strides=strides, writeable=True
308
    )[::window_step]
309
    return rolled_a
310

311

312
313
314
def smooth_mult_trajectory(series: np.array, alpha: float = 0.15) -> np.array:
    """Returns a smooths a trajectory using exponentially weighted averages

315
316
        Parameters:
            - series (numpy.array): 1D trajectory array with N (instances) - alpha (float): 0 <= alpha <= 1;
317
318
            indicates the inverse weight assigned to previous observations. Higher (alpha~1) indicates less smoothing;
            lower indicates more (alpha~0)
319
320
321

        Returns:
            - smoothed_series (np.array): smoothed version of the input, with equal shape"""
322
323
324
325
326

    result = [series[0]]
    for n in range(len(series)):
        result.append(alpha * series[n] + (1 - alpha) * result[n - 1])

327
328
329
    smoothed_series = np.array(result)

    return smoothed_series
330

lucas_miranda's avatar
lucas_miranda committed
331
332

# BEHAVIOUR RECOGNITION FUNCTIONS #
333
334


335
def close_single_contact(
336
337
338
339
340
341
    pos_dframe: pd.DataFrame,
    left: str,
    right: str,
    tol: float,
    arena_abs: int,
    arena_rel: int,
342
343
) -> np.array:
    """Returns a boolean array that's True if the specified body parts are closer than tol.
344

345
346
347
348
349
        Parameters:
            - pos_dframe (pandas.DataFrame): DLC output as pandas.DataFrame; only applicable
            to two-animal experiments.
            - left (string): First member of the potential contact
            - right (string): Second member of the potential contact
350
351
352
            - tol (float): maximum distance for which a contact is reported
            - arena_abs (int): length in mm of the diameter of the real arena
            - arena_rel (int): length in pixels of the diameter of the arena in the video
353

354
355
356
        Returns:
            - contact_array (np.array): True if the distance between the two specified points
            is less than tol, False otherwise"""
357

358
359
360
    close_contact = (
        np.linalg.norm(pos_dframe[left] - pos_dframe[right], axis=1) * arena_abs
    ) / arena_rel < tol
361

362
    return close_contact
363
364


365
366
367
368
369
370
371
def close_double_contact(
    pos_dframe: pd.DataFrame,
    left1: str,
    left2: str,
    right1: str,
    right2: str,
    tol: float,
372
373
    arena_abs: int,
    arena_rel: int,
374
375
376
377
378
379
380
381
382
383
384
    rev: bool = False,
) -> np.array:
    """Returns a boolean array that's True if the specified body parts are closer than tol.

        Parameters:
            - pos_dframe (pandas.DataFrame): DLC output as pandas.DataFrame; only applicable
            to two-animal experiments.
            - left1 (string): First contact point of animal 1
            - left2 (string): Second contact point of animal 1
            - right1 (string): First contact point of animal 2
            - right2 (string): Second contact point of animal 2
385
386
387
388
            - tol (float): maximum distance for which a contact is reported
            - arena_abs (int): length in mm of the diameter of the real arena
            - arena_rel (int): length in pixels of the diameter of the arena in the video
            - rev (bool): reverses the default behaviour (nose2tail contact for both mice)
389
390
391
392
393
394
395

        Returns:
            - double_contact (np.array): True if the distance between the two specified points
            is less than tol, False otherwise"""

    if rev:
        double_contact = (
396
397
398
399
400
401
402
403
            (np.linalg.norm(pos_dframe[right1] - pos_dframe[left2], axis=1) * arena_abs)
            / arena_rel
            < tol
        ) & (
            (np.linalg.norm(pos_dframe[right2] - pos_dframe[left1], axis=1) * arena_abs)
            / arena_rel
            < tol
        )
404
405
406

    else:
        double_contact = (
407
408
409
410
411
412
413
414
            (np.linalg.norm(pos_dframe[right1] - pos_dframe[left1], axis=1) * arena_abs)
            / arena_rel
            < tol
        ) & (
            (np.linalg.norm(pos_dframe[right2] - pos_dframe[left2], axis=1) * arena_abs)
            / arena_rel
            < tol
        )
415
416

    return double_contact
417
418
419


def recognize_arena(
lucas_miranda's avatar
lucas_miranda committed
420
421
422
423
424
    videos: list,
    vid_index: int,
    path: str = ".",
    recoglimit: int = 1,
    arena_type: str = "circular",
425
) -> Tuple[np.array, int, int]:
lucas_miranda's avatar
lucas_miranda committed
426
427
428
    """Returns numpy.array with information about the arena recognised from the first frames
    of the video. WARNING: estimates won't be reliable if the camera moves along the video.

429
430
431
432
433
434
        Parameters:
            - videos (list): relative paths of the videos to analise
            - vid_index (int): element of videos to use
            - path (string): full path of the directory where the videos are
            - recoglimit (int): number of frames to use for position estimates
            - arena_type (string): arena type; must be one of ['circular']
lucas_miranda's avatar
lucas_miranda committed
435

436
437
        Returns:
            - arena (np.array): 1D-array containing information about the arena.
438
439
440
            "circular" (3-element-array) -> x-y position of the center and the radius
            - h (int): height of the video in pixels
            - w (int): width of the video in pixels"""
lucas_miranda's avatar
lucas_miranda committed
441
442

    cap = cv2.VideoCapture(os.path.join(path, videos[vid_index]))
443
444

    # Loop over the first frames in the video to get resolution and center of the arena
lucas_miranda's avatar
lucas_miranda committed
445
    arena, fnum, h, w = False, 0, None, None
446
447
448
449
450
451
452
453
454
455
456
457

    while cap.isOpened() and fnum < recoglimit:
        ret, frame = cap.read()
        # if frame is read correctly ret is True
        if not ret:
            print("Can't receive frame (stream end?). Exiting ...")
            break

        if arena_type == "circular":

            # Detect arena and extract positions
            arena = circular_arena_recognition(frame)[0]
458
            if h is None and w is None:
459
460
461
462
                h, w = frame.shape[0], frame.shape[1]

        fnum += 1

463
464
465
    cap.release()
    cv2.destroyAllWindows()

466
    return arena, h, w
467
468


469
470
def circular_arena_recognition(frame: np.array) -> np.array:
    """Returns x,y position of the center and the radius of the recognised arena
lucas_miranda's avatar
lucas_miranda committed
471

472
        Parameters:
473
            - frame (np.array): numpy.array representing an individual frame of a video
474

475
476
477
        Returns:
            - circles (np.array): 3-element-array containing x,y positions of the center
            of the arena, and a third value indicating the radius"""
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

    # Convert image to greyscale, threshold it, blur it and detect the biggest best fitting circle
    # using the Hough algorithm
    gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray_image, 50, 255, 0)
    frame = cv2.medianBlur(thresh, 9)
    circle = cv2.HoughCircles(
        frame,
        cv2.HOUGH_GRADIENT,
        1,
        300,
        param1=50,
        param2=10,
        minRadius=0,
        maxRadius=0,
    )

    circles = []

    if circle is not None:
        circle = np.uint16(np.around(circle[0]))
        circles.append(circle)

    return circles[0]


504
505
506
507
def climb_wall(
    arena_type: str, arena: np.array, pos_dict: pd.DataFrame, tol: float, nose: str
) -> np.array:
    """Returns True if the specified mouse is climbing the wall
lucas_miranda's avatar
lucas_miranda committed
508

509
510
511
512
513
514
515
516
517
518
519
520
521
        Parameters:
            - arena_type (str): arena type; must be one of ['circular']
            - arena (np.array): contains arena location and shape details
            - pos_dict (table_dict): position over time for all videos in a project
            - tol (float): minimum tolerance to report a hit
            - nose (str): indicates the name of the body part representing the nose of
            the selected animal

        Returns:
            - climbing (np.array): boolean array. True if selected animal
            is climbing the walls of the arena"""

    nose = pos_dict[nose]
522

523
524
525
526
527
528
    if arena_type == "circular":
        center = np.array(arena[:2])
        climbing = np.linalg.norm(nose - center, axis=1) > (arena[2] + tol)

    else:
        raise NotImplementedError("Supported values for arena_type are ['circular']")
529

530
    return climbing
531
532


lucas_miranda's avatar
lucas_miranda committed
533
def rolling_speed(
lucas_miranda's avatar
lucas_miranda committed
534
535
536
537
538
539
    dframe: pd.DatetimeIndex,
    window: int = 5,
    rounds: int = 10,
    deriv: int = 1,
    center: str = None,
    typ: str = "coords",
lucas_miranda's avatar
lucas_miranda committed
540
541
) -> pd.DataFrame:
    """Returns the average speed over n frames in pixels per frame
lucas_miranda's avatar
lucas_miranda committed
542

lucas_miranda's avatar
lucas_miranda committed
543
544
545
546
547
548
        Parameters:
            - dframe (pandas.DataFrame): position over time dataframe
            - pause (int):  frame-length of the averaging window
            - rounds (int): float rounding decimals
            - deriv (int): position derivative order; 1 for speed,
            2 for acceleration, 3 for jerk, etc
lucas_miranda's avatar
lucas_miranda committed
549
550
551
            - center (str): for internal usage only; solves an issue
            with pandas.MultiIndex that arises when centering frames
            to a specific body part
lucas_miranda's avatar
lucas_miranda committed
552

lucas_miranda's avatar
lucas_miranda committed
553
554
555
556
557
        Returns:
            - speeds (pd.DataFrame): containing 2D speeds for each body part
            in the original data or their consequent derivatives"""

    original_shape = dframe.shape
lucas_miranda's avatar
lucas_miranda committed
558
559
560
561
562
563
564
565
    if center:
        body_parts = [bp for bp in dframe.columns.levels[0] if bp != center]
    else:
        try:
            body_parts = dframe.columns.levels[0]
        except AttributeError:
            body_parts = dframe.columns

lucas_miranda's avatar
lucas_miranda committed
566
567
568
    speeds = pd.DataFrame

    for der in range(deriv):
lucas_miranda's avatar
lucas_miranda committed
569
570
571

        features = 2 if der == 0 and typ == "coords" else 1

lucas_miranda's avatar
lucas_miranda committed
572
573
        distances = np.concatenate(
            [
lucas_miranda's avatar
lucas_miranda committed
574
575
                np.array(dframe).reshape([-1, features], order="F"),
                np.array(dframe.shift()).reshape([-1, features], order="F"),
lucas_miranda's avatar
lucas_miranda committed
576
577
578
            ],
            axis=1,
        )
lucas_miranda's avatar
lucas_miranda committed
579

lucas_miranda's avatar
lucas_miranda committed
580
581
        distances = np.array(compute_dist(distances))
        distances = distances.reshape(
lucas_miranda's avatar
lucas_miranda committed
582
583
584
585
586
            [
                original_shape[0],
                (original_shape[1] // 2 if typ == "coords" else original_shape[1]),
            ],
            order="F",
lucas_miranda's avatar
lucas_miranda committed
587
588
589
590
        )
        distances = pd.DataFrame(distances, index=dframe.index)
        speeds = np.round(distances.rolling(window).mean(), rounds)
        speeds[np.isnan(speeds)] = 0.0
lucas_miranda's avatar
lucas_miranda committed
591

lucas_miranda's avatar
lucas_miranda committed
592
        dframe = speeds
lucas_miranda's avatar
lucas_miranda committed
593

lucas_miranda's avatar
lucas_miranda committed
594
    speeds.columns = body_parts
595
596
597
598

    return speeds


599
def huddle(
600
601
602
603
604
605
    pos_dframe: pd.DataFrame,
    speed_dframe: pd.DataFrame,
    tol_forward: float,
    tol_spine: float,
    tol_speed: float,
    animal_id: str = "",
606
) -> np.array:
lucas_miranda's avatar
lucas_miranda committed
607
608
    """Returns true when the mouse is huddling using simple rules. (!!!) Designed to
    work with deepof's default DLC mice models; not guaranteed to work otherwise.
609

lucas_miranda's avatar
lucas_miranda committed
610
        Parameters:
611
612
            - pos_dframe (pandas.DataFrame): position of body parts over time
            - speed_dframe (pandas.DataFrame): speed of body parts over time
lucas_miranda's avatar
lucas_miranda committed
613
614
615
616
            - tol_forward (float): Maximum tolerated distance between ears and
            forward limbs
            - tol_rear (float): Maximum tolerated average distance between spine
            body parts
617
            - tol_speed (float): Maximum tolerated speed for the center of the mouse
lucas_miranda's avatar
lucas_miranda committed
618

lucas_miranda's avatar
lucas_miranda committed
619
620
621
622
        Returns:
            hudd (np.array): True if the animal is huddling, False otherwise
        """

623
624
625
    if animal_id != "":
        animal_id += "_"

lucas_miranda's avatar
lucas_miranda committed
626
    forward = (
627
628
629
630
        np.linalg.norm(
            pos_dframe[animal_id + "Left_ear"] - pos_dframe[animal_id + "Left_fhip"],
            axis=1,
        )
lucas_miranda's avatar
lucas_miranda committed
631
632
        < tol_forward
    ) & (
633
634
635
636
        np.linalg.norm(
            pos_dframe[animal_id + "Right_ear"] - pos_dframe[animal_id + "Right_fhip"],
            axis=1,
        )
lucas_miranda's avatar
lucas_miranda committed
637
        < tol_forward
638
639
    )

640
641
642
643
644
645
    spine = [
        animal_id + "Spine_1",
        animal_id + "Center",
        animal_id + "Spine_2",
        animal_id + "Tail_base",
    ]
lucas_miranda's avatar
lucas_miranda committed
646
647
648
649
650
651
652
653
    spine_dists = []
    for comb in range(2):
        spine_dists.append(
            np.linalg.norm(
                pos_dframe[spine[comb]] - pos_dframe[spine[comb + 1]], axis=1
            )
        )
    spine = np.mean(spine_dists) < tol_spine
654
655
    speed = speed_dframe[animal_id + "Center"] < tol_speed
    hudd = forward & spine & speed
lucas_miranda's avatar
lucas_miranda committed
656
657
658

    return hudd

659

lucas_miranda's avatar
lucas_miranda committed
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
def following_path(
    distance_dframe: pd.DataFrame,
    position_dframe: pd.DataFrame,
    follower: str,
    followed: str,
    frames: int = 20,
    tol: float = 0,
) -> np.array:
    """For multi animal videos only. Returns True if 'follower' is closer than tol to the path that
    followed has walked over the last specified number of frames

        Parameters:
            - distance_dframe (pandas.DataFrame): distances between bodyparts; generated by the preprocess module
            - position_dframe (pandas.DataFrame): position of bodyparts; generated by the preprocess module
            - follower (str) identifier for the animal who's following
            - followed (str) identifier for the animal who's followed
            - frames (int) frames in which to track whether the process consistently occurs,
            - tol (float) Maximum distance for which True is returned

        Returns:
            - follow (np.array): boolean sequence, True if conditions are fulfilled, False otherwise"""
681
682

    # Check that follower is close enough to the path that followed has passed though in the last frames
lucas_miranda's avatar
lucas_miranda committed
683
684
685
    shift_dict = {
        i: position_dframe[followed + "_Tail_base"].shift(i) for i in range(frames)
    }
686
687
    dist_df = pd.DataFrame(
        {
lucas_miranda's avatar
lucas_miranda committed
688
689
690
            i: np.linalg.norm(
                position_dframe[follower + "_Nose"] - shift_dict[i], axis=1
            )
691
692
693
694
695
696
            for i in range(frames)
        }
    )

    # Check that the animals are oriented follower's nose -> followed's tail
    right_orient1 = (
lucas_miranda's avatar
lucas_miranda committed
697
698
699
700
        distance_dframe[tuple(sorted([follower + "_Nose", followed + "_Tail_base"]))]
        < distance_dframe[
            tuple(sorted([follower + "_Tail_base", followed + "_Tail_base"]))
        ]
701
702
703
    )

    right_orient2 = (
lucas_miranda's avatar
lucas_miranda committed
704
705
        distance_dframe[tuple(sorted([follower + "_Nose", followed + "_Tail_base"]))]
        < distance_dframe[tuple(sorted([follower + "_Nose", followed + "_Nose"]))]
706
707
    )

lucas_miranda's avatar
lucas_miranda committed
708
709
    follow = np.all(
        np.array([(dist_df.min(axis=1) < tol), right_orient1, right_orient2]), axis=0,
710
711
    )

lucas_miranda's avatar
lucas_miranda committed
712
713
    return follow

714

lucas_miranda's avatar
lucas_miranda committed
715
def single_behaviour_analysis(
716
717
718
719
720
721
722
723
    behaviour_name: str,
    treatment_dict: dict,
    behavioural_dict: dict,
    plot: int = 0,
    stat_tests: bool = True,
    save: str = None,
    ylim: float = None,
) -> list:
724
    """Given the name of the behaviour, a dictionary with the names of the groups to compare, and a dictionary
725
726
727
728
729
730
731
732
733
734
735
736
737
738
       with the actual tags, outputs a box plot and a series of significance tests amongst the groups

        Parameters:
            - behaviour_name (str): name of the behavioural trait to analize
            - treatment_dict (dict): dictionary containing video names as keys and experimental conditions as values
            - behavioural_dict (dict): tagged dictionary containing video names as keys and annotations as values
            - plot (int): Silent if 0; otherwise, indicates the dpi of the figure to plot
            - stat_tests (bool): performs FDR corrected Mann-U non-parametric tests among all groups if True
            - save (str): Saves the produced figure to the specified file
            - ylim (float): y-limit for the boxplot. Ignored if plot == False

        Returns:
            - beh_dict (dict): dictionary containing experimental conditions as keys and video names as values
            - stat_dict (dict): dictionary containing condition pairs as keys and stat results as values"""
739
740
741
742
743
744
745
746
747
748

    beh_dict = {condition: [] for condition in treatment_dict.keys()}

    for condition in beh_dict.keys():
        for ind in treatment_dict[condition]:
            beh_dict[condition].append(
                np.sum(behavioural_dict[ind][behaviour_name])
                / len(behavioural_dict[ind][behaviour_name])
            )

749
    return_list = [beh_dict]
750

751
    if plot > 0:
752

753
        fig, ax = plt.subplots(dpi=plot)
754

755
756
757
758
759
760
761
762
763
        sns.boxplot(
            list(beh_dict.keys()), list(beh_dict.values()), orient="vertical", ax=ax
        )

        ax.set_title("{} across groups".format(behaviour_name))
        ax.set_ylabel("Proportion of frames")

        if ylim is not None:
            ax.set_ylim(ylim)
764

765
        if save is not None:
766
767
            plt.savefig(save)

768
        return_list.append(ax)
769

770
771
    if stat_tests:
        stat_dict = {}
772
        for i in combinations(treatment_dict.keys(), 2):
773
774
775
776
777
778
779
780
781
782
783
            # Solves issue with automatically generated examples
            if (
                beh_dict[i[0]] == beh_dict[i[1]]
                or np.var(beh_dict[i[0]]) == 0
                or np.var(beh_dict[i[1]]) == 0
            ):
                stat_dict[i] = "Identical sources. Couldn't run"
            else:
                stat_dict[i] = stats.mannwhitneyu(
                    beh_dict[i[0]], beh_dict[i[1]], alternative="two-sided"
                )
784
        return_list.append(stat_dict)
785

786
    return return_list
787
788


789
790
791
792
793
794
795
796
797
798
799
800
def max_behaviour(
    behaviour_dframe: pd.DataFrame, window_size: int = 10, stepped: bool = False
) -> np.array:
    """Returns the most frequent behaviour in a window of window_size frames

        Parameters:
                - behaviour_dframe (pd.DataFrame): boolean matrix containing occurrence
                of tagged behaviours per frame in the video
                - window_size (int): size of the window to use when computing
                the maximum behaviour per time slot
                - stepped (bool): sliding windows don't overlap if True. False by default

801
802
803
        Returns:
            - max_array (np.array): string array with the most common behaviour per instance
            of the sliding window"""
804
805
806
807
808
809
810

    speeds = [col for col in behaviour_dframe.columns if "speed" in col.lower()]

    behaviour_dframe = behaviour_dframe.drop(speeds, axis=1).astype("float")
    win_array = behaviour_dframe.rolling(window_size, center=True).sum()
    if stepped:
        win_array = win_array[::window_size]
811
812
    max_array = win_array[1:].idxmax(axis=1)

813
814
815
816
    return np.array(max_array)


# MACHINE LEARNING FUNCTIONS #
817
818


819
820
821
822
823
824
825
826
827
828
829
830
831
def gmm_compute(x: np.array, n_components: int, cv_type: str) -> list:
    """Fits a Gaussian Mixture Model to the provided data and returns evaluation metrics.

        Parameters:
            - x (numpy.array): data matrix to train the model
            - n_components (int): number of Gaussian components to use
            - cv_type (str): covariance matrix type to use.
            Must be one of "spherical", "tied", "diag", "full"

        Returns:
            - gmm_eval (list): model and associated BIC for downstream selection
    """

832
833
834
835
836
837
838
    gmm = mixture.GaussianMixture(
        n_components=n_components,
        covariance_type=cv_type,
        max_iter=100000,
        init_params="kmeans",
    )
    gmm.fit(x)
839
840
841
842
843
    gmm_eval = [gmm, gmm.bic(x)]
    return gmm_eval


def gmm_model_selection(
844
    x: pd.DataFrame,
845
846
847
848
849
850
851
852
    n_components_range: range,
    part_size: int,
    n_runs: int = 100,
    n_cores: int = False,
    cv_types: Tuple = ("spherical", "tied", "diag", "full"),
) -> Tuple[List[list], List[np.ndarray], Union[int, Any]]:
    """Runs GMM clustering model selection on the specified X dataframe, outputs the bic distribution per model,
       a vector with the median BICs and an object with the overall best model
853

854
        Parameters:
855
            - x (pandas.DataFrame): data matrix to train the models
856
857
858
859
860
            - n_components_range (range): generator with numbers of components to evaluate
            - n_runs (int): number of bootstraps for each model
            - part_size (int): size of bootstrap samples for each model
            - n_cores (int): number of cores to use for computation
            - cv_types (tuple): Covariance Matrices to try. All four available by default
861

862
863
864
865
866
867
868
        Returns:
            - bic (list): All recorded BIC values for all attempted parameter combinations
            (useful for plotting)
            - m_bic(list): All minimum BIC values recorded throughout the process
            (useful for plottinh)
            - best_bic_gmm (sklearn.GMM): unfitted version of the best found model
    """
869
870
871
872
873
874
875
876

    # Set the default of n_cores to the most efficient value
    if not n_cores:
        n_cores = min(multiprocessing.cpu_count(), n_runs)

    bic = []
    m_bic = []
    lowest_bic = np.inf
877
    best_bic_gmm = 0
878
879
880
881
882
883
884
885

    pbar = tqdm(total=len(cv_types) * len(n_components_range))

    for cv_type in cv_types:

        for n_components in n_components_range:

            res = Parallel(n_jobs=n_cores, prefer="threads")(
886
887
888
889
                delayed(gmm_compute)(
                    x.sample(part_size, replace=True), n_components, cv_type
                )
                for _ in range(n_runs)
890
891
892
893
894
895
896
897
898
899
900
            )
            bic.append([i[1] for i in res])

            pbar.update(1)
            m_bic.append(np.median([i[1] for i in res]))
            if m_bic[-1] < lowest_bic:
                lowest_bic = m_bic[-1]
                best_bic_gmm = res[0][0]

    return bic, m_bic, best_bic_gmm

901
902

# RESULT ANALYSIS FUNCTIONS #
903
904
905


def cluster_transition_matrix(
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
    cluster_sequence: np.array,
    nclusts: int,
    autocorrelation: bool = True,
    return_graph: bool = False,
) -> Tuple[Union[nx.Graph, Any], np.ndarray]:
    """Computes the transition matrix between clusters and the autocorrelation in the sequence.

        Parameters:
            - cluster_sequence (numpy.array):
            - nclusts (int):
            - autocorrelation (bool):
            - return_graph (bool):

        Returns:
            - trans_normed (numpy.array / networkx.Graph:
            - autocorr (numpy.array):
922
923
924
    """

    # Stores all possible transitions between clusters
925
926
927
    clusters = [str(i) for i in range(nclusts)]
    cluster_sequence = cluster_sequence.astype(str)

928
929
930
931
932
933
934
    trans = {t: 0 for t in product(clusters, clusters)}
    k = len(clusters)

    # Stores the cluster sequence as a string
    transtr = "".join(list(cluster_sequence))

    # Assigns to each transition the number of times it occurs in the sequence
935
    for t in trans.keys():
936
937
938
        trans[t] = len(re.findall("".join(t), transtr, overlapped=True))

    # Normalizes the counts to add up to 1 for each departing cluster
939
940
    trans_normed = np.zeros([k, k]) + 1e-5
    for t in trans.keys():
941
        trans_normed[int(t[0]), int(t[1])] = np.round(
942
943
944
            trans[t]
            / (sum({i: j for i, j in trans.items() if i[0] == t[0]}.values()) + 1e-5),
            3,
945
946
947
948
949
950
951
952
        )

    # If specified, returns the transition matrix as an nx.Graph object
    if return_graph:
        trans_normed = nx.Graph(trans_normed)

    if autocorrelation:
        cluster_sequence = list(map(int, cluster_sequence))
953
954
        autocorr = np.corrcoef(cluster_sequence[:-1], cluster_sequence[1:])
        return trans_normed, autocorr
955
956
957

    return trans_normed

958

959
960
961
962
963
964
# MAIN BEHAVIOUR TAGGING FUNCTION #


def rule_based_tagging(
    tracks: List,
    videos: List,
965
    coordinates: Coordinates,
966
967
968
969
    vid_index: int,
    animal_ids: List = None,
    show: bool = False,
    save: bool = False,
970
    fps: float = 0.0,
971
    speed_pause: int = 10,
972
973
974
975
    frame_limit: float = np.inf,
    recog_limit: int = 1,
    path: str = os.path.join("./"),
    arena_type: str = "circular",
976
977
978
979
980
981
    close_contact_tol: int = 15,
    side_contact_tol: int = 15,
    follow_frames: int = 20,
    follow_tol: int = 20,
    huddle_forward: int = 15,
    huddle_spine: int = 10,
982
    huddle_speed: int = 1,
983
) -> pd.DataFrame:
lucas_miranda's avatar
lucas_miranda committed
984
985
986
987
    """Outputs a dataframe with the registered motives per frame. If specified, produces a labeled
    video displaying the information in real time

    Parameters:
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
        - tracks (list): list containing experiment IDs as strings
        - videos (list): list of videos to load, in the same order as tracks
        - coordinates (deepof.preprocessing.coordinates): coordinates object containing the project information
        - vid_index (int): index in videos of the experiment to annotate
        - animal_ids (list): IDs identifying multiple animals on the arena. None if there's only one
        - show (bool): if True, enables the display of the annotated video in a separate window
        - save (bool): if True, saves the annotated video to an mp4 file
        - fps (float): frames per second of the analysed video. Same as input by default
        - speed_pause (int): size of the rolling window to use when computing speeds
        - frame_limit (float): limit the number of frames to output. Generates all annotated frames by default
        - recog_limit (int): number of frames to use for arena recognition (1 by default)
        - path (str): directory in which the experimental data is stored
        - arena_type (str): type of the arena used in the experiments. Must be one of 'circular'"
        - close_contact_tol (int): maximum distance between single bodyparts that can be used to report the trait
        - side_contact_tol (int): maximum distance between single bodyparts that can be used to report the trait
        - follow_frames (int): number of frames during which the following trait is tracked
        - follow_tol (int): maximum distance between follower and followed's path during the last follow_frames,
        in order to report a detection
        - huddle_forward (int): maximum distance between ears and forward limbs to report a huddle detection
        - huddle_spine (int): maximum average distance between spine body parts to report a huddle detection
        - huddle_speed (int): maximum speed to report a huddle detection
lucas_miranda's avatar
lucas_miranda committed
1009
1010
1011
1012

    Returns:
        - tag_df (pandas.DataFrame): table with traits as columns and frames as rows. Each
        value is a boolean indicating trait detection at a given time"""
1013
1014
1015

    vid_name = re.findall("(.*?)_", tracks[vid_index])[0]

1016
    coords = coordinates.get_coords()[vid_name]
1017
    speeds = coordinates.get_coords(speed=1)[vid_name]
1018
    arena_abs = coordinates.get_arenas[1][0]
1019
1020
1021
    arena, h, w = recognize_arena(videos, vid_index, path, recog_limit, arena_type)

    # Dictionary with motives per frame
1022
    tag_dict = {}
1023
1024
1025
1026
1027

    if animal_ids:
        # Define behaviours that can be computed on the fly from the distance matrix
        tag_dict["nose2nose"] = smooth_boolean_array(
            close_single_contact(
1028
                coords,
1029
1030
                animal_ids[0] + "_Nose",
                animal_ids[1] + "_Nose",
1031
                close_contact_tol,
1032
1033
1034
1035
1036
1037
                arena_abs,
                arena[2],
            )
        )
        tag_dict[animal_ids[0] + "_nose2tail"] = smooth_boolean_array(
            close_single_contact(
1038
                coords,
1039
1040
                animal_ids[0] + "_Nose",
                animal_ids[1] + "_Tail_base",
1041
                close_contact_tol,
1042
1043
1044
1045
1046
1047
                arena_abs,
                arena[2],
            )
        )
        tag_dict[animal_ids[1] + "_nose2tail"] = smooth_boolean_array(
            close_single_contact(
1048
                coords,
1049
1050
                animal_ids[1] + "_Nose",
                animal_ids[0] + "_Tail_base",
1051
                close_contact_tol,
1052
1053
1054
1055
1056
1057
                arena_abs,
                arena[2],
            )
        )
        tag_dict["sidebyside"] = smooth_boolean_array(
            close_double_contact(
1058
                coords,
1059
1060
1061
1062
                animal_ids[0] + "_Nose",
                animal_ids[0] + "_Tail_base",
                animal_ids[1] + "_Nose",
                animal_ids[1] + "_Tail_base",
1063
                side_contact_tol,
1064
1065
1066
1067
1068
1069
1070
                rev=False,
                arena_abs=arena_abs,
                arena_rel=arena[2],
            )
        )
        tag_dict["sidereside"] = smooth_boolean_array(
            close_double_contact(
1071
                coords,
1072
1073
1074
1075
                animal_ids[0] + "_Nose",
                animal_ids[0] + "_Tail_base",
                animal_ids[1] + "_Nose",
                animal_ids[1] + "_Tail_base",
1076
                side_contact_tol,
1077
1078
1079
1080
1081
1082
1083
1084
                rev=True,
                arena_abs=arena_abs,
                arena_rel=arena[2],
            )
        )
        for _id in animal_ids:
            tag_dict[_id + "_following"] = smooth_boolean_array(
                following_path(
1085
1086
                    coords[vid_name],
                    coords,
1087
1088
                    follower=_id,
                    followed=[i for i in animal_ids if i != _id][0],
1089
1090
                    frames=follow_frames,
                    tol=follow_tol,
1091
1092
                )
            )
1093
            tag_dict[_id + "_climbing"] = smooth_boolean_array(
1094
1095
1096
                pd.Series(
                    (
                        spatial.distance.cdist(
1097
                            np.array(coords[_id + "_Nose"]), np.zeros([1, 2])
1098
1099
                        )
                        > (w / 200 + arena[2])
1100
1101
                    ).reshape(coords.shape[0]),
                    index=coords.index,
1102
                ).astype(bool)
1103
            )
1104
            tag_dict[_id + "_speed"] = speeds[_id + "_speed"]
1105
1106
1107
            tag_dict[_id + "_huddle"] = smooth_boolean_array(
                huddle(coords, speeds, huddle_forward, huddle_spine, huddle_speed)
            )
1108
1109

    else:
1110
        tag_dict["climbing"] = smooth_boolean_array(
1111
1112
            pd.Series(
                (
1113
                    spatial.distance.cdist(np.array(coords["Nose"]), np.zeros([1, 2]))
1114
                    > (w / 200 + arena[2])
1115
1116
                ).reshape(coords.shape[0]),
                index=coords.index,
1117
            ).astype(bool)
1118
        )
1119
        tag_dict["speed"] = speeds["Center"]
1120
1121
1122
        tag_dict["huddle"] = smooth_boolean_array(
            huddle(coords, speeds, huddle_forward, huddle_spine, huddle_speed)
        )
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
1153
1154
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
1275
1276
1277
1278
1279
1280
1281
    if any([show, save]):

        cap = cv2.VideoCapture(os.path.join(path, videos[vid_index]))
        # Keep track of the frame number, to align with the tracking data
        fnum = 0
        writer = None
        frame_speeds = {_id: -np.inf for _id in animal_ids} if animal_ids else -np.inf

        # Loop over the frames in the video
        pbar = tqdm(total=min(coords.shape[0] - recog_limit, frame_limit))
        while cap.isOpened() and fnum < frame_limit:

            ret, frame = cap.read()
            # if frame is read correctly ret is True
            if not ret:
                print("Can't receive frame (stream end?). Exiting ...")
                break

            font = cv2.FONT_HERSHEY_COMPLEX_SMALL

            # Label positions
            downleft = (int(w * 0.3 / 10), int(h / 1.05))
            downright = (int(w * 6.5 / 10), int(h / 1.05))
            upleft = (int(w * 0.3 / 10), int(h / 20))
            upright = (int(w * 6.3 / 10), int(h / 20))

            # Capture speeds
            try:
                if list(frame_speeds.values())[0] == -np.inf or fnum % speed_pause == 0:
                    for _id in animal_ids:
                        frame_speeds[_id] = speeds[_id + "_Center"][fnum]
            except AttributeError:
                if frame_speeds == -np.inf or fnum % speed_pause == 0:
                    frame_speeds = speeds["Center"][fnum]

            # Display all annotations in the output video
            if animal_ids:
                if tag_dict["nose2nose"][fnum] and not tag_dict["sidebyside"][fnum]:
                    cv2.putText(
                        frame,
                        "Nose-Nose",
                        (
                            downleft
                            if frame_speeds[animal_ids[0]] > frame_speeds[animal_ids[1]]
                            else downright
                        ),
                        font,
                        1,
                        (255, 255, 255),
                        2,
                    )
                if (
                    tag_dict[animal_ids[0] + "_nose2tail"][fnum]
                    and not tag_dict["sidereside"][fnum]
                ):
                    cv2.putText(
                        frame, "Nose-Tail", downleft, font, 1, (255, 255, 255), 2
                    )
                if (
                    tag_dict[animal_ids[1] + "_nose2tail"][fnum]
                    and not tag_dict["sidereside"][fnum]
                ):
                    cv2.putText(
                        frame, "Nose-Tail", downright, font, 1, (255, 255, 255), 2
                    )
                if tag_dict["sidebyside"][fnum]:
                    cv2.putText(
                        frame,
                        "Side-side",
                        (
                            downleft
                            if frame_speeds[animal_ids[0]] > frame_speeds[animal_ids[1]]
                            else downright
                        ),
                        font,
                        1,
                        (255, 255, 255),
                        2,
                    )
                if tag_dict["sidereside"][fnum]:
                    cv2.putText(
                        frame,
                        "Side-Rside",
                        (
                            downleft
                            if frame_speeds[animal_ids[0]] > frame_speeds[animal_ids[1]]
                            else downright
                        ),
                        font,
                        1,
                        (255, 255, 255),
                        2,
                    )
                for _id, down_pos, up_pos in zip(
                    animal_ids, [downleft, downright], [upleft, upright]
                ):
                    if tag_dict[_id + "_climbing"][fnum]:
                        cv2.putText(
                            frame, "Climbing", down_pos, font, 1, (255, 255, 255), 2
                        )
                    if (
                        tag_dict[_id + "_huddle"][fnum]
                        and not tag_dict[_id + "_climbing"][fnum]
                    ):
                        cv2.putText(
                            frame, "Huddling", down_pos, font, 1, (255, 255, 255), 2
                        )
                    if (
                        tag_dict[_id + "_following"][fnum]
                        and not tag_dict[_id + "_climbing"][fnum]
                    ):
                        cv2.putText(
                            frame,
                            "*f",
                            (int(w * 0.3 / 10), int(h / 10)),
                            font,
                            1,
                            (
                                (150, 150, 255)
                                if frame_speeds[animal_ids[0]]
                                > frame_speeds[animal_ids[1]]
                                else (150, 255, 150)
                            ),
                            2,
                        )
                    cv2.putText(
                        frame,
                        _id + ": " + str(np.round(frame_speeds[_id], 2)) + " mmpf",
                        (up_pos[0] - 20, up_pos[1]),
                        font,
                        1,
                        (
                            (150, 150, 255)
                            if frame_speeds[_id] == max(list(frame_speeds.values()))
                            else (150, 255, 150)
                        ),
                        2,
                    )

            else:
                if tag_dict["climbing"][fnum]:
                    cv2.putText(
                        frame, "Climbing", downleft, font, 1, (255, 255, 255), 2
                    )
                if tag_dict["huddle"][fnum] and not tag_dict["climbing"][fnum]:
                    cv2.putText(frame, "huddle", downleft, font, 1, (255, 255, 255), 2)
                cv2.putText(
                    frame,
                    str(np.round(frame_speeds, 2)) + " mmpf",
                    upleft,
                    font,
                    1,
                    (
                        (150, 150, 255)
                        if huddle_speed > frame_speeds
                        else (150, 255, 150)
                    ),
                    2,
1282
1283
                )

1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
            if show:
                cv2.imshow("frame", frame)

                if cv2.waitKey(1) == ord("q"):
                    break

            if save:

                if writer is None:
                    # Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
                    # Define the FPS. Also frame size is passed.
                    writer = cv2.VideoWriter()
                    writer.open(
                        re.findall("(.*?)_", tracks[vid_index])[0] + "_tagged.avi",
                        cv2.VideoWriter_fourcc(*"MJPG"),
1299
                        (fps if fps != 0 else cv2.CAP_PROP_FPS),
1300
1301
1302
1303
                        (frame.shape[1], frame.shape[0]),
                        True,
                    )

1304
1305
                print(cv2.CAP_PROP_FPS)

1306
1307
1308
1309
1310
1311
1312
                writer.write(frame)

            pbar.update(1)
            fnum += 1

        cap.release()
        cv2.destroyAllWindows()
1313

1314
    tag_df = pd.DataFrame(tag_dict)
1315

1316
    return tag_df
1317
1318


1319
1320
# TODO:
#    - Add sequence plot to single_behaviour_analysis (show how the condition varies across a specified time