Debugging options in R - r

In some coding languages, the cursor stops in debug mode before the error happened in the local environment of the function being run. I am wondering if there is a similar functionality in R.
Currently what I found from researching this matter:
To reproduce that in R, we need to position "browser()" at a strategic location we think of. Then recompile the function we were running by selecting all the lines of the function then hitting CTRL + Enter to compile it then run the code then debug in the function. If browser was improperly positioned due to bad guessing this operation has to be repeated causing significant time loss.
It is very painful.
Another solution I found that is even worse is the use of options(error = recover). If we are going through iterations for example, it will be offer to stop before the loop started instead of offering to jump in the code at the iteration that caused the bug. This feature does not seem to be much more helpful.

(This is too long/formatted for a comment.) I'm not sure what you mean (referring to options(error=recover) by
it will be offer to stop before the loop started instead of offering to jump in the code at the iteration that caused the bug.
Here's an example where the break seems to occur at the iteration that caused the error, as requested:
options(error=recover)
f <- function(x) { for (i in 1:x) if (i==2) stop() }
f(5)
Error in f(5) :
Enter a frame number, or 0 to exit
1: f(5)
Selection: 1
Called from: top level
Browse[1]> print(i)
[1] 2
This is breaking at a specific step in the loop, not (as suggested above) before the loop starts (where i would be undefined).
Can you please give a reproducible example to clarify the difference between the behaviour that happens and what you'd prefer?
For what it's worth, the RStudio front-end offers a slightly more visual debugging experience that you might prefer.

Related

R studio lp solve hanging, how to fix

I am using lp solve in r to solve an optimization problem, but sometimes the function runs into an issue and hangs. Rstudio has the red stop-sign logo that I can click to terminate the program, however for some reason the stop-sign does not break this particular error.
Other than clicking the stop sign, is there any way to terminate the console from running when a function gets stuck? Something that I can do automatically (i.e. if the console is stuck hanging for 10+ seconds, then terminate) would be great.
thanks!
If the problem is, that the optimization is too complex, you can use the function lp.control. Where:
lp.control( "Name of optimization problem", timeout= "number of seconds before termination")
lp.solver will look for all possible answers, so stopping it will yield the best answer found during the timeframe.

Product of range in Prolog

I need to write a program, which calculates product of product in range:
I written the following code:
mult(N,N,R,R).
mult(N,Nt,R,Rt):-N1=Nt+1,R1=Rt*(1/(log(Nt))),mult(N,N1,R,R1).
This should implement basic product from Nt to N of 1/ln(j). As far as I understand it's got to be stopped when Nt and N are equal. However, I can't get it working due to:
?- mult(10,2,R,1), write(R).
ERROR: Out of global stack
The following error. Is there any other way to implement loop not using default libraries of SWI-Prolog?
Your program never terminates! To see this consider the following failure-slice of your program:
mult(N,N,R,R) :- false.
mult(N,Nt,R,Rt):-
N1=Nt+1,
R1=Rt*(1/(log(Nt))),
mult(N,N1,R,R1), false.
This new program does never terminate, and thus the original program doesn't terminate. To see that this never terminates, consider the two (=)/2 goals. In the first, the new variable N1 is unified with something. This will always succeed. Similarly, the second goal with always succeed. There will never be a possibility for failure prior to the recursive goal. And thus, this program never terminates.
You need to add some goal, or to replace existing goals. in the visible part. Maybe add
N > Nt.
Further, it might be a good idea to replace the two (=)/2 goals by (is)/2. But this is not required for termination, strictly speaking.
Out of global stack means you entered a too-long chain of recursion, possibly an infinite one.
The problem stems from using = instead of is in your assignments.
mult(N,N,R,R).
mult(N,Nt,R,Rt):-N1 is Nt+1, R1 is Rt*(1/(log(Nt))), mult(N,N1,R,R1).
You might want to insert a cut in your first clause to avoid going on after getting an answer.
If you have a graphical debugger (like the one in SWI) try setting 'trace' and 'debug' on and running. You'll soon realize that performing N1 = Nt+1 giving Ntas 2 yields the term 2+1. Since 2+1+1+1+(...) will never unify with with 10, that's the problem right there.

Diagnozing opaque errors and stabilizing / robustifying a Simulation in R

