test_utils.py 23.4 KB
Newer Older
1
# @author lucasmiranda42
2
3
4
5
6
7
8
9
# encoding: utf-8
# module deepof

"""

Testing module for deepof.utils

"""
10
11

from hypothesis import given
12
from hypothesis import HealthCheck
lucas_miranda's avatar
lucas_miranda committed
13
from hypothesis import settings
14
15
16
17
from hypothesis import strategies as st
from hypothesis.extra.numpy import arrays
from hypothesis.extra.pandas import range_indexes, columns, data_frames
from scipy.spatial import distance
lucas_miranda's avatar
lucas_miranda committed
18
from deepof.utils import *
19
import deepof.preprocess
lucas_miranda's avatar
lucas_miranda committed
20
import matplotlib.figure
21
import pytest
22
import string
23

24

lucas_miranda's avatar
lucas_miranda committed
25
26
27
28
# AUXILIARY FUNCTIONS #


def autocorr(x, t=1):
lucas_miranda's avatar
lucas_miranda committed
29
    """Computes autocorrelation of the given array with a lag of t"""
lucas_miranda's avatar
lucas_miranda committed
30
31
    return np.round(np.corrcoef(np.array([x[:-t], x[t:]]))[0, 1], 5)

32

33
34
35
# QUALITY CONTROL AND PREPROCESSING #


