Low-cost solution for rodent home-cage behaviour monitoring

In the current research on measuring complex behaviours/phenotyping in rodents, most of the experimental design requires the experimenter to remove the animal from its home-cage environment and place it in an unfamiliar apparatus (novel environment). This interaction may influence behaviour, general well-being, and the metabolism of the animal, affecting the phenotypic outcome even if the data collection method is automated. Most of the commercially available solutions for home-cage monitoring are expensive and usually lack the flexibility to be incorporated with existing home-cages. Here we present a low-cost solution for monitoring home-cage behaviour of rodents that can be easily incorporated to practically any available rodent home-cage. To demonstrate the use of our system, we reliably predict the sleep/wake state of mice in their home-cage using only video. We validate these results using hippocampal local field potential (LFP) and electromyography (EMG) data. Our approach provides a low-cost flexible methodology for high-throughput studies of sleep, circadian rhythm and rodent behaviour with minimal experimenter interference.


Introduction
Rodents have been widely used for understanding the aetiology, pathophysiology and pharmacology of neurological disorders, due in part to its similar brain architecture to primates and complex behavioural repertoire. Recent improvement of sophisticated tools used for measuring and manipulating brain activity, including optogenetics, two-photon imaging, wide-field mesoscale imaging, fibre photometry, mini endoscopes [1][2][3][4][5][6][7], as well as the availability of diverse transgenic lines and disease models, further incentivize their use in mechanistic studies [8][9][10][11]. Though non-human primates have been traditionally used to understand the neural mechanisms underlying executive function and higher-order cognition (such as decision making, motor skill execution, and perceptual discrimination), high-throughput experiments on non-human primates are not feasible because of cost and regulation constrains [12].
The organization of spontaneous home-cage behaviour of rodents reflects the interplay between multiple neurobiological processes and can provide a high-throughput phenotyping strategy without experimenter's intervention. In addition to the lack of observer bias in PLOS

Animals
All experiments were carried out on adult (20-30 g, age 4 month) wild type C57BL/6 mice, n = 10 (n = 5 for 24 hr recordings and n = 5 for 3 hr recordings (data not shown)). Mice were housed under standard conditions, in clear plastic cages under 12 h light, 12 h dark cycles. All the animals were either grouped or singly housed in Optimice (Animal Care Systems) homecages depending on the experimental protocol they were going through. Mice were given ad libitum access to water and standard laboratory mouse diet. All protocols and procedures were approved by the Animal Welfare Committee of the University of Lethbridge and were in accordance with guidelines set forth by the Canadian Council for Animal Care.

Surgery
Local field potential (LFP) and electromyography (EMG) electrodes were implanted in C57BL/6J mice anesthetized with isoflurane (2.5% induction, 1-1.5 maintenance). For hippocampal LFP recordings, a monopolar electrode made of Teflon coated stainless-steel wire (bare diameter 50.8 μm) was inserted in the brain (at coordinates -2.5mm AP, 2mm ML and 1.1mm DV from bregma), targeting the CA1 region. For EMG recordings, a multi-stranded Teflon-coated stainless-steel wire (bare diameter 127 μm) was inserted into the neck musculature using a 23-gauge needle. The reference and ground screws were placed on the skull over the cerebellum. The other end of electrode wires were clamped between two receptacle connectors (Mill-Max Mfg. Corp.) glued to the headpiece which in turn was secured to the skull using metabond and dental cement.

