Introduction

Behaviour in the novel object recognition task

The novel object recognition task (NOR) was initially developed as a single-trial paradigm to assess spatial memoryA. Ennaceur (2010). The task takes advantage of the natural tendency of rodents to investigate new objects—which requires them to retain a memory of the old objects in order to make that distinction. While typically scored by the amount of time spent investigating the old and new objects, the rich set of metrics provided by Rtrack may provide a more nuanced insight into the behaviour of the animals in this task.

Using Rtrack for the novel object recognition task

The Rtrack package aims to be an easy-to-use interface for data management and analysis of spatial tracking data. This workflow describes analysis of data from the novel object recognition task. Although NOR is a very simple paradigm, experiments often accumulate many tracks each with associated metadata. Managing all these data can be overwhelming and lead to confusion and potential errors. Unfortunately, due to the potential complexity of the experiments and the range of computational abilities of the researchers (who are typically experimentalists with little background in programming or data analysis), many existing software solutions have not found their way into laboratory workflows. The Rtrack package is built on the popular and ubiquitous R platform which runs on all commonly-used operating systems, is free and open-source (so that the cost of licencing is not a limitation) and which integrates well into existing analysis environments. The data preparation involves exporting path data from the acquisition software used (outputs from a number of software platforms are supported and more are being added), defining the arenas in which the experiment was performed and creating a spreadsheet with information about each track. Once the data and information spreadsheet have been prepared, the actual analysis runs in very little time (processing for 1000 tracks takes under a minute on a typical modern computer) and the results are available in R for further analysis, or can be exported for analysis using other software if desired. Publication-quality graphs can be generated and exported directly from the functions in Rtrack. In addition, the raw path data can be saved to a standardised format to allow data sharing and to enhance reproducibility.

About the example experiment

The data provided together with this vignette are from a published study (Zocher et al. 2020) where mice were housed in three different environments (either standard laboratory cages, STD; enriched cages with many cage mates and toys, ENR; or enrichment housing followed by a return to standard cages; ENR-STD). Mice were tested over three sessions, of 5 min each in a 60 × 60 cm field, where they were presented with two types of object (called ‘R’ and ‘Q’ for brevity). For the first two sessions, ‘Habituation’ and ‘Acquisition’, animals were exposed to two similar objects. In the third trial, ‘Test’, one of the objects was replaced with a different object type. The order and position of the two object types was varied, following the protocol in Table 1, to ensure that there was no inherent preference for either the object type or the position in the arena.

Table 1. design of the experiment with balanced novel object combinations. Novel objects are shown in bold. Experimental design. 

Quick start example

In this example, an archived experiment (raw data that has been saved in the portable trackxf format) is read in directly from a URL. The experiment is reconstructed, strategies calculated and plotted for a visual overview. To explore the further functionality of the package, please work through the tutorial examples below.

experiment = Rtrack::read_experiment("https://rupertoverall.net/Rtrack/examples/NOR_example.trackxf")
#>     Restoring archived experiment.
#>     Processing tracks.
Rtrack::plot_variable("path.length", experiment = experiment, factor = "Group",
    las = 1)

Preparing the input files

Arena descriptions

An ‘arena’ is a description of the novel object recognition apparatus and the recording parameters for each session. This means that any change in layout of the field (for example, if the camera position is moved) and each different combination of objects will require a separate arena file. The description files are simple and consist of only a few lines:

  1. The experiment type. For the novel object recognition task, this will always be nor.
  2. The time units. The units in which the timestamps are measured. Each x,y coordinate pair in the path data is associated with a timestamp. The frequency of measurement may be in the range of milliseconds, seconds, hours or even days—depending on the type of experiment. This can either be a text code (‘s’ = seconds, ‘h’ = hours etc.)1 or a conversion factor to seconds (1 = seconds, 0.0002777778 = hours (a second is 1/3600 of an hour) etc.).
  3. The bounds of the arena (i.e. the dimensions of the novel object recognition apparatus). This line has 9 components2, each is separated by a space.
    1. The shape. For the novel object recognition task this is ‘square’.
    2. The x coordinate of the first corner of the field as it is seen in the video.
    3. The y coordinate of the first corner of the field as it is seen in the video.
    4. The x coordinate of the second corner of the field.
    5. The y coordinate of the second corner of the field.
    6. The x coordinate of the third corner of the field.
    7. The y coordinate of the third corner of the field.
    8. The x coordinate of the fourth corner of the field.
    9. The y coordinate of the fourth corner of the field.
  4. The definition of the first object. This can be either a training object, in which case it is called object.1 or a novel object, in which case it is called novel.object.1. This information allows Rtrack to calculate time spent at the novel object(s)—an essential part of this experimental paradigm.
  5. The definition of the second object. This is called object.2 or novel.object.2 as for the first object. It does not matter which of the two objects is called the first or second, as long as this is consistent throughout the experiment.

