File size: 11,744 Bytes
bc18e51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
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
302
303
304
305
306
307
308
309
310
311
312
"""
Unit tests for MovementClassifier
Tests movement classification, intensity calculation, and rhythm detection
"""

import pytest
import numpy as np
from pathlib import Path
import sys

sys.path.insert(0, str(Path(__file__).parent.parent))

from app.movement_classifier import MovementClassifier, MovementType, MovementMetrics
from app.pose_analyzer import PoseKeypoints
from app.config import Config


class TestMovementClassifier:
    """Test suite for MovementClassifier functionality"""
    
    @pytest.fixture
    def classifier(self):
        """Create MovementClassifier instance for testing"""
        return MovementClassifier()
    
    @pytest.fixture
    def standing_sequence(self):
        """Create a sequence representing standing still"""
        sequence = []
        base_landmarks = np.random.rand(33, 3)
        
        for i in range(10):
            # Very small random noise to simulate standing
            landmarks = base_landmarks + np.random.normal(0, 0.001, (33, 3))
            landmarks[:, 2] = 0.9  # High confidence
            
            pose = PoseKeypoints(
                landmarks=landmarks,
                frame_number=i,
                timestamp=i/30.0,
                confidence=0.9
            )
            sequence.append(pose)
        
        return sequence
    
    @pytest.fixture
    def dancing_sequence(self):
        """Create a sequence representing dancing (high movement)"""
        sequence = []
        
        for i in range(20):
            # Create varied movement
            landmarks = np.random.rand(33, 3)
            landmarks[:, 2] = 0.9
            
            # Add more variation to simulate dancing
            landmarks[:, 0] += np.sin(i * 0.5) * 0.1
            landmarks[:, 1] += np.cos(i * 0.5) * 0.1
            
            pose = PoseKeypoints(
                landmarks=landmarks,
                frame_number=i,
                timestamp=i/30.0,
                confidence=0.9
            )
            sequence.append(pose)
        
        return sequence
    
    @pytest.fixture
    def jumping_sequence(self):
        """Create a sequence representing jumping (vertical movement)"""
        sequence = []
        base_landmarks = np.random.rand(33, 3)
        
        for i in range(15):
            landmarks = base_landmarks.copy()
            
            # Simulate vertical jump (modify hip positions)
            jump_height = 0.1 * np.sin(i * np.pi / 7)  # Jump cycle
            landmarks[23, 1] -= jump_height  # Left hip
            landmarks[24, 1] -= jump_height  # Right hip
            landmarks[:, 2] = 0.9
            
            pose = PoseKeypoints(
                landmarks=landmarks,
                frame_number=i,
                timestamp=i/30.0,
                confidence=0.9
            )
            sequence.append(pose)
        
        return sequence
    
    def test_classifier_initialization(self, classifier):
        """Test MovementClassifier initializes correctly"""
        assert classifier is not None
        assert len(classifier.movement_history) == 0
        assert classifier.smoothing_window > 0
    
    def test_analyze_empty_sequence(self, classifier):
        """Test analyzing empty sequence"""
        metrics = classifier.analyze_sequence([])
        
        assert metrics.movement_type == MovementType.UNKNOWN
        assert metrics.intensity == 0.0
        assert metrics.velocity == 0.0
    
    def test_analyze_standing_sequence(self, classifier, standing_sequence):
        """Test classification of standing movement"""
        metrics = classifier.analyze_sequence(standing_sequence)
        
        assert metrics is not None
        # Standing should have low velocity
        assert metrics.velocity < Config.VELOCITY_WALKING
        # Should have low intensity
        assert metrics.intensity < 30.0
    
    def test_analyze_dancing_sequence(self, classifier, dancing_sequence):
        """Test classification of dancing movement"""
        metrics = classifier.analyze_sequence(dancing_sequence)
        
        assert metrics is not None
        # Dancing should have higher velocity
        assert metrics.velocity > Config.VELOCITY_STANDING
        # Should have higher intensity
        assert metrics.intensity > 20.0
    
    def test_velocity_calculation(self, classifier, dancing_sequence):
        """Test velocity calculation between frames"""
        velocities = classifier._calculate_velocities(dancing_sequence)
        
        assert len(velocities) == len(dancing_sequence) - 1
        assert np.all(velocities >= 0)  # Velocities should be non-negative
    
    def test_jumping_detection(self, classifier, jumping_sequence):
        """Test jumping detection algorithm"""
        is_jumping = classifier._detect_jumping(jumping_sequence)
        
        # Jumping sequence should be detected
        # Note: This may be True or False depending on threshold sensitivity
        assert isinstance(is_jumping, bool)
    
    def test_crouching_detection(self, classifier):
        """Test crouching detection"""
        # Create crouching pose (compressed torso)
        landmarks = np.random.rand(33, 3)
        landmarks[11, 1] = 0.3  # Shoulder
        landmarks[12, 1] = 0.3
        landmarks[23, 1] = 0.35  # Hip (very close to shoulder)
        landmarks[24, 1] = 0.35
        landmarks[:, 2] = 0.9
        
        crouch_pose = PoseKeypoints(
            landmarks=landmarks,
            frame_number=0,
            timestamp=0.0,
            confidence=0.9
        )
        
        is_crouching = classifier._detect_crouching([crouch_pose])
        
        assert isinstance(is_crouching, bool)
    
    def test_intensity_calculation(self, classifier, dancing_sequence):
        """Test movement intensity calculation"""
        velocities = classifier._calculate_velocities(dancing_sequence)
        movement_type = MovementType.DANCING
        
        intensity = classifier._calculate_intensity(velocities, movement_type)
        
        assert 0 <= intensity <= 100
        assert isinstance(intensity, (int, float))
    
    def test_body_part_activity(self, classifier, dancing_sequence):
        """Test body part activity calculation"""
        activity = classifier._calculate_body_part_activity(dancing_sequence)
        
        # Should have activity scores for all body parts
        expected_parts = ["head", "torso", "left_arm", "right_arm", "left_leg", "right_leg"]
        
        for part in expected_parts:
            assert part in activity
            assert 0 <= activity[part] <= 100
    
    def test_movement_summary_empty(self, classifier):
        """Test movement summary with no data"""
        summary = classifier.get_movement_summary()
        
        assert summary['total_sequences'] == 0
        assert summary['average_intensity'] == 0.0
        assert summary['most_active_body_part'] == "none"
    
    def test_movement_summary_with_data(self, classifier, dancing_sequence):
        """Test movement summary with analyzed data"""
        classifier.analyze_sequence(dancing_sequence)
        summary = classifier.get_movement_summary()
        
        assert summary['total_sequences'] == 1
        assert summary['average_intensity'] > 0
        assert 'movement_distribution' in summary
        assert 'most_active_body_part' in summary
    
    def test_rhythm_detection_short_sequence(self, classifier, standing_sequence):
        """Test rhythm detection with short sequence"""
        rhythm = classifier.detect_rhythm_patterns(standing_sequence[:5], fps=30.0)
        
        assert 'has_rhythm' in rhythm
        assert 'estimated_bpm' in rhythm
        assert rhythm['estimated_bpm'] >= 0
    
    def test_rhythm_detection_long_sequence(self, classifier, dancing_sequence):
        """Test rhythm detection with adequate sequence"""
        rhythm = classifier.detect_rhythm_patterns(dancing_sequence, fps=30.0)
        
        assert 'has_rhythm' in rhythm
        assert 'estimated_bpm' in rhythm
        assert 'peak_count' in rhythm
        assert 'rhythm_consistency' in rhythm
    
    def test_find_peaks(self, classifier):
        """Test peak detection in signal"""
        # Create signal with obvious peaks
        signal = np.array([0, 1, 0, 1, 0, 1, 0, 5, 0, 1, 0])
        
        peaks = classifier._find_peaks(signal, threshold_percentile=50)
        
        assert len(peaks) > 0
        # Peak at index 7 (value=5) should be detected
        assert 7 in peaks
    
    def test_movement_smoothness_empty(self, classifier):
        """Test smoothness calculation with minimal data"""
        sequence = []
        smoothness = classifier.calculate_movement_smoothness(sequence)
        
        assert smoothness == 100.0  # Default for no data
    
    def test_movement_smoothness_smooth_motion(self, classifier, standing_sequence):
        """Test smoothness with smooth motion"""
        smoothness = classifier.calculate_movement_smoothness(standing_sequence)
        
        assert 0 <= smoothness <= 100
        # Standing should be very smooth
        assert smoothness > 80
    
    def test_movement_smoothness_jerky_motion(self, classifier):
        """Test smoothness with jerky motion"""
        sequence = []
        
        for i in range(10):
            # Create jerky movement (alternating positions)
            landmarks = np.random.rand(33, 3)
            if i % 2 == 0:
                landmarks[:, 0] += 0.2
            landmarks[:, 2] = 0.9
            
            pose = PoseKeypoints(
                landmarks=landmarks,
                frame_number=i,
                timestamp=i/30.0,
                confidence=0.9
            )
            sequence.append(pose)
        
        smoothness = classifier.calculate_movement_smoothness(sequence)
        
        assert 0 <= smoothness <= 100
    
    def test_movement_type_enum(self):
        """Test MovementType enum values"""
        assert MovementType.STANDING.value == "Standing"
        assert MovementType.WALKING.value == "Walking"
        assert MovementType.DANCING.value == "Dancing"
        assert MovementType.JUMPING.value == "Jumping"
        assert MovementType.CROUCHING.value == "Crouching"
        assert MovementType.UNKNOWN.value == "Unknown"
    
    def test_reset_classifier(self, classifier, dancing_sequence):
        """Test resetting classifier clears history"""
        classifier.analyze_sequence(dancing_sequence)
        assert len(classifier.movement_history) > 0
        
        classifier.reset()
        assert len(classifier.movement_history) == 0
    
    def test_multiple_sequence_analysis(self, classifier, standing_sequence, dancing_sequence):
        """Test analyzing multiple sequences"""
        metrics1 = classifier.analyze_sequence(standing_sequence)
        metrics2 = classifier.analyze_sequence(dancing_sequence)
        
        assert len(classifier.movement_history) == 2
        assert metrics1.intensity != metrics2.intensity
    
    def test_body_parts_defined(self, classifier):
        """Test that all body parts are properly defined"""
        assert 'head' in classifier.BODY_PARTS
        assert 'torso' in classifier.BODY_PARTS
        assert 'left_arm' in classifier.BODY_PARTS
        assert 'right_arm' in classifier.BODY_PARTS
        assert 'left_leg' in classifier.BODY_PARTS
        assert 'right_leg' in classifier.BODY_PARTS
        
        # Each body part should have landmark indices
        for part, indices in classifier.BODY_PARTS.items():
            assert len(indices) > 0
            assert all(0 <= idx < 33 for idx in indices)


if __name__ == "__main__":
    pytest.main([__file__, "-v"])