## Test the nex reader.
## 2014-03-17
## test1.nex is generated by the matlab script
## ~/langs/matlab/matpath/neuroexplorer/exampleSaveDataInNexFile.m
## require(testthat); test_file('./test_nex.R')

context("Check test1.nex")

x = readnex(system.file("examples", "test1.nex", package="sjemea"))
expect_equal(x$nvar, 5)


## check continuous var
Fs = 1000;
t = seq(from=1, to=5, by= 1 /Fs)
x2 = sin(2*pi*t*2)
##plot(t, x2)
contvar = x$conts[[1]]
expect_equal(contvar$name, 'sin2Hz')
expect_equal(contvar$timestamps, 1)
## tolerance: difference due to storing as 16 bit number
expect_true( all.equal( (contValues = contvar$data), x2, tolerance=5e-4))

## check neuron
neuron = x$neurons[[1]]
expect_equal(neuron$name, "neuron1")
expect_true(all.equal(neuron$timestamps, c(0.5, 0.9, 2.1, 2.3, 2.5)))

## check event spike train
event = x$event[[1]]
expect_equal(event$name, "event1")
expect_true(all.equal(event$timestamps, 10*(1:4)))

## check waveforms
wave = x$waveforms[[1]]
expect_equal(wave$timestamps, 1:2)
m <- matrix( c(-10, 0, 10, 20, 30,  -15, 0, 15, 25, 15), ncol=2)
expect_true(all.equal(wave$waveforms, m, tolerance=5e-4))

context("Check reading a nex file against a timestamp file")

f1 <- system.file("examples", "CS056P07R-MEME1.nex", package="sjemea")
f2 <- system.file("examples", "CS056P07R-MEME1.mct", package="sjemea")

s1 <- nex.read.spikes(f1, array.name='MCS_8x8_200um')
s2 <- sun.read.spikes(f2)
##s1 <- s2

## channel names are stored in different order.
expect_equal( sort(s1$channels), sort(s2$channels))

## this sum should be zero!
expect_equal(sum(sapply(s1$channels, function(n)
                        sum(abs( s1$spikes[[n]] - s2$spikes[[n]])))), 0)

##There are smalll differences in the mean firing rates because the two
##files have slightly difference start, end times (the .nex file uses
##the "proper" time of the recording).
##
## The two files also have slightly different beg,end times; the .nex file explicitly
## records this information, whereas sun.read.spikes  guesses it from spike times.
