txtProgressBar suddenly stopped working with style=3 - r

I've been using txtProgressBar() for a while now. Since today, it stopped working if using style=3.
It just shows an empty progress bar, and is not updated.
Yesterday I updated some packages, but not the utils package, AFAIK. Maybe the sysadmins updated R without me knowing.
To reproduce:
for (i in 1:10) {
pb <- txtProgressBar(max = 11, style = 3)
Sys.sleep(1)
setTxtProgressBar(pb, pb$getVal()+1)
}
close(pb)
In my case, this just shows:
| | 0%
All the time. Other styles (1 and 2) work fine.
My R details:
> R.version
_
platform x86_64-pc-linux-gnu
arch x86_64
os linux-gnu
system x86_64, linux-gnu
status
major 3
minor 2.2
year 2015
month 08
day 14
svn rev 69053
language R
version.string R version 3.2.2 (2015-08-14)
nickname Fire Safety
Is there something I'm missing, maybe something that could be wrongly set in my session, or is this a bug?

You put pb <- txtProgressBar(max = 11, style = 3) inside the loop. It should be outside the loop, before it.
Also, your max is not correct. It should be 10, as your for loop goes from 1 to 10.
pb <- txtProgressBar(max = 10, style = 3)
for (i in 1:10) {
Sys.sleep(0.5)
setTxtProgressBar(pb, pb$getVal()+1)
}
close(pb)

the following part of the code: pb <- txtProgressBar(max = 11, style = 3)
should be outside the for loop. In my interpretation, if you put it inside you re-initialize the progress bar at each cycle of the loop.
The following code does what you are expecting:
pb <- txtProgressBar(max = 11, style = 3)
for (i in 1:10) {
Sys.sleep(1)
setTxtProgressBar(pb, pb$getVal()+1)
}
close(pb)

Related

Using callr to display an (estimated) progress bar without stopping the script

I would like to run a very simple script concurrently or asynchronously, displaying an estimated progress bar.
This works well enough when using system2() like this:
path <- '../Desktop/.../My_Skript_Dir/'
system2(command = "cmd.exe",
input = paste('"./R-4.2.1/bin/Rscript.exe"',
paste0(path, '/Progress_Bar.R')), wait = FALSE)
If possible I would like to avoid using system2 though and I recently found out that callr might do the trick. It almost works, using the function from the "Progress_Bar" script:
estimated_progress <- function(df = NULL, add_time = FALSE){
require(tcltk)
require(callr)
pred <- round(nrow(df)*0.6) # prediction
callr::r_bg(func = function(pred){ # open background r session
pb1 <- tcltk::tkProgressBar(title='PB', label='PB', min=0, max=pred, initial=0)
for (index in seq(pred)){
tcltk::setTkProgressBar(pb=pb1, value=index)
Sys.sleep(1)
}
}, args = list(pred))
}
df <- data.frame(matrix(nrow = 200, ncol = 3)) # dummy data
estimated_progress(df = df, add_time = FALSE)
When I do this, the progress bar opens in a new window as expected.
It keeps going for the next 1-3 function(s) (for example invisible(pbapply::pblapply(1:200000, function(x) x**3)) ) but any more than that and estimated_progress() abborts.
What am I missing here? I am sure it's quite obvious and I have read that callr can work asynchronously (look here) but I can't make it work.

Error in Running NLRX (NetLogo) in Manjaro (Arch) Linux

