Is it possible, to control the mouse pointer from the R console?
I have something like this in mind:
move_mouse(x_pos=100,y_pos=200) # move the mouse pointer to position (100,200)
mouse_left_button_down # simulate a press of the left button
move_mouse(x_pos=120,y_pos=250) # move mouse to select something
mouse_release_left_button # release the pressed button
In MATLAB, something like this is possible with the following code
import java.awt.Robot;
mouse = Robot;
mouse.mouseMove(0, 0);
mouse.mouseMove(100, 200);
I tried a direct conversion of the above into R that looks like this:
install.packages("rJava") # install package
library(rJava) # load package
.jinit() # this starts the JVM
jRobot <- .jnew("java/awt/Robot") # Create object of the Robot class
Once I got jRobot in R, I tried to call its metho "MouseMove(100,200)" using the two command below which both resulted in an error.
jRobot$mouseMove(10,10)
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl, :
java.lang.NoSuchMethodException: No suitable method for the given parameters
or
.jcall(jRobot,, "mouseMove",10,10)
Error in .jcall(jRobot, , "mouseMove", 10, 10) :
method mouseMove with signature (DD)V not found
Finally I found the problem. You have to tell R that 100 is an integer, in order to pass it to java correctly.
install.packages("rJava") # install package
library(rJava) # load package
.jinit() # this starts the JVM
jRobot <- .jnew("java/awt/Robot") # Create object of the Robot class
# Let java sleep 500 millis between the simulated mouse events
.jcall(jRobot,, "setAutoDelay",as.integer(500))
# move mouse to 100,200 and select the text up to (100,300)
.jcall(jRobot,, "mouseMove",as.integer(100),as.integer(200))
.jcall(jRobot,, "mousePress",as.integer(16))
.jcall(jRobot,, "mouseMove",as.integer(100),as.integer(300))
.jcall(jRobot,, "mouseRelease",as.integer(16))
As of 2017, CRAN has a package called rMouse to handle mouse movement.
library(rMouse)
move(0,0) # move to top left corner (0,0)
move(50,30) # move to pixel x = 50, y = 30
left() # left click
right() # right click
Under the hood it still uses Java's robot.
Similarly, KeyboardSimulator package published in 2018 seems to be doing pretty much the same thing
If you are using Windows, library(KeyboardSimulator) is the easiest way.
You can use it to make a bot in R
see the example:
Move Mouse in R (RStudio)
make a bot in R (Rstudio) for social media
What operating system? In Linux, you could use xdotool and call it from the R system function.
> mousemove=function(x,y){system(paste0("xdotool mousemove ",x," ",y))}
> mousemove(0,0)
> mousemove(500,500)
Note these are screen coordinates, nothing to do with the coordinates in your R graphics window, but you weren't clear about what you wanted. You might be able to get the screen coords of your R graphics window with some other X11 utilities and position on a plot if that's what you want.
In Windows, there's probably some other mouse-tweaking program you can leech onto. IDK.
xdotool info: http://tuxradar.com/content/xdotool-script-your-mouse
further reading of that article shows how to activate particular windows and do mouse actions in them.
Related
I am currently learning Julia and have been practicing in the Jupyter notebook environment. However, the ProgressBar package (similar to TQDM in python) is updated every new line instead of updating on the same line (picture attached). Is there any way to fix this? Thanks.
UPDATE : Here is the full function that I wrote.
function spike_rate(raw_dat, width)
N = size(raw_dat)[1]
domain = collect(1:N);
spike_rat = zeros(N);
for i in ProgressBar(1:N)
dx = i .- domain;
window = gaussian.(dx, width);
spike_rat[i] = sum(window .* raw_dat) ./ width;
end
return spike_rat;
end
This seems to be a known issue with ProgressBars.jl, unfortunately. It's not clear what changed to make these progress bars not work properly anymore, but the maintainer's comment says that tqdm uses "a custom ipywidget" to make this work for the Python library, and that hasn't been implemented for the Julia package yet.
To expand on #Zitzero's mention of ] up, that calls Pkg.update() which also prints a progress bar - so the suggestion is to use the mechanism Pkg uses for it. Pkg has an internal module called MiniProgressBars which handles this output.
Edit: Tim Holy's ProgressMeter package seems well-maintained, and is a much better option than relying on an internal non-exported Pkg submodule with no docs. So I'd recommend ProgressMeter over the below.
The Readme mentions a caveat regarding printing additional information with the progress bar when in Jupyter, which likely applies to MiniProgressBar as well. So, using ProgressMeter, and separating the progress output vs other relevant output to different cells, seems like the best option.
(not recommended)
using Pkg.MiniProgressBars
bar = MiniProgressBar(; indent=2, header = "Progress", color = Base.info_color(),
percentage=false, always_reprint=true)
bar.max = 100
# start_progress(stdout, bar)
for i in 1:100
sleep(0.05) # replace this with your code
# print_progress_bottom(stdout)
bar.current = i
show_progress(stdout, bar)
end
# end_progress(stdout, bar)
This is based on how Pkg uses it, from this file. The commented out lines (with start_progress, print_progress_bottom, and end_progress) are in the original usage in Pkg, but it's not clear what they do and here they just seem to mess up the output - maybe I'm using them wrongly, or maybe Jupyter notebooks only support a subset of the ANSI codes that MiniProgressBars uses.
There is a way, the package module does that as far as I know when you do:
] up
Could you share a little of your code?
For example, where you define what is written to the console.
One guess is that
print("text and progressbar")
instead of
println("text and progressbar")
could help, because println() always creates a new line, while print() should just overwrite you current line.
I'm an Octave noob but I'm trying to display a graph at the same time as an input in the terminal however the graphics only update after the input therefore I get an unloaded graph:
This is the code:
f=figure;
imshow(img);
pause(1); % FIX THIS!
in=input('Input required:', 's');
Pausing for 1 second is sketchy because it doesn't always the graph but without a pause it doesn't even enter the graphics loop. Is there someway to block until the graph is loaded before continuing? I wasn't able to find the required function in the documentation.
You can use drawnow to force the graphics to render and the event queue to be flushed.
f = figure();
imshow(img);
drawnow
in = input('Input required:', 's');
I've made a gui with a button, the handler of which executes a plot method of a class I made, it uses ggplot2 and grid/gridExtra in a normal R session to put together the plot. It works fine using the plot() function in console. My button/handler is below:
Plotbutton <- gbutton("Plot!", container=MainWindow,
handler=function(h,...){
plot(analysis, linesplot=svalue(linecheck), lineplot.legend=svalue(linelegcheck), baseannotate=svalue(bpcheck), bpfreq=as.numeric(svalue(bpspin)), mosaic.bars=svalue(mosaiccheck), mosaic.scale=as.numeric(svalue(mosaicspin)), combine.plots=svalue(combinecheck), condense.mosaics=svalue(condensecheck), labfontsize=as.numeric(svalue(fontspin1)), legfontsize=as.numeric(svalue(fontspin2)))
})
I'm not sure of the reason, but loading gWidgets, gWidgetstcltk, and the package required for my plot method, and then clicking the button, nothing is plotted to the R graphics environment, however in RStudio the plot panel is not updated until the GUI is exited. The graphic does appear in a window in the normal Windows RGui though.
Can anyone suggest why this is happening?
The reason why it works from the R-console and not from a function is that the R-console will invoke print() automatically if nothing else is stated. Within a function R does not do this, so if you want to print a graph, you must explicitly state print(graph). Try
print(plot(analysis, linesplot=svalue(linecheck), lineplot.legend=svalue(linelegcheck), baseannotate=svalue(bpcheck), bpfreq=as.numeric(svalue(bpspin)), mosaic.bars=svalue(mosaiccheck), mosaic.scale=as.numeric(svalue(mosaicspin)), combine.plots=svalue(combinecheck), condense.mosaics=svalue(condensecheck), labfontsize=as.numeric(svalue(fontspin1)), legfontsize=as.numeric(svalue(fontspin2)))
I am currently working on an application of Principal Component Analysis to visual data in R.
In Matlab, one can invoke commands such as "im2double" and "mat2gray" to convert a bitmap into a numerical matrix and back again to an image.
I was wondering whether this can be achieved in R, maybe via additional packages.
I've used the EBImage package (vignette here) available on bioconductor to work with and manipulate images:
# installing package if needed
source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")
library(EBImage)
f = readImage(system.file("images", "lena-color.png", package="EBImage"))
str(f)
#Formal class 'Image' [package "EBImage"] with 2 slots
# ..# .Data : num [1:512, 1:512, 1:3] 0.886 0.886 0.875 0.875 0.886 ...
# ..# colormode: int 2
I was curious enough to try this out; clearly a package is a better solution, but if you really want to stick to base R, this will load a png (albeit upside down and backwards; that's probably fixable). It assumes the presence of the netpbm tools, so probably won't work out of the box on Windows systems.
readPng <- function(pngFile) {
contents <- system(paste('pngtopnm',pngFile,'| pnmtoplainpnm'),intern=TRUE)
imgDims <- strsplit(contents[2], ' ')
width <- as.numeric(imgDims[[1]][1])
height <- as.numeric(imgDims[[1]][2])
rawimg <- scan(textConnection(contents),skip=3)
return(list(
x=1:width,
y=1:height,
z=matrix(rawimg,width),
width=width,
height=height))
}
You can run image(img) on the list returned from this function directly, or access the per-pixel values using img$z.
Two methods to install the package.
install through command line if you have no Editor like RStudio
install the command line by entering into R interpreter using R command in bash.
Go to prompt where you can execute R commands. here these the basic image processing command.
execute this command to install the Bio conductor backage biocLite, which will help to install the EBIMage package( This package is used widely for image processing)
source("http://bioconductor.org/biocLite.R")
install the EMImage package to use image processing commands.
biocLite("EBImage")
Load the EBIMage package to use the image processing
library("EBImage")
# Reading image from computer
img=readImage(files="~/Desktop/Prog/R/tinago.JPG")
display(img)
img1=img+ 0.2 # increase brightness
img2=img- 0.2 # decrease brightness
display(img1) # Display images in browser or graphical window
display(img2) # Display images in browser or graphical window
img3= img * 0.5 # decrease contrast
img4=img * 2 # increase contrast
display(img3); display(img4) # show result images
img5=img^2 # increase Gamma correction
img6=img^0.7 # decrease Gamma correction
display(img5); display(img6) # Display result images
Note : readImage to read the image. Display is used to view the image in Graphical Window.
The relatively new package tiff will read and write TIF images quite nicely.
All the same, for anything other than relatively simple image manipulation, I'd recommend using ImageJ or SAOImage9 from the Harvard-Smithsonian group: http://www.cfa.harvard.edu/resources/software.html .
I've written tools in R to do pixel merging, pixel splitting, Sobel & Hough transforms, decolorization, etc., with great success. Ultimately the choice of application depends on the size of your images and the type of processing you need to do.
I am new to R and trying to use the animation package. From the manual, I tried to run this snippet
library(animation)
oopt = ani.options(interval = 0.2, nmax = 10)
## use a loop to create images one by one
for (i in 1:ani.options("nmax")) {
plot(rnorm(30))
ani.pause() ## pause for a while (’interval’)
}
## restore the options
ani.options(oopt)
but I get the error:
Error in ani.options(oopt) : object 'oopt' not found
I am have the package installed and I am using ver 2.14.2
RStudio can evaluate your code line by line: Ctrl-Enter runs the line at the cursor in the source. You can see in the Console below your source that in this case only one line will have been evaluated.
To run your full script, use 'run all' (Ctrl-Shift-R).
Instead of running from the source code window, you can also type in a line of code directly and evaluate it by pressing Enter.