Electrophysiology
After electrode implantation, the animals were allowed to recover for 7 days before being habituated to the recording setup consisting of a home-cage without the lid placed in the middle of a large Plexiglas box used as secondary containment. During 24 hour LFP and EMG recordings, the electrophysiological tethers were connected to a motorized commutator (Neu-roTek Inc.

System architecture/hardware
Our system consists of a RaspberryPi (model 3B+), an infrared Picamera module (v2 NoIR), a wide-angle lens (AUKEY optics) and IR LEDs (DC12V SMD3528-300-IR (850nm)) placed on the home-cage lid to monitor the mouse behaviour (Fig 1). To make sure that the field of view covered most of the home-cage, we placed the camera lens on the home-cage lid through a custom made hole at its centroid and sealed it with hot glue. The Picamera module is connected to the Mobile Industry Processor Interface (MIPI) Camera Serial Interface (CSI) port on the RaspberryPi via a 15cm ribbon cable. The RaspberryPi further connects to the computer network either via a LAN cable or a Wi-Fi connection (Fig 1A-1D).

System interface
The remote user can view the live feed of the animal activity in the home-cage via a customized web interface (Fig 1E). In addition to live home-cage monitoring, it is possible to record video data to do off-line behavioural analysis. The web interface was created using PHP, JavaScript and CSS, which runs on an Apache web server on the Raspberry Pi and is based on Silvan Low-cost rodent home-cage monitoring URL tab within video source. This allows the user to simultaneously capture a video stream on a desktop computer and on the RPi. This implementation allows to schedule video recordings across multiple cages.

Offline behaviour analysis
To process the recorded videos, we implemented two offline algorithms for behavioural data analysis using OpenCV and Python (https://github.com/surjeets/Home-Cage-Python-and-MATLAB-Code), one for motion detection and another for animal tracking in the home-cage. Using these simple algorithms, we were able to demonstrate our approach by performing sleep/wake analysis with accuracy comparable to EMG recordings-based methods.

Motion detection, tracking and sleep/wake scoring
We use a simple and well-known computer vision method to detect motion and to track animals in the home-cage. To estimate the amount of motion in a video we extract the background [36][37][38][39] and take the difference between consecutive frames (frame differencing) [40]. For motion detection we implemented the algorithm shown in Fig 5 (Algorithm 1). First, the background is estimated by calculating the weighted mean of previous frames along with the current frame. In this way our system can dynamically adjust to the background even with the small changes in the lighting conditions. After this, frame differencing is performed by subtracting the weighted mean from the current frame to get a delta frame: The delta frame is then thresholded (assigning a constant value to all the pixels above the threshold and zero to the rest) to find regions in the image that contain substantial difference from the background. These regions correspond to "motion regions" in each video frame. Next, we calculated the area of each motion region in the thresholded delta frame. If these motion regions have an area larger than a threshold (the area that a mouse occupies in the visual field is assumed to be larger than a certain number of pixels), the motion is considered to be caused by the mouse (the motion region is shown with a rectangle around it Fig 6A). This threshold was set to avoid other objects (e.g. cables or bedding) or pixel fluctuations due to breathing being incorrectly detected as mouse motion. This tracking algorithm has been previously used for a Morris Water Task [11].
For animal tracking we implemented the algorithm shown in Fig 5 (Algorithm 2). This algorithm assumes that there is a high contrast between the mouse and the home-cage background. First, a Gaussian filter (size = 21, sigma = 3.5) is used to reduce noise in each video frame, then intensity-based thresholding is applied to segment the filtered image. Subsequently, to find the animal location, the contour with the largest area is detected, which, in the home-cage, is usually the animal. Finally, to calculate the trajectory of an animal, the centroids of the detected largest contour in each frame are connected (Fig 6B top panel). To validate these results, we compared our tracking Algorithm 2 with an open-source single mouse tracker in Icy software [41]. We show that the performance of the Algorithm 2 is equivalent to Icy ( Fig  6B bottom panel). These trajectories can be used to calculate the distance travelled by the animal or to visualize its spatial occupancy. We use the centroid of the motion-detected region to track the animal position in the home-cage ( Fig 6B). These trajectories can be used to calculate the distance travelled by the animal or to visualize its spatial occupancy. Finally, we use our motion measure (motion signal) to predict when the animal is sleeping or awake. For sleep/wake scoring, we filtered the video-based motion signal below 0.1 Hz using a zero-lag Chebyshev filter and detrended using 10 sec windows with 5 sec overlap (using the locdetrend function from the Chronux Toolbox) to remove the variations in the baseline across light and dark cycle. The result was then rectified and integrated using 20-sec moving windows. Next, this signal was thresholded using its 50-60 percentile to classify waking and sleep periods. If the signal was below the threshold for at least 40 sec, the animal was assumed to be asleep, or awake otherwise. This threshold was chosen based on the optimal length based on the accuracy of sleep detection (Fig 9A). A similar criterion was reported in [29,30,42]. For LFP/EMG based sleep/wake scoring, hippocampal LFP was filtered between 0.2 and 100 Hz and down sampled to 200 Hz. Delta power (0.5-4 Hz) and theta power ratio (6-10 Hz) were calculated for the LFP. State was scored as sleep when EMG RMS signal was smaller than its 50-60 percentile and Delta power value above its 20-30 percentile or theta power ratio was above 0.3-0.4.
Sleep/wake scoring based on only EMG signals was also done by filtering the raw EMG activity between 90 Hz and 1000 Hz and then rectifying and integrating it using 20-sec moving windows. A state was scored as sleep when the EMG signal was smaller than its 50-60 percentile, otherwise it was classified as awake [29]. This EMG based state scoring was compared to the LFP/EMG-based state scoring and the overlap of two scoring signals was calculated, which turns out to be 99.01 ± 0.27%. Thus, for the remaining of this paper, we use only EMG based sleep/awake scoring. The accuracy of video-based classification was calculated by counting the amount of time the video-based scoring was the same as the EMG-based scoring divided by

Camera settings and temporal precision evaluation
In some behavioural tasks (e.g. reach and grasp, grooming behaviour) it is very important to acquire the data at high frame rates. With the Picamera camera board V2.1 (8MP Sony Low-cost rodent home-cage monitoring IMX219 sensor), it is possible to record video @ 30 fps in full resolution (no shutter lag and simultaneous recording), and also @120 fps if using the 2 × 2 analogue binning mode (which is a clocking scheme to collect the charge of a 2x2 CCD pixel area). We evaluated the temporal precision of the frame acquisition of the RPi Camera by comparing the average number of dropped frames and variation in interframe intervals (IFIV) in a video at different framerates (30, 60, 90 and 120 fps) and recording formats: h264, which is the compression standard MPEG-4 AVC and raw YUV, which is an uncompressed bitmap data format. In order to quantify the temporal precision of the frame acquisition of the Picamera, we recorded the time stamps of each frame acquisition into a csv file using the picamera python library [43]. To evaluate the time difference in simultaneous frame acquisition, multiple RPis were simultaneously triggered with an external square TTL pulse. On another RPi (besides the ones being triggered), we monitored the transition (high or low) of selected GPIO pins in real-time that corresponded to external trigger pulses that represent the start and stop times of video recording (Fig 7) using piscope [44]. The timestamps of acquired frames on different RPis were later aligned offline to quantify any temporal differences in the acquisition. Table 1 shows that the jitter in the frame acquisition on different RPis is in the order of few microseconds.

Off-line alignment of the video with additional signals
To align the video recordings to LFP or EMG signals, we keep track of the times when the video acquisition begins and ends in the same acquisition system that records the electrophysiological signals. We do this by setting a TTL signal (Transistor-Transistor Logic 5V) to HIGH in one of the GPIO pins of the RPi when the video acquisition starts and set to LOW when the acquisition terminates. Additionally, we also record the times when each video frame is acquired (see https://picamera.readthedocs.io/en/release-1.13/api_camera.html).

High frame rate acquisition
The temporal precision and resolution required for the video recordings depends largely on the behaviour we are interested in. For example, if one is interested in skilled reaching or play behaviour this might require to record video at higher resolution and frame rates than if we are interested in monitoring the general activity in the home-cage. Since the temporal precision of the video varies depending on the settings we used, we compared some of the file formats and recording settings in this system. We observed that there are dropped frames when we save the video in raw YUV format above 30 fps at full resolution. This situation gets worse when the frame rate augments. For example, at 90 fps we can only achieve a frame rate of 77.61 ± 4.59 fps with a lag of 54.45 ± 31.78 ms between consecutive frames (Table 1). In contrast, using the H264 encoding we were able to record at 120 fps with no missed frames (120.54 ± 0.00 fps) and almost no lag between frames (2.44 ± 0.46 μs).

Multiple camera synchronization
The system presented here assumes that a single camera is placed on the home-cage providing a top-down view. However, it is possible to use more than one camera if they can be synchronized [45]. To test this, we evaluated the temporal alignment of two cameras recording video synchronously (see Methods). We found that the temporal difference between the two cameras is in the order of less than ten microseconds when using H264 encoding at 320 x 240 pixel resolution and frame rates from 30-120 (last column of Table 1 and Fig 7).

Sleep-wake state classification
To classify the behaviour of the mouse into sleep and wake states, we applied the following criteria: if the mouse was not moving (according to our motion detection algorithm) for more than 40 sec, we assumed that it was asleep, otherwise we assumed it was awake (see Methods and Fig 5). To validate this classification, we simultaneously recorded hippocampal LFP and EMG signals and compared them to our video-only based classification (Fig 8A and 8B). Our Table 1 Low-cost rodent home-cage monitoring sleep-wake classification was highly correlated to the 24 hr EMG recordings (90.52% ± 0.4 accuracy). Similar results were obtained for shorter recordings (data not shown). The highthroughput methodology for sleep-wake monitoring presented here can be easily incorporated into any existing phenotyping test battery, e.g. circadian studies (Fig 8B). For example, our 24 hour sleep/wake classification algorithm shows that animals were more active during the dark cycle than during the light cycle (Fig 8C and 8D, n = 5, one-way anova, Bonferroni correction, F (1,9) = 12.03, p = 0.0085), a trend that is observed in commercial solutions that use running wheels for phenotyping circadian rhythms in mice [42].

Variance in interframe interval (IFIV) for h264 encoded
We chose a 40 sec threshold to determine the behavioural state of the animal based on the optimal accuracy of our method compared to the EMG based classification (Fig 9A). A very similar finding is reported in [30]. The performance of our method decreased when using shorter windows thresholds because the mouse could be immobile for very short periods of Low-cost rodent home-cage monitoring Low-cost rodent home-cage monitoring time but not asleep. Analogously, when using long windows, the accuracy drops because mice can sleep during short periods (see Discussion). We found that the estimated distributions of the duration of the detected sleep events using the video-based and EMG based methods is generally similar. However, they differ when the durations of the events are small, close to 1-2 sec or between 10-30 seconds (Fig 9B). In addition, the accuracy of the video-based method changes with respect to the noise in the motion detection signal, which in turn is modulated (in part) by the smoothening of this signal (see Methods). When the video-based motion detection signal was smoothened using very short windows, small motion fluctuations could be incorrectly detected as wakening. The smoothening over longer windows improves the correlation of EMG and video signals up until an asymptotic value (Fig 9C).

Discussion
When studying complex behaviour, experimental designs that require the experimenter to move the animal from its home-cage environment to an unfamiliar apparatus (novel environment) are relatively disruptive, time-and labour-consuming and require additional laboratory space. This disruption may influence behaviour, general well-being, and metabolism of the animal, affecting the phenotypic outcome, even if the data collection method is automated, therein possibly creating spurious findings. Therefore, monitoring the animals in their homecage has several advantages. Though there are already open-source and commercial solutions available to monitor animal behaviour [25,[47][48][49][50][51][52][53], they are usually difficult to construct, require a new infrastructure/space, and are expensive. Conversely, we propose a video-based system that is composed of off-the-shelf components and designed to be simple and easily integrated in existing home-cage setups with minimal modifications for remote behaviour monitoring. Such a system can be used for short-term welfare assessment (e.g. post-surgery monitoring) by enabling 24 hr monitoring, even in the dark phase where welfare assessment without disturbance to the cage is difficult and subjective. Further, video data collected with this system can be used to classify sleep-wake states of an animal in the home-cage using video-based tracking. The simple video-based tracking algorithm that we use has an accuracy above 90% when compared with tethered EMG recordings for sleep-wake state classification. This algorithm is based on the quantification of motion during a period to determine if the animal is awake or asleep. We found that the highest accuracy of the sleep/wake classification is reached when the time window threshold for no motion period to be considered as sleep is close to 40 secs compared to the gold standard EMG based classification. The performance of our classification method mainly depends on two factors: the amount of time we use as a threshold to assume the animal is asleep and the amount of noise (or smoothness) in the motion detection signal. When considering shorter time windows as a threshold, this method incorrectly classifies periods of quiet wakefulness as sleep. Analogously, when the window is too large, this method incorrectly classifies long periods of sleep that contain small movement as wake periods (e.g. twitches) (Fig 9A). The smoothness of the motion detection signal is determined (in part) by the length of the smoothening window. If the window is small, the motion detection signal contains small changes in the home-cage (illumination, cables, bedding, etc), that can cause the algorithm to incorrectly detect these changes as the mouse being awake. We can alleviate this problem by extending the smoothening signal to reach an asymptotic performance compared to the EMG-based classification (Fig 9C). This has been previously reported in similar video-based sleep/wake classification approaches [29,30]. Although these results show that our video-based algorithm reliably determines whether the animal is awake or asleep (compared to an EMG based algorithm), for a more in depth classification of sleep into Rapid-Eye Movement (REM) and non-Rapid Eye Movement (NREM) sleep states, our video analysis should be complemented with more advance computer vision techniques [54] or additional brain signals.
The proposed video-based monitoring/tracking methods has several advantages and limitations, one advantage is in accurate animal tracking due to the system's high spatial (in the order of millimeters) and temporal resolution (in the order of milliseconds). In contrast, a home-cage RFID system with an array of 18 RFID sensors (ID20LA) has a spatial resolution of 5 cm and a temporal resolution of 1Hz [24]. One disadvantage of our system is that it can only track one animal at a time due to the potential high similarity between multiple mice (e.g. same fur colour and shape) [49], compared to the multiple animal tracking capability of an RFID based system. However, RFID (and video-hybrid) systems are highly specialized, difficult to setup and expensive [25,53,55,56]. A potential approach to improve video-based tracking methods is to extract high level features from each animal to identify every individual using machine learning [57,58]. But, such algorithms need to be highly calibrated and tested to provide reliable results. Another possible limitation of our system is the processing power of the RPi if extensive online video processing is required. For example, streaming live video over a network and simultaneously performing object recognition on the RPi in real time might result in frame dropping. Despite these limitations, the system has several advantages for large scale monitoring of rodents, added to the fact that it can be easily integrated with any available rodent cage-rack system. Further, a user can remotely monitor day/night activity of animals in multiple cages, from virtually anywhere via the web interface which can be applied not only for research but animal care and husbandry.
Although this manuscript presents motion-based classification for sleep/awake behaviour of a single mouse, a user can still collect data for multiple animals in the home-cage and analyze it using more complex algorithms than the ones presented here.

Conclusions
In this paper, we present a low-cost home-cage reliable behavioural monitoring system that can be easily adapted and extended to a large variety of conditions and pre-existing experimental setups. We demonstrated that our system can be used to study natural sleep patterns of mice in their home-cage using only video. Due to its suitability for remote behaviour monitoring and minimization of experimenter bias at low-cost, systems like the one presented here, can become a useful tool for high-throughput data collection and behavioural analysis of rodents in their home-cage.