I am attempting to run an NLRX simulation in Manjaro Linux (RNetLogo wouldn't work for some reason either), and am running into the following error when attempting to set up an dummy experiment:
cp: cannot stat '~/.netlogo/NetLogo 6.1.1/netlogo-headless.sh': No such file or directory
sed: can't read /tmp/Rtmpj15Yf7/netlogo-headless365385fb4bdc0.sh: No such file or directory
sed: can't read /tmp/Rtmpj15Yf7/netlogo-headless365385fb4bdc0.sh: No such file or directory
sh: /tmp/Rtmpj15Yf7/netlogo-headless365385fb4bdc0.sh: No such file or directory
Error in util_gather_results(nl, outfile, seed, siminputrow) :
Temporary output file /tmp/Rtmpj15Yf7/nlrx5493_1365385ab03157.csvnot found. On unix systems this can happen if the default system temp folder is used.
Try reassigning the default temp folder for this R session (unixtools package).
In addition: Warning message:
In system(NLcall, wait = TRUE) : error in running command
Given that I am running R 4.0.0, the Unixtools package doesn't work, so that's out of the question. How would I go about fixing this?
Code for those curious:
library(nlrx)
netlogopath <- file.path("~/.netlogo/NetLogo 6.1.1")
modelpath <- file.path(netlogopath, "app/models/Sample Models/Biology/Wolf Sheep Predation.nlogo")
outpath <- file.path("/home/out")
nl <- nl(nlversion = "6.0.3",
nlpath = netlogopath,
modelpath = modelpath,
jvmmem = 1024)
nl#experiment <- experiment(expname="wolf-sheep",
outpath=outpath,
repetition=1,
tickmetrics="true",
idsetup="setup",
idgo="go",
runtime=50,
evalticks=seq(40,50),
metrics=c("count sheep", "count wolves", "count patches with [pcolor = green]"),
variables = list('initial-number-sheep' = list(min=50, max=150, qfun="qunif"),
'initial-number-wolves' = list(min=50, max=150, qfun="qunif")),
constants = list("model-version" = "\"sheep-wolves-grass\"",
"grass-regrowth-time" = 30,
"sheep-gain-from-food" = 4,
"wolf-gain-from-food" = 20,
"sheep-reproduce" = 4,
"wolf-reproduce" = 5,
"show-energy?" = "false"))
nl#simdesign <- simdesign_lhs(nl=nl,
samples=100,
nseeds=3,
precision=3)
results <- run_nl_all(nl = nl)
R Version for those who may want it:
platform x86_64-pc-linux-gnu
arch x86_64
os linux-gnu
system x86_64, linux-gnu
status
major 4
minor 0.0
year 2020
month 04
day 24
svn rev 78286
language R
version.string R version 4.0.0 (2020-04-24)
nickname Arbor Day
In case others find this helpful: I have encountered similar errors as the result of file path misspecification. For instance, double check model path. You may need to drop app/.

Calling applescript in R

