test_pose_utils.py 11.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# @author lucasmiranda42
# encoding: utf-8
# module deepof

"""

Testing module for deepof.pose_utils

"""

from hypothesis import given
from hypothesis import HealthCheck
from hypothesis import settings
from hypothesis import strategies as st
from hypothesis.extra.pandas import range_indexes, columns, data_frames
from deepof.pose_utils import *
17
import deepof.data
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import matplotlib.figure
import pytest
import string


@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),
        ),
    ),
    tol=st.floats(min_value=0.01, max_value=4.98),
)
def test_close_single_contact(pos_dframe, tol):

    idx = pd.MultiIndex.from_product(
40
41
        [["bpart1", "bpart2"], ["X", "y"]],
        names=["bodyparts", "coords"],
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
77
78
79
80
81
82
83
    )
    pos_dframe.columns = idx
    close_contact = close_single_contact(pos_dframe, "bpart1", "bpart2", tol, 1, 1)
    assert close_contact.dtype == bool
    assert np.array(close_contact).shape[0] <= pos_dframe.shape[0]


@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(
            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),
        ),
    ),
    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(
        pos_dframe, "bpart1", "bpart2", "bpart3", "bpart4", tol, 1, 1, rev
    )
    assert close_contact.dtype == bool
    assert np.array(close_contact).shape[0] <= pos_dframe.shape[0]


@settings(deadline=None)
@given(
84
85
86
    center=st.tuples(
        st.integers(min_value=300, max_value=500),
        st.integers(min_value=300, max_value=500),
87
    ),
88
89
90
91
92
    axes=st.tuples(
        st.integers(min_value=300, max_value=500),
        st.integers(min_value=300, max_value=500),
    ),
    angle=st.floats(min_value=0, max_value=360),
93
94
    tol=st.data(),
)
95
def test_climb_wall(center, axes, angle, tol):
96

97
    arena = (center, axes, np.radians(angle))