lucas_miranda's avatar
lucas_miranda committed
36
@settings(deadline=None)
lucas_miranda's avatar
lucas_miranda committed
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
72
73
74
75
76
@given(
    mult=st.integers(min_value=1, max_value=10),
    dframe=data_frames(
        index=range_indexes(min_size=1),
        columns=columns(["X", "y", "likelihood"], dtype=float),
        rows=st.tuples(
            st.floats(
                min_value=0, max_value=1000, allow_nan=False, allow_infinity=False
            ),
            st.floats(
                min_value=0, max_value=1000, allow_nan=False, allow_infinity=False
            ),
            st.floats(
                min_value=0.01, max_value=1.0, allow_nan=False, allow_infinity=False
            ),
        ),
    ),
    threshold=st.data(),
)
def test_likelihood_qc(mult, dframe, threshold):
    thresh1 = threshold.draw(st.floats(min_value=0.1, max_value=1.0, allow_nan=False))
    thresh2 = threshold.draw(
        st.floats(min_value=thresh1, max_value=1.0, allow_nan=False)
    )

    dframe = pd.concat([dframe] * mult, axis=0)
    idx = pd.MultiIndex.from_product(
        [list(dframe.columns[: len(dframe.columns) // 3]), ["X", "y", "likelihood"]],
        names=["bodyparts", "coords"],
    )
    dframe.columns = idx

    filt1 = likelihood_qc(dframe, thresh1)
    filt2 = likelihood_qc(dframe, thresh2)

    assert np.sum(filt1) <= dframe.shape[0]
    assert np.sum(filt2) <= dframe.shape[0]
    assert np.sum(filt1) >= np.sum(filt2)


lucas_miranda's avatar
lucas_miranda committed
77
@settings(deadline=None)
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
@given(
    tab=data_frames(
        index=range_indexes(min_size=1),
        columns=columns(["X", "y"], dtype=float),
        rows=st.tuples(
            st.floats(
                min_value=0, max_value=1000, allow_nan=False, allow_infinity=False
            ),
            st.floats(
                min_value=0, max_value=1000, allow_nan=False, allow_infinity=False
            ),
        ),
    )
)
def test_bp2polar(tab):
    polar = bp2polar(tab)
    assert np.allclose(polar["rho"], np.sqrt(tab["X"] ** 2 + tab["y"] ** 2))
    assert np.allclose(polar["phi"], np.arctan2(tab["y"], tab["X"]))


lucas_miranda's avatar
lucas_miranda committed
98
@settings(deadline=None)
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
@given(
    mult=st.integers(min_value=1, max_value=10),
    cartdf=data_frames(
        index=range_indexes(min_size=1),
        columns=columns(["X", "y"], dtype=float),
        rows=st.tuples(
            st.floats(
                min_value=0, max_value=1000, allow_nan=False, allow_infinity=False
            ),
            st.floats(
                min_value=0, max_value=1000, allow_nan=False, allow_infinity=False
            ),
        ),
    ),
)
def test_tab2polar(mult, cartdf):
    cart_df = pd.concat([cartdf] * mult, axis=0)
    idx = pd.MultiIndex.from_product(
        [list(cart_df.columns[: len(cart_df.columns) // 2]), ["X", "y"]],
        names=["bodyparts", "coords"],
    )
    cart_df.columns = idx

    assert cart_df.shape == tab2polar(cart_df).shape


lucas_miranda's avatar
lucas_miranda committed
125
@settings(deadline=None)
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
@given(
    pair_array=arrays(
        dtype=float,
        shape=st.tuples(
            st.integers(min_value=1, max_value=1000),
            st.integers(min_value=4, max_value=4),
        ),
        elements=st.floats(min_value=-1000, max_value=1000, allow_nan=False),
    ),
    arena_abs=st.integers(min_value=1, max_value=1000),
    arena_rel=st.integers(min_value=1, max_value=1000),
)
def test_compute_dist(pair_array, arena_abs, arena_rel):
    assert np.allclose(
        compute_dist(pair_array, arena_abs, arena_rel),
        pd.DataFrame(distance.cdist(pair_array[:, :2], pair_array[:, 2:]).diagonal())
        * arena_abs
        / arena_rel,
    )


lucas_miranda's avatar
lucas_miranda committed
147
@settings(deadline=None)
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
@given(
    cordarray=arrays(
        dtype=float,
        shape=st.tuples(
            st.integers(min_value=1, max_value=100),
            st.integers(min_value=2, max_value=5).map(lambda x: 4 * x),
        ),
        elements=st.floats(
            min_value=-1000, max_value=1000, allow_nan=False, allow_infinity=False
        ),
    ),
)
def test_bpart_distance(cordarray):
    cord_df = pd.DataFrame(cordarray)
    idx = pd.MultiIndex.from_product(
        [list(cord_df.columns[: len(cord_df.columns) // 2]), ["X", "y"]],
        names=["bodyparts", "coords"],
    )
    cord_df.columns = idx

    bpart = bpart_distance(cord_df)

    assert bpart.shape[0] == cord_df.shape[0]
    assert bpart.shape[1] == len(list(combinations(range(cord_df.shape[1] // 2), 2)))


lucas_miranda's avatar
lucas_miranda committed
174
@settings(deadline=None)
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
@given(
    abc=arrays(
        dtype=float,
        shape=st.tuples(
            st.integers(min_value=3, max_value=3),
            st.integers(min_value=5, max_value=100),
            st.integers(min_value=2, max_value=2),
        ),
        elements=st.floats(
            min_value=1, max_value=10, allow_nan=False, allow_infinity=False
        ).map(lambda x: x + np.random.uniform(0, 10)),
    ),
)
def test_angle(abc):
    a, b, c = abc

    angles = []
    for i, j, k in zip(a, b, c):
        ang = np.arccos(
            (np.dot(i - j, k - j) / (np.linalg.norm(i - j) * np.linalg.norm(k - j)))
        )
        angles.append(ang)

    print(angle(a, b, c), np.array(angles))

    assert np.allclose(angle(a, b, c), np.array(angles))


lucas_miranda's avatar
lucas_miranda committed
203
@settings(deadline=None)
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
@given(
    array=arrays(
        dtype=float,
        shape=st.tuples(
            st.integers(min_value=3, max_value=3),
            st.integers(min_value=5, max_value=100),
            st.integers(min_value=2, max_value=2),
        ),
        elements=st.floats(
            min_value=1, max_value=10, allow_nan=False, allow_infinity=False
        ).map(lambda x: x + np.random.uniform(0, 10)),
    )
)
def test_angle_trio(array):
    assert len(angle_trio(array)) == 3


lucas_miranda's avatar
lucas_miranda committed
221
@settings(deadline=None)
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
@given(
    p=arrays(
        dtype=float,
        shape=st.tuples(
            st.integers(min_value=2, max_value=100),
            st.integers(min_value=2, max_value=2),
        ),
        elements=st.floats(
            min_value=1, max_value=10, allow_nan=False, allow_infinity=False
        ),
    )
)
def test_rotate(p):
    assert np.allclose(rotate(p, 2 * np.pi), p)
    assert np.allclose(rotate(p, np.pi), -p)
lucas_miranda's avatar
lucas_miranda committed
237
    assert np.allclose(rotate(p, 0), p)
238
239


lucas_miranda's avatar
lucas_miranda committed
240
@settings(deadline=None)
241
242
243
244
245
246
247
248
249
250
251
@given(
    data=arrays(
        dtype=float,
        shape=st.tuples(
            st.integers(min_value=1, max_value=100),
            st.integers(min_value=3, max_value=100),
            st.integers(min_value=1, max_value=10).map(lambda x: 2 * x),
        ),
        elements=st.floats(
            min_value=1, max_value=10, allow_nan=False, allow_infinity=False
        ),
252
    ),
lucas_miranda's avatar
lucas_miranda committed
253
    mode_idx=st.integers(min_value=0, max_value=2),
254
)
255
def test_align_trajectories(data, mode_idx):
lucas_miranda's avatar
lucas_miranda committed
256
    mode = ["center", "all", "none"][mode_idx]
257
258
259
260
261
262
    aligned = align_trajectories(data, mode)
    assert aligned.shape == data.shape
    if mode == "center":
        assert np.allclose(aligned[:, (data.shape[1] - 1) // 2, 0], 0)
    elif mode == "all":
        assert np.allclose(aligned[:, :, 0], 0)
lucas_miranda's avatar
lucas_miranda committed
263
264
    elif mode == "none":
        assert np.allclose(aligned, data)
265
266


lucas_miranda's avatar
lucas_miranda committed
267
@settings(deadline=None)
268
269
270
@given(a=arrays(dtype=bool, shape=st.tuples(st.integers(min_value=3, max_value=1000))))
def test_smooth_boolean_array(a):
    smooth = smooth_boolean_array(a)
lucas_miranda's avatar
lucas_miranda committed
271
272

    def trans(x):
lucas_miranda's avatar
lucas_miranda committed
273
        """In situ function for computing boolean transitions"""
lucas_miranda's avatar
lucas_miranda committed
274
275
        return sum([i + 1 != i for i in range(x.shape[0] - 1)])

276
277
278
    assert trans(a) >= trans(smooth)


lucas_miranda's avatar
lucas_miranda committed
279
@settings(deadline=None)
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
@given(
    a=arrays(
        dtype=float,
        shape=st.tuples(
            st.integers(min_value=1000, max_value=10000),
            st.integers(min_value=1, max_value=10).map(lambda x: 2 * x),
        ),
        elements=st.floats(
            min_value=1, max_value=10, allow_nan=False, allow_infinity=False
        ),
    ),
    window=st.data(),
)
def test_rolling_window(a, window):
    window_step = window.draw(st.integers(min_value=1, max_value=10))
    window_size = window.draw(
        st.integers(min_value=1, max_value=10).map(lambda x: x * window_step)
    )

    rolled_shape = rolling_window(a, window_size, window_step).shape

301
    assert len(rolled_shape) == len(a.shape) + 1
302
    assert rolled_shape[1] == window_size
lucas_miranda's avatar
lucas_miranda committed
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
333


@settings(deadline=None)
@given(
    alpha=st.data(),
    series=arrays(
        dtype=float,
        shape=st.tuples(st.integers(min_value=10, max_value=1000),),
        elements=st.floats(
            min_value=1.0, max_value=1.0, allow_nan=False, allow_infinity=False
        ),
    ),
)
def test_smooth_mult_trajectory(alpha, series):
    alpha1 = alpha.draw(
        st.floats(min_value=0.1, max_value=1.0, allow_nan=False, allow_infinity=False)
    )
    alpha2 = alpha.draw(
        st.floats(
            min_value=alpha1, max_value=1.0, allow_nan=False, allow_infinity=False
        )
    )

    series *= +np.random.normal(0, 1, len(series))

    smoothed1 = smooth_mult_trajectory(series, alpha1)
    smoothed2 = smooth_mult_trajectory(series, alpha2)

    assert autocorr(smoothed1) >= autocorr(series)
    assert autocorr(smoothed2) >= autocorr(series)
    assert autocorr(smoothed2) <= autocorr(smoothed1)
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350


# BEHAVIOUR RECOGNITION FUNCTIONS #


@settings(deadline=None)
@given(
    pos_dframe=data_frames(
        index=range_indexes(min_size=5),
        columns=columns(["X1", "y1", "X2", "y2"], dtype=float),
        rows=st.tuples(
            st.floats(min_value=1, max_value=10, allow_nan=False, allow_infinity=False),
            st.floats(min_value=1, max_value=10, allow_nan=False, allow_infinity=False),
            st.floats(min_value=1, max_value=10, allow_nan=False, allow_infinity=False),
            st.floats(min_value=1, max_value=10, allow_nan=False, allow_infinity=False),
        ),
    ),
351
    tol=st.floats(min_value=0.01, max_value=4.98),
352
353
354
355
356
357
358
)
def test_close_single_contact(pos_dframe, tol):

    idx = pd.MultiIndex.from_product(
        [["bpart1", "bpart2"], ["X", "y"]], names=["bodyparts", "coords"],
    )
    pos_dframe.columns = idx
359
    close_contact = close_single_contact(pos_dframe, "bpart1", "bpart2", tol, 1, 1)
360
361
    assert close_contact.dtype == bool
    assert np.array(close_contact).shape[0] <= pos_dframe.shape[0]
362
363
364
365
366
367
368
369


@settings(deadline=None)
@given(
    pos_dframe=data_frames(
        index=range_indexes(min_size=5),
        columns=columns(["X1", "y1", "X2", "y2", "X3", "y3", "X4", "y4"], dtype=float),
        rows=st.tuples(
lucas_miranda's avatar
lucas_miranda committed
370
371
372
373
374
375
376
377
            st.floats(min_value=1, max_value=10),
            st.floats(min_value=1, max_value=10),
            st.floats(min_value=1, max_value=10),
            st.floats(min_value=1, max_value=10),
            st.floats(min_value=1, max_value=10),
            st.floats(min_value=1, max_value=10),
            st.floats(min_value=1, max_value=10),
            st.floats(min_value=1, max_value=10),
378
379
380
381
382
383
384
385
386
387
388
389
390
        ),
    ),
    tol=st.floats(min_value=0.01, max_value=4.98),
    rev=st.booleans(),
)
def test_close_double_contact(pos_dframe, tol, rev):

    idx = pd.MultiIndex.from_product(
        [["bpart1", "bpart2", "bpart3", "bpart4"], ["X", "y"]],
        names=["bodyparts", "coords"],
    )
    pos_dframe.columns = idx
    close_contact = close_double_contact(
391
        pos_dframe, "bpart1", "bpart2", "bpart3", "bpart4", tol, 1, 1, rev
392
393
394
    )
    assert close_contact.dtype == bool
    assert np.array(close_contact).shape[0] <= pos_dframe.shape[0]
lucas_miranda's avatar
lucas_miranda committed
395
396


397
@settings(deadline=None)
398
399
@given(indexes=st.data())
def test_recognize_arena_and_subfunctions(indexes):
lucas_miranda's avatar
lucas_miranda committed
400

401
    path = os.path.join(".", "tests", "test_examples", "Videos")
lucas_miranda's avatar
lucas_miranda committed
402
403
404
405
406
    videos = [i for i in os.listdir(path) if i.endswith("mp4")]

    vid_index = indexes.draw(st.integers(min_value=0, max_value=len(videos) - 1))
    recoglimit = indexes.draw(st.integers(min_value=1, max_value=10))

407
    assert recognize_arena(videos, vid_index, path, recoglimit, "")[0] == 0
408
    assert len(recognize_arena(videos, vid_index, path, recoglimit, "circular")) == 3
409
410
411
412
413
414
415
    assert len(recognize_arena(videos, vid_index, path, recoglimit, "circular")[0]) == 3
    assert (
        type(recognize_arena(videos, vid_index, path, recoglimit, "circular")[1]) == int
    )
    assert (
        type(recognize_arena(videos, vid_index, path, recoglimit, "circular")[2]) == int
    )
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431


@settings(deadline=None)
@given(
    arena=st.lists(
        min_size=3, max_size=3, elements=st.integers(min_value=300, max_value=500)
    ),
    tol=st.data(),
)
def test_climb_wall(arena, tol):

    tol1 = tol.draw(st.floats(min_value=0.001, max_value=10))
    tol2 = tol.draw(st.floats(min_value=tol1, max_value=10))

    prun = (
        deepof.preprocess.project(
432
            path=os.path.join(".", "tests", "test_examples"),
433
            arena="circular",
lucas_miranda's avatar
lucas_miranda committed
434
            arena_dims=tuple([arena[2]]),
435
436
437
438
            angles=False,
            video_format=".mp4",
            table_format=".h5",
        )
439
        .run(verbose=True)
440
441
442
443
444
445
446
447
448
449
450
451
        .get_coords()
    )

    climb1 = climb_wall("circular", arena, prun["test"], tol1, nose="Nose")
    climb2 = climb_wall("circular", arena, prun["test"], tol2, nose="Nose")

    assert climb1.dtype == bool
    assert climb2.dtype == bool
    assert np.sum(climb1) >= np.sum(climb2)

    with pytest.raises(NotImplementedError):
        climb_wall("", arena, prun["test"], tol1, nose="Nose")
lucas_miranda's avatar
lucas_miranda committed
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485


@settings(deadline=None)
@given(
    dframe=data_frames(
        index=range_indexes(min_size=50),
        columns=columns(["X1", "y1", "X2", "y2"], dtype=float),
        rows=st.tuples(
            st.floats(min_value=1, max_value=10),
            st.floats(min_value=1, max_value=10),
            st.floats(min_value=1, max_value=10),
            st.floats(min_value=1, max_value=10),
        ),
    ),
    sampler=st.data(),
)
def test_rolling_speed(dframe, sampler):

    dframe *= np.random.uniform(0, 1, dframe.shape)

    order1 = sampler.draw(st.integers(min_value=1, max_value=3))
    order2 = sampler.draw(st.integers(min_value=order1, max_value=3))

    idx = pd.MultiIndex.from_product(
        [["bpart1", "bpart2"], ["X", "y"]], names=["bodyparts", "coords"],
    )
    dframe.columns = idx

    speeds1 = rolling_speed(dframe, 5, 10, order1)
    speeds2 = rolling_speed(dframe, 5, 10, order2)

    assert speeds1.shape[0] == dframe.shape[0]
    assert speeds1.shape[1] == dframe.shape[1] // 2
    assert np.all(np.std(speeds1) >= np.std(speeds2))
lucas_miranda's avatar
lucas_miranda committed
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


@settings(deadline=None)
@given(
    pos_dframe=data_frames(
        index=range_indexes(min_size=5),
        columns=columns(
            [
                "X1",
                "y1",
                "X2",
                "y2",
                "X3",
                "y3",
                "X4",
                "y4",
                "X5",
                "y5",
                "X6",
                "y6",
                "X7",
                "y7",
                "X8",
                "y8",
            ],
            dtype=float,
            elements=st.floats(min_value=-20, max_value=20),
        ),
    ),
    tol_forward=st.floats(min_value=0.01, max_value=4.98),
    tol_spine=st.floats(min_value=0.01, max_value=4.98),
517
    tol_speed=st.floats(min_value=0.01, max_value=4.98),
518
    animal_id=st.text(min_size=0, max_size=15, alphabet=string.ascii_lowercase),
lucas_miranda's avatar
lucas_miranda committed
519
)
520
521
522
523
524
def test_huddle(pos_dframe, tol_forward, tol_spine, tol_speed, animal_id):

    _id = animal_id
    if animal_id != "":
        _id += "_"
lucas_miranda's avatar
lucas_miranda committed
525
526
527
528

    idx = pd.MultiIndex.from_product(
        [
            [
529
530
531
532
533
534
535
536
                _id + "Left_ear",
                _id + "Right_ear",
                _id + "Left_fhip",
                _id + "Right_fhip",
                _id + "Spine_1",
                _id + "Center",
                _id + "Spine_2",
                _id + "Tail_base",
lucas_miranda's avatar
lucas_miranda committed
537
538
539
540
541
542
            ],
            ["X", "y"],
        ],
        names=["bodyparts", "coords"],
    )
    pos_dframe.columns = idx
543
544
545
546
547
548
549
550
    hudd = huddle(
        pos_dframe,
        pos_dframe.xs("X", level="coords", axis=1, drop_level=True),
        tol_forward,
        tol_spine,
        tol_speed,
        animal_id,
    )
lucas_miranda's avatar
lucas_miranda committed
551
552
553
554

    assert hudd.dtype == bool
    assert np.array(hudd).shape[0] == pos_dframe.shape[0]
    assert np.sum(np.array(hudd)) <= pos_dframe.shape[0]
lucas_miranda's avatar
lucas_miranda committed
555
556
557
558
559
560
561


@settings(deadline=None)
@given(
    distance_dframe=data_frames(
        index=range_indexes(min_size=20, max_size=20),
        columns=columns(
562
            ["d1", "d2", "d3", "d4"],
lucas_miranda's avatar
lucas_miranda committed
563
564
565
566
567
568
569
            dtype=float,
            elements=st.floats(min_value=-20, max_value=20),
        ),
    ),
    position_dframe=data_frames(
        index=range_indexes(min_size=20, max_size=20),
        columns=columns(
570
            ["X1", "y1", "X2", "y2", "X3", "y3", "X4", "y4"],
lucas_miranda's avatar
lucas_miranda committed
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
            dtype=float,
            elements=st.floats(min_value=-20, max_value=20),
        ),
    ),
    frames=st.integers(min_value=1, max_value=20),
    tol=st.floats(min_value=0.01, max_value=4.98),
)
def test_following_path(distance_dframe, position_dframe, frames, tol):

    bparts = [
        "A_Nose",
        "B_Nose",
        "A_Tail_base",
        "B_Tail_base",
    ]

    pos_idx = pd.MultiIndex.from_product(
588
        [bparts, ["X", "y"]], names=["bodyparts", "coords"],
lucas_miranda's avatar
lucas_miranda committed
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
    )

    position_dframe.columns = pos_idx
    distance_dframe.columns = [c for c in combinations(bparts, 2) if c[0][0] != c[1][0]]

    follow = following_path(
        distance_dframe,
        position_dframe,
        follower="A",
        followed="B",
        frames=frames,
        tol=tol,
    )

    assert follow.dtype == bool
    assert len(follow) == position_dframe.shape[0]
    assert len(follow) == distance_dframe.shape[0]
    assert np.sum(follow) <= position_dframe.shape[0]
    assert np.sum(follow) <= distance_dframe.shape[0]
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


@settings(
    deadline=None, suppress_health_check=[HealthCheck.too_slow],
)
@given(sampler=st.data())
def test_single_behaviour_analysis(sampler):
    behaviours = sampler.draw(
        st.lists(min_size=2, elements=st.text(min_size=5), unique=True)
    )
    treatments = sampler.draw(
        st.lists(min_size=2, max_size=4, elements=st.text(min_size=5), unique=True)
    )

    behavioural_dict = sampler.draw(
        st.dictionaries(
            min_size=2,
            keys=st.text(min_size=5),
            values=data_frames(
                index=range_indexes(min_size=50, max_size=50),
                columns=columns(behaviours, dtype=bool),
            ),
        )
    )

    ind_dict = {vid: np.random.choice(treatments) for vid in behavioural_dict.keys()}
    treatment_dict = {treat: [] for treat in set(ind_dict.values())}
    for vid, treat in ind_dict.items():
        treatment_dict[treat].append(vid)

    ylim = sampler.draw(st.floats(min_value=0, max_value=10))
    stat_tests = sampler.draw(st.booleans())

lucas_miranda's avatar
lucas_miranda committed
641
642
    plot = sampler.draw(st.integers(min_value=0, max_value=200))

643
644
645
646
    out = single_behaviour_analysis(
        behaviours[0],
        treatment_dict,
        behavioural_dict,
lucas_miranda's avatar
lucas_miranda committed
647
        plot=plot,
648
649
650
651
652
        stat_tests=stat_tests,
        save=None,
        ylim=ylim,
    )

lucas_miranda's avatar
lucas_miranda committed
653
    assert len(out) == 1 if (stat_tests == 0 and plot == 0) else len(out) >= 2
654
    assert type(out[0]) == dict
lucas_miranda's avatar
lucas_miranda committed
655
656
    if plot:
        assert np.any(np.array([type(i) for i in out]) == matplotlib.figure.Figure)
657
658
    if stat_tests:
        assert type(out[0]) == dict
659
660
661
662
663
664
665
666
667
668
669
670
671


@settings(
    deadline=None, suppress_health_check=[HealthCheck.too_slow],
)
@given(
    behaviour_dframe=data_frames(
        index=range_indexes(min_size=100, max_size=1000),
        columns=columns(
            ["d1", "d2", "d3", "d4", "speed1"], dtype=bool, elements=st.booleans(),
        ),
    ),
    window_size=st.data(),
672
    stepped=st.booleans(),
673
)
674
def test_max_behaviour(behaviour_dframe, window_size, stepped):
675
676
677
    wsize1 = window_size.draw(st.integers(min_value=5, max_value=50))
    wsize2 = window_size.draw(st.integers(min_value=wsize1, max_value=50))

678
679
    maxbe1 = max_behaviour(behaviour_dframe, wsize1, stepped)
    maxbe2 = max_behaviour(behaviour_dframe, wsize2, stepped)
680
681
682

    assert type(maxbe1) == np.ndarray
    assert type(maxbe2) == np.ndarray
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
    if not stepped:
        assert type(maxbe1[wsize1 // 2 + 1]) == str
        assert type(maxbe1[wsize2 // 2 + 1]) == str
        assert maxbe1[wsize1 // 2 + 1] in behaviour_dframe.columns
        assert maxbe2[wsize2 // 2 + 1] in behaviour_dframe.columns
        assert len(maxbe1) >= len(maxbe2)


@settings(
    deadline=None, suppress_health_check=[HealthCheck.too_slow],
)
@given(
    x=arrays(
        dtype=float,
        shape=st.tuples(
            st.integers(min_value=10, max_value=1000),
            st.integers(min_value=10, max_value=1000),
        ),
        elements=st.floats(min_value=1.0, max_value=1.0,),
    ).map(lambda x: x * np.random.uniform(0, 2, x.shape)),
    n_components=st.integers(min_value=1, max_value=10),
    cv_type=st.integers(min_value=0, max_value=3),
)
def test_gmm_compute(x, n_components, cv_type):
    cv_type = ["spherical", "tied", "diag", "full"][cv_type]
    assert len(gmm_compute(x, n_components, cv_type)) == 2


@settings(
    deadline=None, suppress_health_check=[HealthCheck.too_slow],
)
@given(
    x=arrays(
        dtype=float,
        shape=st.tuples(
            st.integers(min_value=10, max_value=1000),
            st.integers(min_value=10, max_value=1000),
        ),
        elements=st.floats(min_value=1.0, max_value=1.0,),
    ).map(lambda x: x * np.random.uniform(0, 2, x.shape)),
    sampler=st.data(),
)
def test_gmm_model_selection(x, sampler):
    n_component_range = range(1, sampler.draw(st.integers(min_value=2, max_value=5)))
    part_size = sampler.draw(
        st.integers(min_value=x.shape[0] // 2, max_value=x.shape[0] * 2)
    )
    assert (
        len(
            gmm_model_selection(pd.DataFrame(x), n_component_range, part_size, n_runs=1)
        )
        == 3
    )
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


@settings(deadline=None)
@given(sampler=st.data(), autocorrelation=st.booleans(), return_graph=st.booleans())
def test_cluster_transition_matrix(sampler, autocorrelation, return_graph):

    nclusts = sampler.draw(st.integers(min_value=1, max_value=10))
    cluster_sequence = sampler.draw(
        arrays(
            dtype=int,
            shape=st.tuples(st.integers(min_value=10, max_value=1000)),
            elements=st.integers(min_value=1, max_value=nclusts),
        ).filter(lambda x: len(set(x)) != 1)
    )

    trans = cluster_transition_matrix(
        cluster_sequence, nclusts, autocorrelation, return_graph
    )

    if autocorrelation:
        assert len(trans) == 2

        if return_graph:
            assert type(trans[0]) == nx.Graph
        else:
            assert type(trans[0]) == np.ndarray

        assert type(trans[1]) == np.ndarray

    else:
        if return_graph:
            assert type(trans) == nx.Graph
        else:
            assert type(trans) == np.ndarray
770
771


772
def test_rule_based_tagging():
773
774
775
776

    prun = deepof.preprocess.project(
        path=os.path.join(".", "tests", "test_examples"),
        arena="circular",
lucas_miranda's avatar
lucas_miranda committed
777
        arena_dims=tuple([380]),
778
779
780
        angles=False,
        video_format=".mp4",
        table_format=".h5",
781
    ).run(verbose=True)
782
783
784
785
786
787
788

    hardcoded_tags = rule_based_tagging(
        list([i + "_" for i in prun.get_coords().keys()]),
        ["test_video_circular_arena.mp4"],
        prun,
        vid_index=0,
        path=os.path.join(".", "tests", "test_examples", "Videos"),
789
790
        save=True,
        frame_limit=100,
791
792
793
    )

    assert type(hardcoded_tags) == pd.DataFrame
794
    assert hardcoded_tags.shape[1] == 3