Both of the objects can be either a square (defined as above) or a circle (where three numbers are required: the x and the *y coordinates of the centre of the circle as well as the radius).

The units for the x and y coordinates do not need to be specified, but these must be the same units used in the raw track files.

For example, the description for one of the arenas in the example file (‘Arena_Test_R-RQ_1’; for a novel object trial) is:

type = nor
time.units = s
arena.bounds = square -2.2 128.16 60.22 119.72 54.80 58.75 -7.7 64.52
object.1 = square 11.35 96.08 4
novel.object.2 = square 36.9 92.9 4

Definition of the arena zones.

Assembling the experiment description

The key task before analysing an experiment is to gather together all the information you need for the analysis. This is always necessary for any analysis, and is always a nasty task. Nevertheless, Rtrack uses a straightforward spreadsheet format to make this task less tedious and less confusing.

Several columns are required, these all must begin with an underscore ’_’:

  • _TrackID is a unique identifier for each track. The easiest way to do this is just write “Track_1” in the first cell and drag to fill the whole column using Excel’s autofill feature.
  • _TargetID is a unique identifier for each subject. Here you should put the animal ID tags, blinded patient IDs or whatever identifies the subjects.
  • _Day indicates the day of the experiment. Use ordinal numbers for the days (e.g. 1 for the first experimental day).
  • _Trial indicates the trial number. Typically there will be multiple trials per day, but this is not necessary. The field is still required even if a one-trial-per-day paradigm is used. These also need to be numbers.
  • _Arena is the name of the arena description file that applies to this track. This is a file path and is relative to the project directory (which is defined by project.dir in the read_experiment function. See the note on relative paths below.
  • _TrackFile is the name of the arena description file that applies to this track. This is also a file path and is relative to the data directory (which is defined by data.dir in the read_experiment function. See the note on relative paths below.
  • _TrackFileFormat is the format in which the raw track data is stored. See the package documentation (run ?Rtrack::identify_track_format) for a list of the supported file formats.

You can also add any other columns of factors. In the example, there is a factor ‘Group’, which records the type of housing the animals were in prior to testing.

An excerpt from an example open field experiment description spreadsheet. 

Note: Relative paths

If your analysis will be done in the same directory as the raw data files are in, then you can ignore this comment. If, however, your raw data are large, you may have them stored on an external disc or network volume. By specifying the data.dir parameter, you can keep these raw data anywhere you like and even move them without having to update the experiment description spreadsheet. All file paths in the experiment description are relative to the data.dir directory.

Process a single track

Reading in data

Look at one track to get a feel for the workflow. Firstly an arena definition must be read in. The resulting object has the class Rtrack_arena.

arena = Rtrack::read_arena("NOR_example/Arena_Test_R-RQ_4.txt")

There are many different raw data formats. The format of the data files depends on the software they were recorded with, the locale and (sometimes) the computer system they were recorded with. Each format supported by Rtrack has a code, which must be given to the read_path function. Run the function identify_track_format with one of the raw track files to help you determine the appropriate format code for your data.

track.format = Rtrack::identify_track_format("NOR_example/Data/Trial_97_Arena_4.txt")
#> ✔ This track seems to be in the format 'ethovision.xt.csv2'.

The tracks for the example are in the format ethovision.xt.csv2, we need to pass this information on to the reader function. The arena is also required for reading in the path (to provide calibration information).

path = Rtrack::read_path("NOR_example/Data/Trial_97_Arena_4.txt", arena, id = "Example track",
    track.format = "ethovision.xt.csv2")

Extracting path metrics

The path (of class Rtrack_path) can now be used to collect a range of metrics. This results in a list of various secondary variables which can be used for plotting and analysis.

metrics = Rtrack::calculate_metrics(path, arena)

Plotting the path

The path (the coordinates of the animal in the arena during the experiment) can be plotted. This representation shows the path as a black line and some informative areas of the field (called ‘zones’ by Rtrack; the zones in an open field experiment are the wall, the corners and the centre.) in shades of blue.

Rtrack::plot_path(metrics)

Plotting a density heatmap

Paths can also be plotted as a density heatmap.

Rtrack::plot_density(metrics)

Feel free to play with the colours (just please don’t use a garish ‘rainbow’ scheme). The colour scales are best defined using the ‘colorRampPalette’ function.

Rtrack::plot_density(metrics, col = colorRampPalette(c("yellow", "orange", "red"))(256))

You can use any of the colour definitions provided in R, and reducing the number of colours in the palette gives a contour effect.

Rtrack::plot_density(metrics, col = colorRampPalette(c(rgb(1, 1, 0.2), "orange",
    "#703E3E"))(8))

Bulk processing a whole experiment

Usually, an experiment will consist of multiple subjects/animals and possibly more than one trial per subject. Running each track separately by hand as we have done above would be tedious and error-prone. Rtrack allows you to set up a batch processing workflow to make this task easier. A description of the experiment is filled out with all the required data and passed to to the read_experiment function to be processed automatically.

Reading in experiment data and metadata

The experiment information is read in using metadata in a spreadsheet. See ‘Preparing the input files’ above for details on how to properly construct this file. The raw data are read in, metrics calculated and returned in a list object of class Rtrack_experiment. This is the most processor-intensive part of the workflow and an experiment will typically consist of many hundreds of tracks. Depending on the size of the experiment and the speed of your computer, this step may take several minutes (a friendly progress bar will let you know if there is time for a coffee at this step—the software is fast though, so it may be an espresso!).

experiment = Rtrack::read_experiment("NOR_example/Experiment.xlsx", data.dir = "NOR_example/Data")
#>     Processing tracks.

Parallel processing

By default, processing the experiment will run as one single process3 but is trivial to parallelise this potentially time-consuming step (if perhaps you have run out of coffee). Rtrack version 2 will take care of parallelising the code and all you need to do is adjust the threads parameter. The simple option is to specify threads = 0, which tells Rtrack to use as much processing power as it can. Now try running the read_experiment code again and see if this makes a difference in processing time.

experiment = Rtrack::read_experiment("NOR_example/Experiment.xlsx", data.dir = "NOR_example/Data",
    threads = 0)

Analysis of selected metrics

Once the experiment object has been constructed, you can use this to start analysing the results. Individual metrics might be of interest for separate analysis; for example, the number of time each subject crossed the centre zone—traditionally an indicator of boldness in mice The built-in plotting function allows you to quickly inspect your data and includes the ability to split the results by a grouping factor—here the housing group.

Rtrack::plot_variable("latency.to.object.vicinity", experiment = experiment,
    factor = "Group")
title(main = "Crossings of the centre zone")

The ‘summary.variables’ element shows all the metrics available

experiment$summary.variables
#>  [1] "path.length"                      "total.time"                      
#>  [3] "velocity"                         "immobility"                      
#>  [5] "coverage"                         "distance.from.object"            
#>  [7] "distance.from.novel.object"       "roaming.entropy"                 
#>  [9] "latency.to.object.vicinity"       "latency.to.novel.object.vicinity"
#> [11] "time.in.wall.zone"                "time.in.corner.zone"             
#> [13] "time.in.object.vicinity"          "time.in.novel.object.vicinity"   
#> [15] "object.vicinity.crossings"        "novel.object.vicinity.crossings"

Bulk density maps

It is also possible to create a density heatmap for many tracks together.

Rtrack::plot_density(experiment$metrics)
#> Warning in Rtrack::plot_density(experiment$metrics): Multiple arena definitions
#> have been used. A merged plot may not make sense.

The warning tells us that there are data from tracks using different arenas in our ‘metrics’ list so this plot does not make sense.

However, it might be interesting to look at all the novel object tracks from one arena type and compare this between the different housing environments.

par(mfrow = c(1, 3))
rrq.std.metrics = experiment$metrics[experiment$factors$`_Arena` == "Arena_Test_R-RQ_4" &
    experiment$factors$Group == "STD"]
Rtrack::plot_density(rrq.std.metrics, title = "R-RQ STD")
rrq.enr1.metrics = experiment$metrics[experiment$factors$`_Arena` == "Arena_Test_R-RQ_4" &
    experiment$factors$Group == "ENR1"]
Rtrack::plot_density(rrq.enr1.metrics, title = "R-RQ ENR1")
rrq.enr2.metrics = experiment$metrics[experiment$factors$`_Arena` == "Arena_Test_R-RQ_4" &
    experiment$factors$Group == "ENR2"]
Rtrack::plot_density(rrq.enr2.metrics, title = "R-RQ ENR2")

Plotting all paths

This next block of code produces a large PDF (one page for each track) including each of the paths titled with the track ID. This can be used to check everything is the way it should be and to detect any possible recording or processing problems.

pdf(file = "Results/NOR_path_plots.pdf")
for (i in 1:length(experiment$metrics)) {
    Rtrack::plot_path(experiment$metrics[[i]], title = experiment$metrics[[i]]$id)
}
dev.off()
#> agg_png 
#>       2

Exporting analysis results

As a data.frame

To get a data.frame containing all the experiment metadata, metrics and strategies for each track, it is possible to export the experiment results. The function export_results is really intended for saving to a file, but if no filename is given, then you get the data as a data.frame.

results = Rtrack::export_results(experiment)

Writing to file

The results can be written to file in any one of several formats. The format will be determined from the filename extension. The default, and most likely to be used in an experimental workflow, is the Excel ‘.xlsx’ format.

Rtrack::export_results(experiment, file = "Results/NOR_results.xlsx")

An excerpt from an Excel file containing exported results. 

Also supported are tab-delimited text (recommended for maximum portability; file extension can be any of ‘.tsv’, ‘txt’ or ‘.tab’) and comma-delimited values (‘.csv’, or ‘.csv2’ where decimal commas are needed). You can actually use any file extension, but it will be written in that case as tab-delimited text and you’ll get a warning.

Exporting a subset of the results

It is also possible to only export some of the results. To do this, just specify the indices or names of the tracks you would like to export.

# Export just the data for the standard-housed animals.
std = experiment$factors$Group == "STD"
Rtrack::export_results(experiment, tracks = std, file = "Results/NOR_results_STD.xlsx")

It is worthwhile noting that the order of the exported results is also determined by the order of the values given to the tracks parameter.

results = Rtrack::export_results(experiment)  # Get the results as a data frame.
ordered = order(results$path.length, decreasing = TRUE)  # Then sort by path length (highest to lowest).
Rtrack::export_results(experiment, tracks = ordered, file = "Results/NOR_results_ordered.xlsx")

Saving the experiment

As an RData archive

The entire Rtrack_experiment object can easily be saved and reloaded into a later R session. The .RData format is a compressed version of the Rtrack_experiment object and requires very little space.

save(experiment, file = "Results/experiment.RData")

Load the file again (not necessary in this session, but the following line demonstrates the command needed to read in the .RData file we just created).

load("Results/experiment.RData")

As a standardised “trackxf” archive

We have also developed a format for saving the raw data in a way that it can be accessed by other software. This allows sharing with other people and archiving in a way that is more likely to be readable in the future. The command below will create a file with the extension .trackxf—you do not need to add the extension though (in fact it is better not to) as Rtrack will take care of naming the file correctly.

Rtrack::export_data(experiment, file = "Results/NOR_example")
#>     Creating trackxf archive.
#>     Compressing trackxf archive.

Data saved in this way can be read back into Rtrack using the read_experiment function (with the format trackxf, although Rtrack will work this out for you). Because only the raw data are saved in trackxf, recreating an experiment in this way will re-calculate all of the Rtrack-specific metrics.

recreated.experiment = Rtrack::read_experiment("Results/NOR_example.trackxf",
    threads = 0)
#>     Restoring archived experiment.
#>     Initialising cluster.
#>     Processing tracks using 8 threads.

This experiment object recreated from the saved trackxf file is (almost) identical to the original object. Only the export information will obviously be different.

# If we set 'export.note' back to empty, then the objects are the same.
recreated.experiment$info$export.note = experiment$info$export.note
all.equal(recreated.experiment, experiment)
#> [1] TRUE

References

Ennaceur, A. 2010. “One-Trial Object Recognition in Rats and Mice: Methodological and Theoretical Issues.” Special Issue on Episodic Memory 215 (2): 244–54. https://doi.org/10.1016/j.bbr.2009.12.036.
Ennaceur, Abdelkader, and Kamel Meliani. 1992. “A New One-Trial Test for Neurobiological Studies of Memory in Rats. III. Spatial Vs. Non-Spatial Working Memory.” Behavioural Brain Research 51 (1): 83–92. https://doi.org/10.1016/S0166-4328(05)80315-8.
Zocher, Sara, Susan Schilling, Anna N Grzyb, Vijay S Adusumilli, Jadna Bogado Lopes, Sandra Günther, Rupert W Overall, York Winter, and Gerd Kempermann. 2020. “Early-Life Environmental Enrichment Generates Persistent Individualized Behavior in Mice.” Science Advances 6 (35): eabb1478. https://doi.org/10.1126/sciadv.abb1478.

  1. The full range of supported codes is: ‘us’ or ‘micros’ for microseconds, ‘ms’ for milliseconds, ‘s’ for seconds, ‘min’ for minutes, ‘h’ for hours, ‘d’ for days and ‘y’ for years.↩︎

  2. There are actually some other ways of describing the field shape, but this is the preferred method.↩︎

  3. modern computers can multi-task and run several jobs side-by-side at the same time. These separate processes are called ‘threads’ in computer terminology. Running multiple parallel threads can make make optimal use of the multiple ‘cores’ of your CPU (the microchip at the heart of your computer) and allow programs to process data more quickly.↩︎