98
99
100
101
    tol1 = tol.draw(st.floats(min_value=0.001, max_value=10))
    tol2 = tol.draw(st.floats(min_value=tol1, max_value=10))

    prun = (
102
        deepof.data.project(
103
            path=os.path.join(".", "tests", "test_examples", "test_single_topview"),
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
            arena="circular",
            arena_dims=tuple([arena[2]]),
            video_format=".mp4",
            table_format=".h5",
        )
        .run(verbose=True)
        .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")


@settings(deadline=None)
@given(
    pos_dframe=data_frames(
        index=range_indexes(min_size=5),
        columns=columns(
            [
130
131
                "X0",
                "y0",
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
                "X1",
                "y1",
                "X2",
                "y2",
                "X3",
                "y3",
                "X4",
                "y4",
                "X5",
                "y5",
            ],
            dtype=float,
            elements=st.floats(min_value=-20, max_value=20),
        ),
    ),
    tol_forward=st.floats(min_value=0.01, max_value=4.98),
    tol_speed=st.floats(min_value=0.01, max_value=4.98),
    animal_id=st.text(min_size=0, max_size=15, alphabet=string.ascii_lowercase),
)
151
def test_single_animal_traits(pos_dframe, tol_forward, tol_speed, animal_id):
152
153
154
155
156
157
158
159

    _id = animal_id
    if animal_id != "":
        _id += "_"

    idx = pd.MultiIndex.from_product(
        [
            [
160
                _id + "Nose",
161
162
                _id + "Left_bhip",
                _id + "Right_bhip",
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
                _id + "Left_fhip",
                _id + "Right_fhip",
                _id + "Center",
            ],
            ["X", "y"],
        ],
        names=["bodyparts", "coords"],
    )
    pos_dframe.columns = idx
    hudd = huddle(
        pos_dframe,
        pos_dframe.xs("X", level="coords", axis=1, drop_level=True),
        tol_forward,
        tol_speed,
        animal_id,
    )
179
180
181
182
183
184
185
    digging = dig(
        pos_dframe.xs("X", level="coords", axis=1, drop_level=True),
        pos_dframe.xs("X", level="coords", axis=1, drop_level=True),
        tol_speed,
        0.85,
        animal_id,
    )
186
187

    assert hudd.dtype == bool
188
    assert digging.dtype == bool
189
    assert np.array(hudd).shape[0] == pos_dframe.shape[0]
190
    assert np.array(digging).shape[0] == pos_dframe.shape[0]
191
    assert np.sum(np.array(hudd)) <= pos_dframe.shape[0]
192
    assert np.sum(np.array(digging)) <= pos_dframe.shape[0]
193
194


lucas_miranda's avatar
lucas_miranda committed
195
@settings(max_examples=10, deadline=None, suppress_health_check=[HealthCheck.too_slow])
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
@given(
    distance_dframe=data_frames(
        index=range_indexes(min_size=20, max_size=20),
        columns=columns(
            ["d1", "d2", "d3", "d4"],
            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(
            ["X1", "y1", "X2", "y2", "X3", "y3", "X4", "y4"],
            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(
226
227
        [bparts, ["X", "y"]],
        names=["bodyparts", "coords"],
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    )

    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]


@settings(
250
251
    deadline=None,
    suppress_health_check=[HealthCheck.too_slow],
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
)
@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())

    plot = sampler.draw(st.integers(min_value=0, max_value=200))

    out = single_behaviour_analysis(
        behaviours[0],
        treatment_dict,
        behavioural_dict,
        plot=plot,
        stat_tests=stat_tests,
        save=None,
        ylim=ylim,
    )

    assert len(out) == 1 if (stat_tests == 0 and plot == 0) else len(out) >= 2
    assert type(out[0]) == dict
    if plot:
        assert np.any(np.array([type(i) for i in out]) == matplotlib.figure.Figure)
    if stat_tests:
        assert type(out[0]) == dict


@settings(
302
303
    deadline=None,
    suppress_health_check=[HealthCheck.too_slow],
304
305
306
307
308
)
@given(
    behaviour_dframe=data_frames(
        index=range_indexes(min_size=100, max_size=1000),
        columns=columns(
309
310
311
            ["d1", "d2", "d3", "d4", "speed1"],
            dtype=bool,
            elements=st.booleans(),
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
        ),
    ),
    window_size=st.data(),
    stepped=st.booleans(),
)
def test_max_behaviour(behaviour_dframe, window_size, stepped):
    wsize1 = window_size.draw(st.integers(min_value=5, max_value=50))
    wsize2 = window_size.draw(st.integers(min_value=wsize1, max_value=50))

    maxbe1 = max_behaviour(behaviour_dframe, wsize1, stepped)
    maxbe2 = max_behaviour(behaviour_dframe, wsize2, stepped)

    assert type(maxbe1) == np.ndarray
    assert type(maxbe2) == np.ndarray
    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)


lucas_miranda's avatar
lucas_miranda committed
334
def test_get_hparameters():
335
336
    assert type(get_hparameters()) == dict
    assert get_hparameters({"speed_pause": 20})["speed_pause"] == 20
lucas_miranda's avatar
lucas_miranda committed
337
338


339
340
341
342
343
344
345
346
347
348
@settings(deadline=None)
@given(
    w=st.integers(min_value=300, max_value=500),
    h=st.integers(min_value=300, max_value=500),
)
def test_frame_corners(w, h):
    assert len(frame_corners(w, h)) == 4
    assert frame_corners(w, h, {"downright": "test"})["downright"] == "test"


349
350
351
352
353
354
@settings(deadline=None)
@given(
    multi_animal=st.booleans(),
    video_output=st.booleans(),
)
def test_rule_based_tagging(multi_animal, video_output):
355

356
357
    if video_output:
        video_output = ["test"]
lucas_miranda's avatar
lucas_miranda committed
358

359
360
361
362
363
364
    path = os.path.join(
        ".",
        "tests",
        "test_examples",
        "test_{}_topview".format("multi" if multi_animal else "single"),
    )
lucas_miranda's avatar
lucas_miranda committed
365

366
    prun = deepof.data.project(
367
        path=path,
lucas_miranda's avatar
lucas_miranda committed
368
369
370
371
        arena="circular",
        arena_dims=tuple([380]),
        video_format=".mp4",
        table_format=".h5",
372
        animal_ids=(["B", "W"] if multi_animal else [""]),
lucas_miranda's avatar
lucas_miranda committed
373
374
    ).run(verbose=True)

375
376
377
    hardcoded_tags = prun.rule_based_annotation(
        video_output=video_output, frame_limit=50
    )
lucas_miranda's avatar
lucas_miranda committed
378

379
    assert type(hardcoded_tags) == deepof.data.table_dict
380
    assert list(hardcoded_tags.values())[0].shape[1] == (21 if multi_animal else 6)