Memory usage keep growing until crash - r

I'm running some scripts from R that gets info from some webs. The problems is that even though I clean the session with gc(), the memory keep growing until my session crashes.
Here is the script:
library(XML)
library(RJDBC)
library(RCurl)
procesarPublicaciones <- function(tabla){
log_file <<- file(log_path, open="a")
drv <<- JDBC("oracle.jdbc.OracleDriver", classPath="C:/jdbc/jre6/ojdbc6.jar"," ")
con <<- dbConnect(drv, "server_path", "user", "password")
query <- paste("SELECT * FROM",tabla,sep=' ')
bool <- tryCatch(
{
## Get a list of URLs from a DB
listUrl <- dbGetQuery(con, query)
if( nrow(listUrl) != 0) TRUE else FALSE
dbDisconnect(con)
}, error = function(e) return(FALSE)
)
if( bool ) {
file.create(data_file)
apply(listUrl,c(1),procesarHtml)
}else{
cat("\n",getTime(),"\t[ERROR]\t\t", file=log_file)
}
cat( "\n",getTime(),"\t[INFO]\t\t FINISH", file=log_file)
close(log_file)
}
procesarHtml <- function(pUrl){
headerGatherer <- basicHeaderGatherer()
html <- getURI(theUrl, headerfunction = headerGatherer$update, curl = curlHandle)
heatherValue <- headerGatherer$value()
if ( heatherValue["status"] == "200" ){
doc <- htmlParse(html)
tryCatch
(
{
## Here I get all the info that I need from the web and write it on a file.
## here is a simplification
info1 <- xpathSApply(doc, xPath.info1, xmlValue)
info2 <- xpathSApply(doc, xPath.info2, xmlValue)
data <- data.frame(col1 = info1, col2=info2)
write.table(data, file=data_file , sep=";", row.names=FALSE, col.names=FALSE, append=TRUE)
}, error= function(e)
{
## LOG ERROR
}
)
rm(info1, info2, data, doc)
}else{
## LOG INFO
}
rm(headerGatherer,html,heatherValue)
cat("\n",getTime(),"\t[INFO]\t\t memory used: ", memory.size()," MB", file=log_file)
gc()
cat("\n",getTime(),"\t[INFO]\t\t memory used after gc(): ", memory.size()," MB", file=log_file)
}
Even though I remove all internal variables with rm() and use gc(), memory keeps growing. It seems that all the html that I get from the web is kept in memory.
Here is my Session Info:
> sessionInfo()
R version 3.2.0 (2015-04-16)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows XP (build 2600) Service Pack 3
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] RCurl_1.95-4.6 bitops_1.0-6 RJDBC_0.2-5 rJava_0.9-6 DBI_0.3.1
[6] XML_3.98-1.1
loaded via a namespace (and not attached):
[1] tools_3.2.0
--------------------EDIT 2015-06-08 --------------------
I'm still having the problem, but I found the same issue on other post, which is apparently resolved.
Serious Memory Leak When Iteratively Parsing XML Files

When using the XML package, you'll want to use free() to release the memory allocated by htmlParse() (or any of the other html parsing functions that allocate memory at the C level). I usually place a call to free(doc) as soon as I don't need the html doc any more.
So in your case, I would try placing free(doc) on its own line prior to rm(info1, info2, data, doc) in your function, like this:
free(doc)
rm(info1, info2, data, doc)
In fact the call to free() may be sufficient enough that you could remove the rm() call completely.

I had a related issue using htmlParse. Led to Windows crashing (out of memory) before my 10,000 iterataions completed.
Answer:
in addition to free/remove - do a garbage collect gc() (as suggested in Serious Memory Leak When Iteratively Parsing XML Files ) every n iterations

Related

Parallelization of Rcpp without inline/ creating a local package