Is there any way to run an applescript within R?
I found this reference in an R FAQ on CRAN
From release 1.3.1 R has partial support for AppleScripts. This means two things: you can run applescripts from inside R using the command applescript() (see the corresponding help)
But in my current version of R
R version 3.4.1 (2017-06-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.6
neither applescript() nor ?applescript() returns anything.
Thanks, Simon
Those features aren't in modern R versions (IIRC they harken back to pre-macOS/Mac OS X days).
However, the applescript() function performed no magic:
applescript <- function(script_source, extra_args = c()) {
script_source <- paste0(script_source, collapse = "\n")
tf <- tempfile(fileext = ".applescript")
on.exit(unlink(tf), add=TRUE)
cat(script_source, file = tf)
osascript <- Sys.which("osascript")
args <- c(extra_args, tf)
system2(
command = osascript,
args = args,
stdout = TRUE
) -> res
invisible(res)
}
So you can do anything with it, like open a folder:
applescript(
sprintf(
'tell app "Finder" to open POSIX file "%s"',
Sys.getenv("R_DOC_DIR")
)
)
or, query an app and return data:
res <- applescript('
tell application "iTunes"
set r_name to name of current track
set r_artist to artist of current track
end
return "artist=" & r_artist & "\ntrack=" & r_name
')
print(res)
## [1] "artist=NICO Touches the Walls" "track=Hologram"
For (mebbe) easier usage (I say "mebbe" as the pkg relies on reticulate for some things) I added this to the macthekinfe macOS-centric R package.

How would one check the system memory available using R on a Windows machine?

I am running a multi-threaded R program but am having trouble with some nodes crashing due to the host system running out of memory. Is there a way for each node to check the available memory for the entire system before continuing to run? (machine is running Windows Server 2012 R2)
Maybe one of the below will help ( I am also on Windows Server 2012 R2):
Maybe this would be the most useful:
> system('systeminfo')
#the output is too big to show but you can save into a list and choose the rows you want
Or just use one of the below which are specific about the memory
> system('wmic MemoryChip get BankLabel, Capacity, MemoryType, TypeDetail, Speed')
BankLabel Capacity MemoryType Speed TypeDetail
RAM slot #0 8589934592 2 512
RAM slot #1 4294967296 2 512
Free available memory:
> system('wmic OS get FreePhysicalMemory /Value')
FreePhysicalMemory=8044340
Total available Memory
> system('wmic OS get TotalVisibleMemorySize /Value')
TotalVisibleMemorySize=12582456
Basically you can even run any other cmd command you want that you know it could help you through the system function. R will show the output on the screen and you can then save into a data.frame and use as you want.
Just for the sake of completion, I added support for Linux on Stefan's answer above-
Tested on Ubuntu 16
getFreeMemoryKB <- function() {
osName <- Sys.info()[["sysname"]]
if (osName == "Windows") {
x <- system2("wmic", args = "OS get FreePhysicalMemory /Value", stdout = TRUE)
x <- x[grepl("FreePhysicalMemory", x)]
x <- gsub("FreePhysicalMemory=", "", x, fixed = TRUE)
x <- gsub("\r", "", x, fixed = TRUE)
return(as.integer(x))
} else if (osName == 'Linux') {
x <- system2('free', args='-k', stdout=TRUE)
x <- strsplit(x[2], " +")[[1]][4]
return(as.integer(x))
} else {
stop("Only supported on Windows and Linux")
}
}
I wrapped LyzandeR's answer above up in a functions that returns the physical memory in kilobytes (1024 bytes). Tested on windows 7.
get_free_ram <- function(){
if(Sys.info()[["sysname"]] == "Windows"){
x <- system2("wmic", args = "OS get FreePhysicalMemory /Value", stdout = TRUE)
x <- x[grepl("FreePhysicalMemory", x)]
x <- gsub("FreePhysicalMemory=", "", x, fixed = TRUE)
x <- gsub("\r", "", x, fixed = TRUE)
as.integer(x)
} else {
stop("Only supported on Windows OS")
}
}

How do I bring an R Tk window to the front after launching via Rscript from another application?

I have a script along the lines of:
if (!require(tcltk2)) {install.packages('tcltk2', repos="http://cran.us.r-project.org"); require(tcltk2)}
base <- NULL
done <- tclVar(0)
quasitelgui <- function(inputfile = NULL)
{
base <- tktoplevel()
tkwm.title(base, "QuasiTel")
# Files
file.frm <- tkframe(base, borderwidth=2)
datafile.lbl <- tklabel(file.frm, text="Data")
datafile.entry <- tkentry(file.frm, state="readonly")
datafile.btn <- tkbutton(file.frm, text="Browse...")
tkgrid(datafile.lbl, datafile.entry, datafile.btn)
tkgrid.configure(datafile.lbl, sticky="e")
tkgrid.configure(datafile.entry, sticky="ew", padx=1)
tkgrid.columnconfigure(file.frm, 1, weight=1)
tkgrid(file.frm)
tkgrid.configure(file.frm, sticky="ew")
# Main
main.frm <- tkframe(base, borderwidth=2)
g1.lbl <- tklabel(main.frm, text="Group 1")
g2.lbl <- tklabel(main.frm, text="Group 2")
tkgrid(g1.lbl, g2.lbl)
q.btn <- tkbutton(bott.frm, text="Quit", command=function() tclvalue(done) <- 1)
tkbind(base,"<Destroy>", function() tclvalue(done) <- 2)
tkgrid(filter.lbl, columnspan=2)
tkgrid(filter.entry)
tkgrid(ok.btn, q.btn)
tkgrid.configure(ok.btn, q.btn, padx=1)
tkgrid(bott.frm)
tkgrid.columnconfigure(base, 0, weight=1)
if (length(inputfile) > 0) { datafile.open(inputfile) }
}
cmd.args <- commandArgs(trailingOnly=TRUE)
if (length(cmd.args) > 0) {
quasitelgui(gsub("\\\\", "/", cmd.args[1]))
} else {
quasitelgui()
}
tkfocus(base)
tkwait.variable(done)
tkdestroy(base)
I'm running it via rscript from another GUI. I want the window to grab focus when it starts. Tkfocus doesn't do it.
Not focus, but raise:
> library(tcltk)
Loading Tcl/Tk interface ... done
> w1 <- tktoplevel()
> w2 <- tktoplevel()
> tkraise(w1)
I think jverzani is correct is that many if not all (contemporary) GUI systems (I mean, OS/desktop level, not GUI toolkits) prevent focus stealing. A new process which wants to grab focus is a perfect case of a focus stealing attempt, so I'm inclined to think that if your script, Matt, runs in another process, you can't expect it to actually grab focus. There are system-dependent ways to draw user attention to a particular window but I doubt they are directly supported by Tk.
In MS Windows you can follow this way:
info_sys <- Sys.info() # sniff the O.S.
if (info_sys['sysname'] == 'Windows') { # MS Windows trick
shell("powershell -command [void] [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') ; [Microsoft.VisualBasic.Interaction]::AppActivate('The title of your window') ")
}

Resources