Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@

# CHANGES IN GGIR VERSION 3.3-?

- Part 1: Reduced time and allocation overhead in `g.calibrate()` by avoiding full raw-block matrix copies, reducing epoch-mean temporaries, preparing only populated feature rows, and reusing matrix inputs with per-axis transforms in the calibration fit. Feature buffers now start with one day of epochs and grow as needed. Epoch SDs use `vapply()` with the same `sd()` calculation; calibration thresholds, cumulative-sum arithmetic and fitting/stopping rules are retained.

- Part 1: Faster rolling-median metric extraction using R's existing `runmed()` directly for complete data. Fixed loss of smoothing when block length is not divisible by the downsampling step (including typical 75 Hz blocks), corrected trailing padding to use the final window median, and preserved valid zero medians at block edges. Angle and rolling-median metrics can change as a result of these fixes.

- Part 5: Nap time (dur_day_nap_min) is now mutually exclusive with the rest of total outputs. #1558

- Documentation: clarified how bout tolerance for gaps works, added Crotti cutpoint, and clarified GENEActiv light sensor calibration. #1531, #1536, #1544
Expand Down
49 changes: 15 additions & 34 deletions R/g.applymetrics.R
Original file line number Diff line number Diff line change
Expand Up @@ -87,43 +87,24 @@ g.applymetrics = function(data, sf, ws3, metrics2do,
data_processed[, i] = signal::filter(coef, data[,i])
}
} else if (filtertype == "rollmedian") {
# rollmed = function(x, sf) {
# winsi = round(sf * 5)
# if (round(winsi/2) == (winsi/2)) winsi = winsi + 1
# xm = zoo::rollmedian(x, k = winsi, na.pad = TRUE)
# xm[which(is.na(xm[1:1000]) == TRUE)] = xm[which(is.na(xm[1:1000]) == FALSE)[1]]
# return(xm)
# }
rollmed = function(x, sf) {
stepsize = max(c(floor(sf / 10), 1))
newsf = ifelse(test = stepsize > 1, yes = 10, no = sf)
stepsize = max(floor(sf / 10), 1)
newsf = if (stepsize > 1) 10 else sf
winsi = round(newsf * 5)
if (round(winsi/2) == (winsi/2)) winsi = winsi + 1
if ((winsi %% 2) == 0) winsi = winsi + 1
xm = zoo::rollmedian(x[seq(1, length(x), by = stepsize)],
k = winsi, fill = c(0, 0, 0), na.pad = FALSE)
# replace zeros:
S2check = max(c(sf * 60, 1000))
# head
xm[which(xm[1:S2check] == 0)] = xm[which(xm[1:S2check] != 0)[1]]
# tail
LN = length(xm)
S2check = min(LN-1, S2check)
xm_tail = xm[(LN - S2check):LN]
lastvalue = xm_tail[which(xm_tail != 0)][1]
if (length(lastvalue) == 0) lastvalue = xm[which(xm != 0)][1]
xm_tail[which(xm_tail == 0)] = lastvalue
xm[(LN - S2check):LN] = xm_tail
# repeat values to get back to original sample rate
xm = rep(xm, each = stepsize)
LN = length(xm)
LX = length(x)
if (LN > LX) {
xm = x[1:LX]
} else if (LN < LX) {
xm = c(xm, rep(xm[LN], LX - LN))
if (winsi %% 2 == 0) winsi = winsi + 1
sampled = x[seq(1, length(x), by = stepsize)]
if (length(sampled) >= winsi && !anyNA(sampled)) {
# zoo::rollmedian uses runmed internally. Calling it directly avoids
# constructing zoo objects, indices and padding for each axis/block.
xm = stats::runmed(sampled, k = winsi, endrule = "constant")
} else {
xm = zoo::rollmedian(sampled, k = winsi,
fill = list("extend", 0, "extend"))
}
return(xm)
# Extend only the padded edges, retaining valid zero medians. Repeat
# to the original sample rate and trim a possible partial final step.
xm = rep(xm, each = stepsize)
return(xm[seq_along(x)])
}
data_processed = data
for (i in 1:3) {
Expand Down
81 changes: 52 additions & 29 deletions R/g.calibrate.R
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,27 @@ g.calibrate = function(datafile, params_rawdata = c(),
#-----------------
# Define local functions:
rollMean = function(x, fs, epochSize) {
x = cumsum(c(0, x))
select = seq(1, length(x), by = fs * epochSize)
y = diff(x[round(select)]) / abs(diff(round(select)))
# Keep the cumulative-sum arithmetic, but prepend zero only after
# selecting epoch boundaries instead of copying the full input vector.
select = round(seq(1, length(x) + 1, by = fs * epochSize))
y = diff(c(0, cumsum(as.numeric(x))[select[-1] - 1])) / abs(diff(select))
return(y)
}
rollSD = function(x, sf, epochSize) {
dim(x) = c(sf * epochSize, ceiling(length(x) / (sf * epochSize)))
y = apply(x, 2, sd)
# Avoid apply's matrix permutation/copy while retaining sd's calculation.
y = vapply(seq_len(ncol(x)), function(i) sd(x[, i]), numeric(1))
return(y)
}
transformAxes = function(x, offset, scale, temperature, tempoffset) {
# Match scale()'s order of operations without its sweep()/aperm() arrays.
out = x
for (axis in seq_len(ncol(x))) {
out[, axis] = (x[, axis] + offset[axis]) / (1 / scale[axis]) +
temperature[, axis] / (1 / tempoffset[axis])
}
return(out)
}
#-----------------
use.temp = temp.available = TRUE

Expand Down Expand Up @@ -72,7 +83,9 @@ g.calibrate = function(datafile, params_rawdata = c(),

#creating matrices for storing output
S = matrix(0,0,4) #dummy variable needed to cope with head-tailing succeeding blocks of data
NR = ceiling((90*10^6) / (sf*calibEpochSize)) + 1000 #NR = number of rows to initialise features matrix with
# Features are 10-second epochs, independent of the raw sampling rate.
# Start with one day and expand below for larger chunks/longer recordings.
NR = 24 * 3600 / calibEpochSize

# setting size of blocks that are loaded (too low slows down the process)
# the setting below loads blocks size of 12 hours (modify if causing memory problems)
Expand Down Expand Up @@ -127,49 +140,57 @@ g.calibrate = function(datafile, params_rawdata = c(),
options(warn = 0) #turn on warnings
#process data as read from binary file
if (length(accread$P) > 0) { # would have been set to zero if file was corrupt or empty
data = as.matrix(accread$P$data[,which(colnames(accread$P$data) %in% c("x", "y", "z", "time", "temperature"))]) # convert to matrix b/c rbind is much faster on matrices
# Keep columns separate: converting an entire raw block to a matrix
# copies time and temperature along with all three acceleration axes.
data = as.data.frame(accread$P$data[, which(colnames(accread$P$data) %in%
c("x", "y", "z", "time", "temperature")), drop = FALSE])
if (exists("accread")) {
rm(accread)
}
# add leftover data from last time
if (min(dim(S)) > 1) {
data = rbind(S,data)
data = as.data.frame(Map(c, S, data))
}
# remove 0s if ActiGraph csv (idle sleep mode) OR if similar imputation done in ad-hoc csv
# current ActiGraph csv's are not with zeros but with last observation carried forward
zeros = c()
if (!(mon == MONITOR$ACTIGRAPH && dformat == FORMAT$CSV)) {
zeros = which(data[, "x"] == 0 & data[, "y"] == 0 & data[, "z"] == 0)
zeros = which(data$x == 0 & data$y == 0 & data$z == 0)
}
if ((mon == MONITOR$ACTIGRAPH && dformat == FORMAT$CSV) || length(zeros) > 0) {
data = g.imputeTimegaps(x = as.data.frame(data), sf = sf, impute = FALSE)
data = as.matrix(data$x)
data = data$x
}
LD = nrow(data)
#store data that could not be used for this block, but will be added to next block
use = (floor(LD / (blockResolution*sf))) * (blockResolution*sf) #number of datapoint to use
if (length(use) > 0) {
if (use > 0) {
if (use != LD) {
S = data[(use + 1):LD,] # store leftover data

# if S is only one row, it gets coersed to a vector, and what we need is a 1-row matrix
if (is.vector(S)) {
S = t(S)
}
S = data[(use + 1):LD, , drop = FALSE] # store leftover data
}
data = data[1:use,]
LD = nrow(data) #redefine LD because there is less data

Gx = data[, "x"]
Gy = data[, "y"]
Gz = data[, "z"]
# Subset only columns needed for feature extraction. If the block
# already contains complete hours, reuse the column vectors.
rows = seq_len(use)
if (use == LD) {
Gx = data$x
Gy = data$y
Gz = data$z
if (use.temp) temperature = data$temperature
} else {
Gx = data$x[rows]
Gy = data$y[rows]
Gz = data$z[rows]
if (use.temp) temperature = data$temperature[rows]
}
LD = use
rm(data)

if (use.temp) {
if (mean(data[1:10, "temperature"], na.rm = TRUE) > 120) {
if (mean(temperature[1:10], na.rm = TRUE) > 120) {
warning("\ntemperature ignored for auto-calibration because values are too high\n")
use.temp = FALSE
} else if (sd(data[, "temperature"], na.rm = TRUE) < 0.01) {
} else if (sd(temperature, na.rm = TRUE) < 0.01) {
warning("\ntemperature ignored for auto-calibration because no variance in values\n")
use.temp = FALSE
}
Expand Down Expand Up @@ -198,10 +219,11 @@ g.calibrate = function(datafile, params_rawdata = c(),
features[count:endCount, 6] = rollSD(Gy, sf, calibEpochSize)
features[count:endCount, 7] = rollSD(Gz, sf, calibEpochSize)
if (use.temp == TRUE) {
features[count:endCount, 8] = rollMean(data[, "temperature"], sf, calibEpochSize)
features[count:endCount, 8] = rollMean(temperature, sf, calibEpochSize)
}
count = endCount + 1 # increasing count, the indicator of how many timesteps (calibEpochSize) have been read
rm(Gx); rm(Gy); rm(Gz)
rm(Gx, Gy, Gz, EN, EN2)
if (exists("temperature", inherits = FALSE)) rm(temperature)
# Update blocksize depending on available memory:
BlocksizeNew = updateBlocksize(blocksize = blocksize, bsc_qc = bsc_qc)
bsc_qc = BlocksizeNew$bsc_qc
Expand All @@ -216,7 +238,9 @@ g.calibrate = function(datafile, params_rawdata = c(),
if (isLastBlock) {
LD = 0
}
features_temp = data.frame(V = features, stringsAsFactors = FALSE)
# Only prepare epochs collected so far, not the unused buffer capacity.
features_temp = data.frame(V = features[seq_len(count - 1), , drop = FALSE],
stringsAsFactors = FALSE)
# remove 999999, missing values
cut = which(features_temp[,1] == 99999 |
is.na(features_temp[,4]) == TRUE | is.na(features_temp[,1]) == TRUE)
Expand Down Expand Up @@ -287,7 +311,7 @@ g.calibrate = function(datafile, params_rawdata = c(),
# START of Zhou Fang's code (slightly edited by vtv21 to use matrix features_temp from above
# instead the similar matrix generated by Zhou Fang's original code. This to allow for
# more data to be used as features_temp can now be based on 10 or more days of raw data
input = features_temp[,2:4]
input = as.matrix(features_temp[,2:4])
if (use.temp == TRUE) {
inputtemp = cbind(as.numeric(features_temp[,8]),as.numeric(features_temp[,8]),as.numeric(features_temp[,8])) #temperature
} else {
Expand All @@ -304,8 +328,7 @@ g.calibrate = function(datafile, params_rawdata = c(),
tol = 1e-10
for (iter in 1:maxiter) {
curr = c()
try(expr = {curr = scale(input, center = -offset, scale = 1/scale) +
scale(inputtemp, center = F, scale = 1/tempoffset)}, silent = TRUE)
try(expr = {curr = transformAxes(input, offset, scale, inputtemp, tempoffset)}, silent = TRUE)
if (length(curr) == 0) {
# set coefficients to default, because it did not work.
break
Expand Down
83 changes: 83 additions & 0 deletions dev/benchmark_g_calibrate.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Run from the package root:
# Rscript --vanilla dev/benchmark_g_calibrate.R <file.cwa> <baseline.R> [outputdir]
# baseline.R must define the version of g.calibrate() to compare with this tree.
# File reading is outside timing; both versions receive the same real CWA block.
args = commandArgs(trailingOnly = TRUE)
if (length(args) < 2) {
stop("Supply a CWA file and a baseline R source defining g.calibrate().")
}
pkgload::load_all(".", quiet = TRUE)
outputdir = if (length(args) >= 3) args[3] else tempfile("ggir-calibrate-benchmark-")
dir.create(outputdir, recursive = TRUE, showWarnings = FALSE)

namespace = environment(GGIR::g.calibrate)
baseline_env = new.env(parent = namespace)
sys.source(args[2], envir = baseline_env)
baseline = baseline_env$g.calibrate
environment(baseline) = namespace
candidate = GGIR::g.calibrate

params = extract_params()
inspection = g.inspectfile(args[1], params_rawdata = params$params_rawdata,
params_general = params$params_general)
if (inspection$monc != MONITOR$AXIVITY || inspection$dformc != FORMAT$CWA) {
stop("This benchmark expects an Axivity CWA file.")
}
block = g.readaccfile(
filename = args[1], blocknumber = 1,
blocksize = round(12 * 3600 * inspection$sf / 80 * params$params_rawdata$chunksize),
filequality = list(filetooshort = FALSE, filecorrupt = FALSE,
filedoesnotholdday = FALSE),
ws = 3600, inspectfileobject = inspection,
params_rawdata = params$params_rawdata, params_general = params$params_general)
block$isLastBlock = TRUE
reader = function(...) block
bind_reader = function(fun) {
environment(fun) = list2env(list(g.readaccfile = reader), parent = namespace)
compiler::cmpfun(fun)
}
implementations = list(baseline = bind_reader(baseline), candidate = bind_reader(candidate))
run = function(fun) {
result = fun(args[1], inspectfileobject = inspection, minloadcrit = 0, verbose = FALSE)
result$bsc_qc = NULL # Resource log: timestamps and memory use intentionally differ.
result
}

# Warm both implementations and validate the entire scientific result.
reference = run(implementations$baseline)
actual = run(implementations$candidate)
if (!identical(reference, actual)) {
print(all.equal(reference, actual))
stop("Calibration results differ.")
}
saveRDS(list(reference = reference, candidate = actual), file.path(outputdir, "results.rds"))

timings = data.frame()
for (trial in seq_len(7)) {
order = if (trial %% 2) names(implementations) else rev(names(implementations))
for (name in order) {
gc()
elapsed = system.time(run(implementations[[name]]), gcFirst = FALSE)[["elapsed"]]
timings = rbind(timings, data.frame(trial = trial, implementation = name, elapsed = elapsed))
}
}
write.csv(timings, file.path(outputdir, "timings.csv"), row.names = FALSE)
print(aggregate(elapsed ~ implementation, timings, median))

if (capabilities("profmem")) {
allocations = data.frame()
for (name in names(implementations)) {
gc()
path = file.path(outputdir, paste0(name, "-allocations.out"))
Rprofmem(path)
tryCatch(run(implementations[[name]]), finally = Rprofmem(NULL))
lines = readLines(path)
sizes = as.numeric(sub(" .*", "", lines[grepl("^[0-9]+ :", lines)]))
allocations = rbind(allocations, data.frame(implementation = name,
allocated_mb = sum(sizes) / 1024^2))
}
write.csv(allocations, file.path(outputdir, "allocations.csv"), row.names = FALSE)
print(allocations) # Total R allocations, not peak resident memory.
}
capture.output(sessionInfo(), file = file.path(outputdir, "session-info.txt"))
cat("Cached samples:", nrow(block$P$data), "\nResults:", normalizePath(outputdir), "\n")
Loading
Loading