I am creating a package that I hope to eventually put onto CRAN. I have coded much of the package in C++ with the help of Rcpp and now would like to enable parallelization of this C++ code. I am using the foreach package, however, I am open to switch to snow or a different library if this would work better.
I started by trying to parallelize a simple function:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
// [[Rcpp::export]]
arma::vec rNorm_c(int length) {
return arma::vec(length, arma::fill::randn);
}
/*** R
n_workers <- parallel::detectCores(logical = F)
cl <- parallel::makeCluster(n_workers)
doParallel::registerDoParallel(cl)
n <- 10
library(foreach)
foreach(j = rep(n, n),
.noexport = c("rNorm_c"),
packages = "Rcpp") %dopar% {rNorm_c(j)}
*/
I added the .noexport because without, I get the error Error in { : task 1 failed - "NULL value passed as symbol address". This led me to this SO post which suggested doing this.
However, I now receive the error Error in { : task 1 failed - "could not find function "rNorm_c"", presumably because I have not followed the top answers instructions to load the function separately at each node. I am unsure of how to do this.
This SO post demonstrates how to do this by writing the C++ code inline, however, since the C++ code for my package is multiple functions, this is likely not the best solution. This SO post advises to create a local package for the workers to load and make calls to, however, since I am hoping to make this code available in a CRAN package, it does not seem as though a local package would be possible unless I wanted to attempt to publish two CRAN packages.
Any suggestions for how to approach this or references to resources for parallelization of Rcpp code would be appreciated.
EDIT:
I used the above function to create a package called rnormParallelization. In this package, I also included a couple of R functions, one of which made use of the snow package to parallelize a for loop using the rNorm_c function:
rNorm_samples_for <- function(num_samples, length){
sample_mat <- matrix(NA, length, num_samples)
for (j in 1:num_samples){
sample_mat[ , j] <- rNorm_c(length)
}
return(sample_mat)
}
rNorm_samples_snow1 <- function(num_samples, length){
clus <- snow::makeCluster(3)
snow::clusterExport(clus, "rNorm_c")
out <- snow::parSapply(clus, rep(length, num_samples), rNorm_c)
snow::stopCluster(clus)
return(out)
}
Both functions work as expected:
> rNorm_samples_for(2, 3)
[,1] [,2]
[1,] -0.82040308 -0.3284849
[2,] -0.05169948 1.7402912
[3,] 0.32073516 0.5439799
> rNorm_samples_snow1(2, 3)
[,1] [,2]
[1,] -0.07483493 1.3028315
[2,] 1.28361663 -0.4360829
[3,] 1.09040771 -0.6469646
However, the parallelized version works considerably slower:
> microbenchmark::microbenchmark(
+ rnormParallelization::rNorm_samples_for(1e3, 1e4),
+ rnormParallelization::rNorm_samples_snow1(1e3, 1e4)
+ )
Unit: milliseconds
expr min lq
rnormParallelization::rNorm_samples_for(1000, 10000) 217.0871 249.3977
rnormParallelization::rNorm_samples_snow1(1000, 10000) 1242.8315 1397.7643
mean median uq max neval
320.5456 285.9787 325.3447 802.7488 100
1527.0406 1482.5867 1563.0916 3411.5774 100
Here is my session info:
> sessionInfo()
R version 4.1.1 (2021-08-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19043)
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] rnormParallelization_1.0
loaded via a namespace (and not attached):
[1] microbenchmark_1.4-7 compiler_4.1.1 snow_0.4-4
[4] parallel_4.1.1 tools_4.1.1 Rcpp_1.0.7
GitHub repo with both of these scripts

Cannot release memory with knitr

I have an issue with knitr where I run can the code in the console without a problem but run out of memory when I knit the document. The markdown document is similar to
---
title: "xyz"
output:
html_document:
toc: true
date: "`r format(Sys.time(), '%d %B, %Y')`"
author: Me
bibliography: ../ref.bib
---
```{r setup, include = FALSE, cache = FALSE}
options(width = 100, digits = 3, scipen = 8)
knitr::opts_chunk$set(
error = FALSE, cache = FALSE,
cache.path = "some-path-cache/", fig.path = "some-path-fig/",
warnings = TRUE, message = TRUE, dpi = 128, cache.lazy = FALSE)
```
[some code]
```{r load_dat}
big_dat <- func_to_get_big_dat()
some_subset <- func_to_get_subset()
```
[some code where both big_dat and some_subset is used, some objects are assigned and some are subsequently removed with rm]
```{r reduce_mem}
dat_fit <- big_dat[some_subset, ]
rm(big_dat)
```
```{r log_to_show}
sink("some-log-file")
print(gc())
print(sapply(ls(), function(x) paste0(class(get(x)), collapse = ";")))
print(sort(sapply(ls(), function(x) object.size(get(x)))))
sink()
```
```{r some_chunk_that_requires_a_lot_of_memory, cache = 1}
...
```
When I knit the document using knitr then I run out of memory in the some_chunk_that_requires_a_lot_of_memory and the content of some-log-file is
used (Mb) gc trigger (Mb) max used (Mb)
Ncells 3220059 172 5684620 304 5684620 304
Vcells 581359200 4436 1217211123 9287 981188369 7486
[output abbreviated (the other variables are "function"s, "character"s, and "matrix"s]
dat_fit X1 some_subset
"data.frame" "integer" "integer"
[output abbreviated]
X1 some_subset dat_fit
5235568 5235568 591631352
so the objects in the .GlobalEnv far from sums to the 4436 MB (there are not many objects and they far smaller than 50 MB each). Running the code in the console does not yield any issues and the print(gc()) shows a much smaller figure.
My questions are
Can I do something to figure out why I use much more memory when I knit the document? Clearly, there must be assigned some objects somewhere that takes up a lot of space. Can I find all assigned objects and check their size?
Do you have some suggestion why gc release less memory when I knit the document? Is there somewhere were knitr assigns some object that may take up a lot of memory?
The data set is proprietary and I have tried but failed to make small example where I can reproduce the result. As a note, I do cache some output from some chunks between load_dat and reduce_mem. I use cache.lazy = FALSE to avoid this issue. Here is my sessionInfo
library(knitr)
sessionInfo()
#R R version 3.4.2 (2017-09-28)
#R Platform: x86_64-w64-mingw32/x64 (64-bit)
#R Running under: Windows 7 x64 (build 7601) Service Pack 1
#R
#R Matrix products: default
#R
#R locale:
#R [1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
#R [4] LC_NUMERIC=C LC_TIME=English_United States.1252
#R
#R attached base packages:
#R [1] stats graphics grDevices utils datasets methods base
#R
#R other attached packages:
#R [1] knitr_1.17
#R
#R loaded via a namespace (and not attached):
#R [1] compiler_3.4.2 tools_3.4.2 yaml_2.1.16
Regarding question 1.
I also added the following to the log_to_show chunk to figure out if there are objects in other environments in the session that takes up a lot of space
# function to check if `this_env` is in `l`
is_env_in_list <- function(l, this_env){
for(i in l)
if(identical(i, this_env))
return(TRUE)
FALSE
}
# remove duplicates for environments
remove_dup_envs <- function(objs){
do_drop <- logical(length(objs))
for(j in rev(seq_along(objs))){
for(i in seq_len(j - 1L)){
if(identical(objs[[i]], objs[[j]])){
do_drop[j] <- TRUE
break
}
}
}
objs[!do_drop]
}
# attempt to write function to get all unique environments
get_env <- function(this_env = .GlobalEnv, out = NULL, only_new = FALSE){
if(is_env_in_list(out, this_env))
return(if(only_new) NULL else out)
if(identical(this_env, emptyenv()))
return(if(only_new) NULL else out)
new. <- this_env # not emptyenv or in list so we add it
# add parent env
p_env <- parent.env(this_env)
if(!is_env_in_list(out, p_env))
new. <- c(new., get_env(p_env, out, only_new = only_new))
# look through assigned objects, find enviroments and add these
objs <- lapply(ls(envir = this_env), function(x){
o <- try(get(x, envir = this_env), silent = TRUE)
if(inherits(o, "try-error"))
NULL
o
})
objs <- lapply(objs, function(x){
if(is.function(x) && !is.null(environment(x)))
return(environment(x))
x
})
if(length(objs) == 0)
return(if(only_new) new. else remove_dup_envs(c(new., out)))
is_env <- which(sapply(objs, is.environment))
if(length(is_env) == 0)
return(if(only_new) new. else remove_dup_envs(c(new., out)))
objs <- remove_dup_envs(objs[is_env])
keep <- which(!sapply(objs, is_env_in_list, l = c(new., out)))
if(length(keep) == 0L)
return(if(only_new) new. else c(new., out))
objs <- objs[keep]
for(o in objs){
ass_envs <- get_env(o, out = c(new., out), only_new = TRUE)
new. <- c(new., ass_envs)
}
return(if(only_new) new. else remove_dup_envs(c(new., out)))
}
tmp <- get_env(asNamespace("knitr"))
names(tmp) <- sapply(tmp, environmentName)
print(tmp <- tmp[order(names(tmp))])
out <- lapply(tmp, function(x){
o <- sapply(ls(envir = x), function(z){
r <- try(object.size(get(z, envir = x)), silent = TRUE)
if(inherits(r, "try-error"))
return(0)
r
})
if(length(o) == 0L)
return(NULL)
tail(sort(o))
})
max_val <- sapply(out, max)
keep <- which(max_val > 10^7)
out <- out[keep]
max_val <- max_val[keep]
tmp <- tmp[keep]
ord <- order(max_val)
print(tmp <- tmp[ord])
print(out <- out[ord])
It shows no objects that are larger than dat_fit.

indirect indexing/subscripting inside %dopar%

I'm not understanding how to do indirect subscripting in %dopar% or in llply( .parallel = TRUE). My actual use-case is a list of formulas, then generating a list of glmer results in a first foreach %dopar%, then calling PBmodcomp on specific pairs of results in a separate foreach %dopar%. My toy example, using numeric indices rather than names of objects in the lists, works fine for %do% but not %dopar%, and fine for alply without .parallel = TRUE but not with .parallel = TRUE. [My real example with glmer and indexing lists by names rather than by integers works with %do% but not %dopar%.]
library(doParallel)
library(foreach)
library(plyr)
cl <- makePSOCKcluster(2) # tiny for toy example
registerDoParallel(cl)
mB <- c(1,2,1,3,4,10)
MO <- c("Full", "noYS", "noYZ", "noYSZS", "noS", "noZ",
"noY", "justS", "justZ", "noSZ", "noYSZ")
# Works
testouts <- foreach(i = 1:length(mB)) %do% {
# mB[i]
MO[mB[i]]
}
testouts
# all NA
testouts2 <- foreach(i = 1:length(mB)) %dopar% {
# mB[i]
MO[mB[i]]
}
testouts2
# Works
testouts3 <- alply(mB, 1, .fun = function(i) { MO[mB[i]]} )
testouts3
# fails "$ operator is invalid for atomic vectors"
testouts4 <- alply(mB, 1, .fun = function(i) { MO[mB[i]]},
.parallel = TRUE,
.paropts = list(.export=ls(.GlobalEnv)))
testouts4
stopCluster(cl)
I've tried various combinations of double brackets like MO[mB[[i]]], to no avail. mB[i] instead of MO[mB[i]] works in all 4 and returns a list of the numbers. I've tried .export(c("MO", "mB")) but just get the message that those objects are already exported.
I assume that there's something I misunderstand about evaluation of expressions like MO[mB[i]] in different environments, but there may be other things I misunderstand, too.
sessionInfo() R version 3.5.1 (2018-07-02) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 7 x64 (build
7601) Service Pack 1
Matrix products: default
locale: [1] LC_COLLATE=English_United States.1252 [2]
LC_CTYPE=English_United States.1252 [3] LC_MONETARY=English_United
States.1252 [4] LC_NUMERIC=C [5]
LC_TIME=English_United States.1252
attached base packages: [1] parallel stats graphics grDevices
utils datasets methods [8] base
other attached packages: [1] plyr_1.8.4 doParallel_1.0.13
iterators_1.0.9 foreach_1.5.0
loaded via a namespace (and not attached): [1] compiler_3.5.1
tools_3.5.1 listenv_0.7.0 Rcpp_0.12.17 [5]
codetools_0.2-15 digest_0.6.15 globals_0.12.1 future_1.8.1
[9] fortunes_1.5-5
The problem appears to be with version 1.5.0 of foreach on r-forge. Version 1.4.4 from CRAN works fine for both foreach %do par% and llply( .parallel = TRUE). For anyone finding this post when searching for %dopar% with lists, here's the code where mList is a named list of formulas, and tList is a named list of pairs of model names to be compared.
tList <- list(Z1 = c("Full", "noYZ"),
Z2 = c("noYS", "noYSZS"),
S1 = c("Full", "noYS"),
S2 = c("noYZ", "noYSZS"),
A1 = c("noYSZS", "noY"),
A2 = c("noSZ", "noYSZ")
)
cl <- makePSOCKcluster(params$nCores) # value from YAML params:
registerDoParallel(cl)
# first run the models
modouts <- foreach(imod = 1:length(mList),
.packages = "lme4") %dopar% {
glmer(as.formula(mList[[imod]]),
data = dsn,
family = poisson,
control = glmerControl(optimizer = "bobyqa",
optCtrl = list(maxfun = 100000),
check.conv.singular = "warning")
)
}
names(modouts) <- names(mList)
####
# now run the parametric bootstrap tests
nSim <- 500
testouts <- foreach(i = seq_along(tList),
.packages = "pbkrtest") %dopar% {
PBmodcomp(modouts[[tList[[i]][1]]],
modouts[[tList[[i]][2]]],
nsim = nSim)
}
names(testouts) <- names(tList)
stopCluster(Cl)

Quantstrat WFA with intraday Data

I've been getting WFA to run on the full set of intraday GBPUSD 30min data, and have come across a couple of things that need addressing. The first is I believe the save function needs changing to remove the time from the string (as shown here as a pull request on the R-Finance/quantstrat repo on github). The walk.forward function throws this error:
Error in gzfile(file, "wb") : cannot open the connection
In addition: Warning message:
In gzfile(file, "wb") :
cannot open compressed file 'wfa.GBPUSD.2002-10-21 00:30:00.2002-10-23 23:30:00.RData', probable reason 'Invalid argument'
The second is a rare case scenario where its ends up calling runSum on a data set with less rows than the period you are testing (n). This is the traceback():
8: stop("Invalid 'n'")
7: runSum(x, n)
6: runMean(x, n)
5: (function (x, n = 10, ...)
{
ma <- runMean(x, n)
if (!is.null(dim(ma))) {
colnames(ma) <- "SMA"
}
return(ma)
})(x = Cl(mktdata)[, 1], n = 25)
4: do.call(indFun, .formals)
3: applyIndicators(strategy = strategy, mktdata = mktdata, parameters = parameters,
...)
2: applyStrategy(strategy, portfolios = portfolio.st, mktdata = symbol[testing.timespan]) at custom.walk.forward.R#122
1: walk.forward(strategy.st, paramset.label = "WFA", portfolio.st = portfolio.st,
account.st = account.st, period = "days", k.training = 3,
k.testing = 1, obj.func = my.obj.func, obj.args = list(x = quote(result$apply.paramset)),
audit.prefix = "wfa", anchored = FALSE, verbose = TRUE)
The extended GBPUSD data used in the creation of the Luxor Demo includes an erroneous date (2002/10/27) with only 1 observation which causes this problem. I can also foresee this being an issue when testing longer signal periods on instruments like Crude where they have only a few trading hours on Sunday evenings (UTC).
Given that I have purely been following the Luxor demo with the same (extended) intra-day data set, are these genuine issues or have they been caused by package updates etc?
What is the preferred way for these things to be reported to the authors of QS, and find out if/when fixes are likely to be made?
SessionInfo():
R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252 LC_MONETARY=English_Australia.1252 LC_NUMERIC=C LC_TIME=English_Australia.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] quantstrat_0.9.1739 foreach_1.4.3 blotter_0.9.1741 PerformanceAnalytics_1.4.4000 FinancialInstrument_1.2.0 quantmod_0.4-5 TTR_0.23-1
[8] xts_0.9.874 zoo_1.7-13
loaded via a namespace (and not attached):
[1] compiler_3.3.0 tools_3.3.0 codetools_0.2-14 grid_3.3.0 iterators_1.0.8 lattice_0.20-33
quantstrat is on github here:
https://github.com/braverock/quantstrat
Issues and patches should be reported via github issues.

R file connection when using parallel

I am trying to make a file connection within a cluster (using parallel).
While it works correctly in the global environment, it gives me an error message when used within the members of the cluster (See the script below).
Do I missed something?
Any suggestion?
Thanks,
# This part works
#----------------
cat("This is a test file" , file={f <- tempfile()})
con <- file(f, "rt")
# Doing what I think is the same thing gives an error message when executed in parallel
#--------------------------------------------------------------------------------------
library(parallel)
cl <- makeCluster(2)
## Exporting the object f into the cluster
clusterExport(cl, "f")
clusterEvalQ(cl[1], con <- file(f[[1]], "rt"))
#Error in checkForRemoteErrors(lapply(cl, recvResult)) :
# one node produced an error: cannot open the connection
## Creating the object f into the cluster
clusterEvalQ(cl[1],cat("This is a test file" , file={f <- tempfile()}))
clusterEvalQ(cl[1],con <- file(f, "rt"))
#Error in checkForRemoteErrors(lapply(cl, recvResult)) :
# one node produced an error: cannot open the connection
############ Here is my sessionInfo() ###################
# R version 3.3.0 (2016-05-03)
# Platform: x86_64-w64-mingw32/x64 (64-bit)
# Running under: Windows 7 x64 (build 7601) Service Pack 1
#
# locale:
# [1] LC_COLLATE=French_Canada.1252 LC_CTYPE=French_Canada.1252
# [3] LC_MONETARY=French_Canada.1252 LC_NUMERIC=C
# [5] LC_TIME=French_Canada.1252
#
# attached base packages:
# [1] stats graphics grDevices utils datasets methods base
#
Try changing the code to return a NULL rather than the created connection object:
clusterEvalQ(cl[1], {con <- file(f[[1]], "rt"); NULL})
Connection objects can't be safely sent between the master and workers, but this method avoids that.

Resources