Apologies, since this question is somewhat vague and general, and is certainly not reproducible since the code is too complex. However, I suspect it could be answered by equally vague strategies of approaching these issues that are instructive and helpful.
I have coded a simulator which has a main, parallelized loop iterating through parameter values, loading them to the model and running them n times.
The issue: while the code generally works well for smaller problem dimensions, it fails at a significant frequency at higher dimensions (particularly higher n); most parameter values execute fine and output is produced, but once in a while there is no file produced. The 'post processing' then fails because of missing files.
What I know: Rerunning the function, different parameter values are effected, so this is not due to invalid parameter values, but seemingly a random failure. There have also been some runs without any problems. There was once an error message about failure to allocate vector of size xyz.
What I tried: traceback() seems to focus on the failure at the end of the sim (a symptom) but doesn't find the real cause. I also tried adding a while loop conditional on the existence of the output file, what would rerun the parameter value if it failed (see below, commented out). This seemed to help a little, but not completely.
The above leads me to suspect some threads crash somehow, and then fail to output any of the parameters assigned to it.
Questions: What strategies would you use to diagnose this issue? What methods can one implement to make such a simulation more robust to errors (diagnosed or otherwise)? What kind of operations might I be doing what can cause such failures?
Sketch of the Sim. Loop:
library(foreach)
library(doMC)
Simulator <- function(params,...)
{
[... Pre Processing...]
times<-foreach(i=1:length(params)) %dopar%
{
# while(!file.exists(paste0("output",i,".rds"))) {
run <-list()
run$par <-params[[i]]
run$data <-list()
foreach(j=1:n) %do% # Run Sim n times with params
{
run$data[[j]] <- SimRun(params[[i]],...)
}
# Combine into single array and label dimensions
run$data <- abind(run$data,along=4)
dimnames(run$data)<- headers
# Compute statistics and save them
run$stats <- Stats(run$data,params[[i]])
saveRDS(run,paste0("output",i,".rds"))
# }
[...etc...]
}
[... Post Processing....]
}
Thanks for your patience!

Ignoring errors in R

I'm running a complex but relatively quick simulation in R (takes about 5-10 minutes per simulation) and I'm beginning to run it in parallel with various input values in order to test the robustness of some of my algorithms.
There seems to be one problem: some arrangements of inputs cause a fatal error within the simulation and the whole code comes crashing down, causing the simulations to end. Is there an easy way to catch the error (which may come from a variety of locations) and have it just ignore those input values and move on to the next?
It's frustrating when I set an array of inputs to check that should take 5-6 hours to run through all the simulations and I come back to find that it crashed in the first 45 minutes.
While I work on trying to fix the bug / identify inputs that push me to that error, any ideas on how to ignore / catch the errors as they come?
Thanks
I don't know how did your organize your simulations, but I guess uu have a loop where you check use new arguments at each step.
You can use tryCatch . Here I am throwing an error if I have bad input.
step.simul <- function (x) {
stopifnot(x%%2 == 1, x>0)
(x - 1)/2
}
Then using tryCatch, I flag the bad inputs with a code
that tells you about the bad input:
sapply(1:5, function(i)tryCatch(step.simul(i), error=function(e)-1000-i))
[1] 0 -1002 1 -1004 2
As you see my simulations runs over all the loop index.

How does setTimeLimit work in R?

I am trying to master setTimeLimit() in R and my experience has led to several related questions, so maybe the fundamental question is: how does this really work? (I have been looking at evalWithTimeout() from R.utils as well, and it may suit my purposes slightly better, but it's built on this function.)
Here are the key things I am trying to figure out:
How does it monitor the elapsed time? I.e. it seems to get inserted into the flow control, so how does it do that? Being able to have "background" processes is cool, and could be used for reporting status, checkpointing, and more.
Can I determine how much time remains until it is triggered? I realize I can wrap it and store, somewhere, the elapsed & CPU time consumed at about the point of invocation (i.e. the output of proc.time()). But, this function is already storing these somewhere and I'd like to know where, or at least how to determine the time remaining.
Can it be made to do something useful if the R console is idle? Being able to monitor elapsed.time() and cpu.time() is very useful. I'd like to be able to monitor when R is idle, but it seems from tinkering that it requires a command to be submitted or completed. Moreover, just outputting an error doesn't trigger a subsequent action. (Maybe I need to give more attention to evalWithTimeout.)
The help information says that it can be applicable with C or Fortran, but doesn't give examples. Any suggestions on how this should be done?
To show that setTimeLimit does not work during a C function call:
rfunction <- function(){
repeat{
x <- rnorm(100);
}
}
cfunction <- function(){
x <- eigen(matrix(rnorm(1e6), 1e3));
}
setTimeLimit(3);
system.time(try(rfunction(), silent=TRUE))
system.time(try(cfunction(), silent=TRUE))

Resources