executing r script from Java: loading libraries - java

I want to use rgp to do a symbolic regression task. I am executing R script from Java using ScriptEngineEx. The R code works perfectly from Rsudio. However, just as I try loading the library rgp in java, I get an error message that "there is no package called 'rgp'".
First thing I tried was using lib.loc parameter for the library() function but got the same error message of not finding rgp.
Second thing I tried was loading other libraries from the same directory as rgp (emoa (also did not work), and manipulate(was successful)). I can not understand why it worked for some packages and not for the others in the same directory
Here is my code:
import org.rosuda.jrs.ScriptEngineEx;
import javax.script.ScriptEngineManager;
import javax.script.Invocable;
import javax.script.ScriptException;
public class RScript {
public static void main(String[] args) throws NoSuchMethodException, ScriptException {
// TODO Auto-generated method stub
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngineEx engine = (ScriptEngineEx) manager.getEngineByExtension("R");
engine.eval("library(manipulate)");
engine.eval("library(emoa)");
engine.eval("library(rgp)");
engine.eval("library(rgp, lib.loc =.libPaths())");
engine.close();
}
The error message that I get:
Error in library(emoa) : there is no package called 'emoa'
Error in library(rgp) : there is no package called 'rgp'
Error in library(rgp, lib.loc = .libPaths()) :
there is no package called 'rgp'
PS:
rgp, manipulate, and emoa are installed in directory:
C:\Users\userName\Documents\R\win-library\3.1
the value of .libpaths() is:
[1] "C:/Users/userName/Documents/R/win-library/3.1"
[2] "C:/Program Files/R/R-3.1.2/library"
both stmts: library(rgp) and library(rgp, lib.loc =.libPaths()) work fine from rStuido.
I hope you can direct me to further inspection to know why loading worked for some and not other libraries thought they are installed in the same location in .libPaths(). And any hint about how to load rgp would be much appreciated.

Related

I am executing .py file in Java using Jython 2.7.2 and getting error as org.python.core.PyException: ImportError: No module named speech_recognition

I am executing .py file in Java using Jython 2.7.2 and getting error as org.python.core.PyException: ImportError: No module named speech_recognition. Can anyone please help resolving the issue.
Attached the code snippet of my java and .py files and error message.
import java.io.IOException;
import javax.script.ScriptException;
import org.apache.commons.exec.ExecuteException;
import org.python.util.PythonInterpreter;
import org.testng.annotations.Test;
public class pythonReader {
#Test
public void record_audio_while_doing_voice_over()
throws InterruptedException, ScriptException, ExecuteException, IOException {
PythonInterpreter python = new PythonInterpreter();
python.execfile("C:\\SpeechtoText\\audio_transcriber.py");
}
}
Python Code : (File Name :audio_transcriber.py)
import speech_recognition as sr
filename = "C:\\SpeechToText\\16-122828-0002.wav"
# initialize the recognizer
r = sr.Recognizer()
with sr.AudioFile(filename) as source:
# listen for the data (load audio to memory)
audio_data = r.record(source)
try:
# recognize (convert from speech to text)
text = r.recognize_google(audio_data)
print(text)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Google Speech Recognition error; {0}".format(e))
print("Transaction complete")
Error Message
org.python.core.PyException: ImportError: No module named speech_recognition
at appium.test.pythonReader.record_audio_while_doing_voice_over(pythonReader.java:18)
You need to install the Python package for SpeechRecognition if you want to use it.
You can install it by running the following command in the terminal:
jython -m pip install SpeechRecognition

GraalVM - embedding python multi-file project in java

I couldn't find a solution create a polyglot source out of multiple files in GraalVM.
What exactly I want to achieve:
I have a python project:
my-project:
.venv/
...libs
__main__.py
src/
__init__.py
Service.py
Example sourcecode:
# __main__.py
from src.Service import Service
lambda url: Service(url)
# src/Service.py
import requests
class Service:
def __init__(self, url):
self.url = url
def invoke(self):
return requests.get(self.url)
This is very simple example, where we've got an entry-point script, project is structured in packages and there is one external library (requests).
It works, when I run it from command-line with python3 __main__.py, but I can't get it work, when embedding it in Java (it can't resolve imports).
Example usage in java:
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
import java.io.File;
import java.io.IOException;
public class Runner {
public static void main(String[] args) throws IOException {
Context context = Context.newBuilder("python")
.allowExperimentalOptions(true)
.allowAllAccess(true)
.allowIO(true)
.build();
try (context) {
// load lambda reference:
Value reference = context.eval(Source.newBuilder("python", new File("/path/to/my-project/__main__.py")).build());
// invoke lambda with `url` argument (returns `Service` object)
Value service = reference.execute("http://google.com");
// invoke `invoke` method of `Service` object and print response
System.out.println("Response: " + service.getMember("invoke").execute());
}
}
}
It fails with Exception in thread "main" ModuleNotFoundError: No module named 'src'.
The solution works for javascript project (having similar index.js to __main__.py, its able to resolve imports - GraalVM "sees" other project's files, but somehow it doesn't, when using python.
I found out, that python is able to run zip package with project inside, but this also doesn't work with GraalVM.
Is there any chance to accomplish it? If not, maybe there is a similar tool to webpack for python (if I could create a single-file bundle, it should also work).
Btw, I don't know python at all, so I may missing something.
Thanks for any help!

IBM Watson Visual Recognition in Java training classifier error

So I want to make a java application in eclipse which the user i will be able to import .zip files. Each .zip file will represent a cat breed. I will click on a "train" button and my program will contact IBM Watson services and create a classifier. Then from a different window, i will import random cat images and the program will show what cat breed is in the image. Everything with the SDKs is fine since I ran some examples from the official Watson site and everything ran smoothly. Problem comes when I try to create my own classifiers. The code you are about to see is also from their site. For some reason the createClassifier method won't take the CreateClassifierOptions object as an argument.
import java.io.File;
import com.ibm.watson.developer_cloud.http.ServiceCall;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognitionCallback;
import com.ibm.watson.developer_cloud.visual_recognition.v3.*;
import com.ibm.watson.developer_cloud.visual_recognition.v3.model.*;
public class TrainningClassifier{
public static void main(String[] args) {
VisualRecognition service = new VisualRecognition(
VisualRecognition.VERSION_DATE_2016_05_20
);
service.setApiKey("aca4433597018de62edafdeebceb2bdc1482496a");
CreateClassifierOptions createClassifierOptions = new CreateClassifierOptions.Builder()
.name("dogs")
.addClass("beagle", new File("./beagle.zip"))
.addClass("goldenretriever",new File("./golden-retriever.zip"))
.addClass("husky", new File("./husky.zip"))
.negativeExamples(new File("./cats.zip"))
.build();
Classifier dogs = service.createClassifier(createClassifierOptions).execute();
System.out.println(dogs); /*error is in the above line.
the createClassifier method.*/
}
}
Error: Exception in thread "main" java.lang.Error: Unresolved
compilation problem: The method createClassifier(ClassifierOptions)
in the type VisualRecognition is not applicable for the arguments
(CreateClassifierOptions)
at testVisualRec.ForAssignment.main(ForAssignment.java:31)
Any ideas?
Found the solution. For some reason eclipse wouldn't recommend this solution I had to experiment. I just added throws IOException in main method. I also put inside the main method System.out.println(new File(".").getAbsoluteFile()); to make sure the path was correct, and it was. (SDK used for this project is 4.0.0, not the newest one. SDK found here: https://github.com/watson-developer-cloud/java-sdk/releases)

Open in default browser exception

I'm using Eclipse to develop Java Desktop applications. The Desktop class has a useful method called browse() which opens an URI in the system's default browser. My problem is that this feature isn't working anymore in Eclipse but still works fine outside of Eclipse e.g. when launching an executable Jar file containing the code.
Here's a short compilable example:
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class OpenExample
{
public static void main(String[] arguments) throws URISyntaxException, IOException
{
Desktop.getDesktop().browse(new URI("https://www.google.com/"));
}
}
I'm receiving the following exception:
Exception in thread "main" java.io.IOException: Failed to open https://www.google.com/. Error message: A device attached to the system is not functioning.
at sun.awt.windows.WDesktopPeer.ShellExecute(Unknown Source)
at sun.awt.windows.WDesktopPeer.browse(Unknown Source)
at java.awt.Desktop.browse(Unknown Source)
at OpenExample.main(OpenExample.java:10)
What could be the problem? Obviously the Java code is right and since it worked before, something must be broken in Eclipse or maybe even Windows.
It might be related this this JDK bug: https://bugs.openjdk.java.net/browse/JDK-8064934
I.e. there might be a real error occurring, but the JDK is reporting the wrong error code because of this bugs.
import java.awt.Desktop;
import java.net.URI;
public class OpenExample {
public static void main(String[] args) throws Exception {
String url = "http://google.com";
if (Desktop.isDesktopSupported()) { // for windows
Desktop.getDesktop().browse(new URI(url));
} else { // for linux
Runtime runtime = Runtime.getRuntime();
runtime.exec("/usr/bin/firefox -new-window " + url);
}
}
}
try this Some times it depend upon OS as well .
Check print Statement giving URL or not .
if it will work please give your review

Using GraphVIZ Native library from Java

I am trying to use graphviz native library from java.I am able to compile the program in Eclipse. But getting exception:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no gv in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1681)
at java.lang.Runtime.loadLibrary0(Runtime.java:840)
at java.lang.System.loadLibrary(System.java:1047)
at org.graphviz.test.Test.<clinit>(Test.java:12)
Could not find the main class: org.graphviz.test.Test. Program will exit.
Here is my code(copied from somewhere of course):
package org.graphviz.test;
import org.graphviz.internal.SWIGTYPE_p_Agedge_t;
import org.graphviz.internal.SWIGTYPE_p_Agnode_t;
import org.graphviz.internal.SWIGTYPE_p_Agraph_t;
import org.graphviz.internal.gv;
public class Test {
static {
System.loadLibrary("gv");
}
public static void main(String[] args) {
SWIGTYPE_p_Agraph_t g, sg;
SWIGTYPE_p_Agnode_t n, m;
SWIGTYPE_p_Agedge_t e;
g = gv.digraph("G");
System.out.println(gv.setv(g,"aaa","xxx"));
System.out.println(gv.getv(g,"aaa"));
sg = gv.graph(g,"SG");
n = gv.node(g,"hello");
System.out.println(gv.getv(n,"label"));
System.out.println(gv.setv(n,"aaa","xxx"));
System.out.println(gv.getv(n,"aaa"));
m = gv.node(g,"world");
System.out.println(gv.getv(m,"aaa"));
e = gv.edge(n,m);
System.out.println(gv.setv(e,"aaa","xxx"));
System.out.println(gv.getv(e,"aaa"));
gv.rm(e);
gv.rm(n);
gv.rm(m);
gv.rm(g);
g = gv.readstring("digraph G {a->b}");
gv.rm(g);
g = gv.read("hello.gv");
gv.layout(g,"dot");
gv.render(g,"png","hello.png");
gv.rm(g);
}
}
I have pointed the library correctly, but at runtime getting UnsatisfiedLinkError. Any one ever tried using the graphviz native library?Please let me know how to configure JNI.
I believe you're problem is that you are trying to import from gv, but you aren't specifying what you want to import. It's kind of like if you were to just write ---
import org.graphviz.internal;
Instead, try importing a specific library from the gv library. For example, if you want a directed graph, you would probably do something like this ---
import org.graphviz.internal.gv.digraph;
Take a look at the following document and see if it helps at all. It might give you a better idea of where gv comes from and how you can import the methods associated with it.
http://www.graphviz.org/pdf/gv.3java.pdf
Get graphviz-java
Make sure you have graphviz-java installed. For MacPorts this should work like this:
sudo port install graphviz +java
This actually failed for me on the first try and complained about swig-java, this fixed it:
sudo port install swig-java
sudo port install graphviz +java
Now the library is installed under /opt/local/lib/graphviz/java for me, search for libgv.jnilib if you don't find it there.
Setup class path
I compiled in Eclipse, for that I added /opt/local/lib/graphviz/java to the build path as an external class folder.
Compile
This is a simple example that writes an image. Note that System.loadLibrary("gv") must happen before calling anything in graphviz.
import org.graphviz.SWIGTYPE_p_Agedge_t;
import org.graphviz.SWIGTYPE_p_Agnode_t;
import org.graphviz.SWIGTYPE_p_Agraph_t;
import org.graphviz.gv;
public class Main {
static {
System.loadLibrary("gv");
}
public static void main(String[] args) {
SWIGTYPE_p_Agraph_t g = gv.digraph("G");
SWIGTYPE_p_Agnode_t n = gv.node(g, "hello");
SWIGTYPE_p_Agnode_t m = gv.node(g, "world");
SWIGTYPE_p_Agedge_t e = gv.edge(n, m);
gv.layout(g, "dot");
gv.render(g, "png", "hello.png");
}
}
Run
Run with java.library.path=/opt/local/lib/graphviz/java, e.g. -Djava.library.path=/opt/local/lib/graphviz/java as VM arguments in an Eclipse run configuration.

Categories

Resources