I have successfully drawn a single graph using Java, JavaGD and R. I followed this tutorial .
Now, I have an R-script, which reads a CSV file, does some calculations. At the end, it plots 8 different graphs. When I run this script using Java/JavaGD, only 1st and 8th plot are visible. 2nd through 7th are on "inactive" windows, which are blank. I am using the exact same code as in the above mentioned link/tutorial. So I guess something is getting overwritten.
How can I draw them on proper windows? Also, the first window, if re-sized, becomes blank. How to solve this issue?
Please don't hesitate to ask for clarification, if needed. I am not sure how well I have explained the problem.
Any help/reading material is greatly appreciated.
Update 1:
Currently, I am using this code:
public static void main(String[] args) {
// TODO Auto-generated method stub
Rengine re;
String[] dummyArgs = new String[1];
dummyArgs[0] = "--vanilla";
re = new Rengine(dummyArgs, false, null);
re.eval("library(JavaGD)");
// This is the critical line: Here, we tell R that the JavaGD() device that
// it is supposed to draw to is implemented in the class MyJavaGD. If it were
// in a package (say, my.package), this should be set to
// my/package/MyJavaGD1.
re.eval("Sys.putenv('JAVAGD_CLASS_NAME'='test/MyJavaGD1')");
re.eval("JavaGD()");
// re.eval("plot(c(1,5,3,8,5), type='l', col=2)");
// re.eval("source(\"C:\\Documents and Settings\\username\\My Documents\\Test Data\\BoxPlot.r\");");
re.eval("source(\"C:\\\\Documents and Settings\\\\username\\\\My Documents\\\\sampleRScript.R\")");
re.end();
System.out.println("Done!");
}
Part of the script:
par(las=2,mfrow=c(2,1))
PlotData <- subset (m4, select=c(LotNo,def,cavity,Lift), subset=(cavity=="1"))
boxplot(Lift ~ def, data=PlotData, main="Number 1")
hist(PlotData$Lift,50, main="", xlab="Lift", ylab="Frequency")
win.graph()
par(las=2,mfrow=c(2,1))
PlotData <- subset (m4, select=c(LotNo,def,cavity,Lift), subset=(cavity=="2"))
boxplot(Lift ~ def, data=PlotData, main="Number 2")
hist(PlotData$Lift,50, main="", xlab="Lift", ylab="Frequency")
win.graph()
par(las=2,mfrow=c(2,1))
PlotData <- subset (m4, select=c(LotNo,def,cavity,Lift), subset=(cavity=="3"))
boxplot(Lift ~ def, data=PlotData, main="Number 3")
hist(PlotData$Lift,50, main="", xlab="Lift", ylab="Frequency")
.
.
.
You'll need to tell the R instance about your initialized JRI using .jengine(), otherwise it can't issue callbacks , e.g. to resize the window. As for blanked windows you'll need to provide the code that you use.
(You may want to use stats-rosuda-devel to discuss rJava/JRI/JavaGD-related issues there.)
Related
I am currentrly working on a Way to visualize Fractals in Java. The mathematics behind it work perfectly fine and I am very happy with how the Pics turn out. Now i want to take these Images and turn them into a Video. I've written a Java Program that produces any number of Pictures and saves them (alphabetically) in a new directory. Now I need a way for Java to convert these Images into a Video.
I know there are solutions such as ffmpeg, however I need this process to be repeatable, so I don't think a Command Line Application would be the best Option.
Is there any Way to implement such a function into Java directly ?
If you're willing to use a third party library and the platform is supported (Windows or Linux, 64bit). You can use Pilecv4j (Full disclosure, I'm the main committer).
There's a test checked in that does exactly this. You can find it here: TestSplitIntoFiles.java
Here is the pertinent function that does this with the minor difference that it's not reading the image file names from the contents on the disk:
private static void encodeFiles(final File imageDir, final long numFrames, final File outputVideo) throws IOException {
try(final CvMat firstFrame = ImageFile.readMatFromFile(new File(imageDir, "image-0.jpg").getAbsolutePath());
final EncodingContext ectx = Ffmpeg2.createEncoder()
.outputStream(outputVideo.getAbsolutePath())
.openVideoEncoder("libx264", "vidEncoder")
.addCodecOptions("preset", "slow")
.addCodecOptions("crf", "40")
.enable(firstFrame, false)
;) {
final VideoEncoder ve = ectx.getVideoEncoder("vidEncoder");
ectx.ready();
LongStream.range(0, numFrames)
.mapToObj(fn -> new File(imageDir, "image-" + fn + ".jpg").getAbsolutePath())
.forEach(frameFile -> {
try(CvMat mat = uncheck(() -> ImageFile.readMatFromFile(frameFile));) {
ve.encode(mat, false);
}
});
}
}
If you decide to give it a try, let me know if you run into any issues. You can use the Issues on GitHub. I've been using it professionally for a while.
Also, see the answer to this question: Read a mp4 and write to anther mp4 creates bigger size
I am currently working on a TESTING a game project. Below are the details about my project.
This is my first Maven Project and I really have very less idea on it's working methodology.Please help me!
1] GameProject - Is a Maven Project in Eclipse. The main goals of this project is to create a game player (also called bot) for a First Person Shooter game. When you run this Java Application, it will run the game, with a new player, whose actions will be determined by the code I wrote up in this project.
It has lot of java files, and one main class. There is a class called PlayerInfo.Java, which contains the code to decide, what the player should do while playing the game. It is like the brain of the player. Let's say it has around 40 variables, which decides the behavior of the Player.
Example - One of the variable in the class may be like Player_HEALTH_Level = 50. This means that Player should have atleast 50% of the health to be able to fight with other players. If it's less than this, then He/she should find a health Pack and increase the value. Similarly I have few other 39 parameters.
2] Testing Project - This too is a maven Project. Which is designed to test my Player(bot) performance in the game. Such as, how many times he wins the match, number of weapons he collects, etc.
The way this project is designed that, it requires the path for the JAR file of the GameProject as a input in the Main Method. Then, It runs the bot/player for the given JAR and prints out the results of the game in a separate file.
Example -
In the Main Method I specify something like this
String playerJAR_Path = "C:\Users\Player\Netbeans\GameProject-one-SNAPSHOT-jar.jar"
Note:- The above is the path for GameProject JAR folder. Basically, I just build the GameProject as "Maven Install" and it will create a JAR for me. Then use the path address on the second Project.
Hope this gives you some idea about my project structure.
Issue
The real issue is I have to basically run my GameProject around 500 times and capture the results. I am using Genetic Algorithms to evolve the Player Parameters and improve them over the time.
Currently, I can have a for Loop in my TestingProject, to loop 500 Iterations and it takes cares of executing the GameProject 500 times for me.
In order to apply Genetic Algorithms, After the end of EACH iteration, I have modify the parameters in the Player/bot Behavior (Specifically in file PlayerInfo.Java). Something like, I may change the value for Player_HEALTH_Level=48 for the iteration 2 run, then to 56 on the third run and so on.
In oreder to do this, I need to acheive the follwing in my Testing Project inside my FOR Loop.
Perhaps may be like this
*For int i=1 to 500 do ;
String playerJAR_Path = "C:\\Users\\Player\\Netbeans\\GameProject-one-SNAPSHOT-jar.jar";
Run the Testing();
Modify the parameters in PlayerInfo.Java (Inside GameProject)
Change the values of 40 Variables in that class.
Build the GameProject Project so that, it creates a UPDATED JAR File
End FOR;*
I am really confused, as in how to build the first project automatically, and also how to change the values of the class variables.
Can any one please help me on giving some suggestions on how to achieve the same. I don't mind in what way to do this. Just be able to AUTOMATE This whole testing Process.
Other details:
1. System - Windows 7, Intel Xeon 12 Core Processor, 24GB RAM, 3 TB Flash Drive.
2. For each iteration on the For-Loop, it produces a million record (As in the console window of the Eclipse will contain a Million lines for each iteration in for loop). I also need to know, how to write this to a file, instead of flooding console.
When I tested this initially, Eclipse hang up with Out of Heap Memory Error. Then I have increased all RAM values to 2GB in the eclipse INI file. This somehow managed not to crash my eclipse with memory errors.
EDIT - Adding code to Question.
public class PlayerInfo {
public int minDistanceToFollowEnemy = 200; // This is in UT Units. If Bot sees an enemy over this distance
// He/she tries to follow him and attack.
public int probabilityToFollowEnemy = 50; // Distance between the bot and Enemy will be calculated in real time.
//If the distance is lower, chasing priority is Higher.
public int probabilityOfFlagHolderReturn = 50; // If the Bot holds the Enemy flag, what's the probability that he/she
//Runs to home base directly without being distracted to collect items, fight with enemies?
public int probabilityOfGettingEnemyFlag = 10; // If bot does not carries the enemy flag, it's probability to hunt for enemy flag.
public double maxDistanceToGetHealthPack = 1000 ; // If Bot finds a health pack within this distance && It needs a Health pack
// Then It searches one and grabs it.
public int minHealthLevel = 30; // Min Health level before bot starts looking for Health Pack
public int probabilityToGetHealthPack=80; // Probability that Bot will Pick one health pack if it sees on its path/view.
public int probabilityToSelectItem = 8 ; //Based on the current Bot's view, what's the probability that it will select to choose the item.
}
Main Class PlayerBot.java IN GameProject
public static void main(String args[]) throws PogamutException {
AddNativeBot addbot = new AddNativeBot();
//addbot.addNativeBots(4);
// starts 2 or 4 CTFBots at once
// note that this is the most easy way to get a bunch of bots running at the same time
new UT2004BotRunner<UT2004Bot, UT2004BotParameters>(CTFBot.class, "PlayerInfo").setMain(true)
.startAgents(
new CTFBotParams().setBotSkin("HumanMaleA.MercMaleC").setBotType(0).setSkillLevel(5).setTeam(0).setAgentId(new AgentId("Attacker 1"))
//,new CTFBotParams().setBotSkin("HumanFemaleA.MercFemaleA").setSkillLevel(5).setTeam(0).setAgentId(new AgentId("Attacker 2"))
//,new CTFBotParams().setBotSkin("HumanMaleA.MercMaleA") .setSkillLevel(5).setTeam(0).setAgentId(new AgentId("Attacker 3"))
//,new CTFBotParams().setBotSkin("HumanFemaleA.MercFemaleB").setSkillLevel(5).setTeam(0).setAgentId(new AgentId("Attacker 4"))
//,new CTFBotParams().setBotSkin("HumanFemaleA.MercFemaleB").setSkillLevel(5).setTeam(1).setAgentId(new AgentId("Attacker 5"))
//,new CTFBotParams().setBotSkin("HumanFemaleA.MercFemaleB").setSkillLevel(5).setTeam(1).setAgentId(new AgentId("Attacker 6"))
);
}
//Project 2
public static String[] getArgs_CTF_2v2v1() {
return new String[] {
"-y", // MATCH TYPE
"CTF", // CAPTURE THE FALG
// GENERIC CONFIG
"-u",
"C:\\UT",
"-h", // human-like-log
"-r",
"./results",
"-n",
"Test-CTF-2v2v1", // MATCH NAME
"-s",
"CTFServer",
// CUSTOM BOTS CONFIG
"-a",
"C:\\Users\\Project\\Downloads\\CTFbot\\target\\mavenproject1-1.0-SNAPSHOT.one-jar.jar;C:\\Users\\Project\\Downloads\\CTFbot\\target\\mavenproject1-1.0-SNAPSHOT.one-jar.jar",
"-b",
"CTFBot1;CTFBot2",
"-l",
"1;2",
"-k",
"HumanFemaleA.NightFemaleA;HumanFemaleA.NightFemaleA",
"-i",
"0;1",
// NATIVE BOTS CONFIG
"-c", // NATIVE BOT COUNT
"2",
"-d", // NATIVE BOT NAME
"Native1;Native2",
"-e", // NATIVE BOT SKILL
"5;6",
"-g", // NATIVE BOT TEAMS
"0;1",
// HUMANS CONFIG
"-x",
"1", // HUMAN COUNT
"-z",
"1",
// CAPTURE THE FLAG SPECIFIC CONFIG
"-m",
"CTF-LostFaith",
"-f",
"1", // SCORE LIMIT
"-t",
"5", // TIME LIMIT
};
}
//Main Class
public static void main(String[] args) throws JSAPException {
// -----------
// FOR TESTING
// -----------
//args = getArgs_DM_2v2v1();
//args = getArgs_TDM_2v2v1();
args = getArgs_CTF_2v2v1();
// --------------
// IMPLEMENTATION
// --------------
initJSAP();
header();
readConfig(args);
sanityChecks();
switch (matchType) {
case DM:
executeDeathMatch();
break;
case TDM:
executeTeamDeathMatch();
break;
case CTF:
executeCaptureTheFlag();
break;
case DD:
executeDoubleDomination();
break;
default:
fail("Unsupported match type specified " + matchTypeName + " recognized as " + matchType.shortName + "[" + matchType.name + "].");
}
}
}
Holy wall of text.
Ok, couple of things. Just because Maven created a jar for you, doesn't mean you have to use the jar. You could call the class directly.
So your testing would instantiate the class, instead of trying to run the class from the command line.
Second. You don't have to modify the internal state of the variables directly. My advice is for you to save the changes to a file and have your Player read the file. For the next iteration you modify the file and run the Player again.
Let me know if you have specific questions and I'll improve the answer.
I am trying to get the values of from the following xml, but the code i've written returns a bunch of question-marks instead of what it was supposed to return. I'm guessing it must be some encoding issue, but I haven't found anything about that yet on the web.
<channel>
<title>ΖΩΔΙΑ Προβλέψεις, 1 Σεπτεμβρίου 2012</title>
</channel>
zodiaClass.java
public class zodiaClass {
#Root(strict = false)
public static class Example {
#Path("channel")
#Element
private String title;
}
public static void main(String[] list) throws Exception {
Persister persister = new Persister();
File file = new File("example1/download.xml");
Example example = persister.read(Example.class, file);
System.out.println(example.title);
}
}
output:
????? ??????????, 1 ??????????? 2012
[As requested, this is a translation of the above comment thread into the form of an answer.]
I suspect that the issue is with the output, rather than with the input. Not all command-line environments support Greek. To test this, you can try System.out.println("\u03B1"); if your command-line supports Greek, it should show up as α (lowercase alpha).
In one of your comments, you mention that you're using Eclipse. If it does turn out that the problem is with the output, then a Google search for Eclipse console encoding suggests that there are a number of different approaches that people have tried successfully — everything from modifying the relevant Run Configuration within Eclipse to editing eclipse.ini and the system encoding.
Update: [not really an update, but I'm trying to maintain the illusion of a regular answer . . .] I see from your follow-up comment that you were able to change the console encoding by changing the encoding of the *.java file. Cool!
I'm reading the chapter 12 on the Combined Pattern in Head First Design Patterns.
On page 541,the sample DJView,it cant't run correctly in my computer.when i press the 'start', the program only sounds once rather than circularly .
i'm not sure whether because of the environment of my system.
but if i add one line code in the method meta of the class BeatModel,it works.like:
public void meta(MetaMessage message) {
if (message.getType() == 47) {
beatEvent();
sequencer.setMicrosecondPosition(0); //add this line
sequencer.start();
setBPM(getBPM());
}
}
can anyone tell me why? i'm so confused,is something wrong with the code given by the book or some other reason? help me .
Thanks in advance!!
So sorry,the code is long so i could not put all here,you could download from the offical website,here is the link http://www.headfirstlabs.com/books/hfdp/HeadFirstDesignPatterns_code102507.zip
you can find the sample in this folder '\HeadFirstDesignPatterns_code102507\HF_DP\src\headfirst\combined\djview'.
run the class DJTestDrive.java
Look forward to your help.
EDIT #2: For completeness' sake, the author of Head First Design Patterns Elisabeth Freeman herself has made a note of the fact that the code in her book has only been tested with Java 1.4. She has promised to take our feedback into account.
EDIT: There seems to be a bug with the Sequencer.setTempoInBPM during play. Your approach with setting the microsecond position to 0 is the right approach -- it basically rewinds the sequencer as soon as it ends (i.e. message type = 47).
Unfortunately, the sample code seems incorrect. There are several problems:
The sequencer is not initialized to play in a loop
The meta() method resets the BPM and renotifies all listeners, but does not reset the sequencer to its original position, which you did to get it to work. However, this method does not need to do anything so long as the sequencer is set to play in a loop.
The off() method sets the BPM to 0, which will fast forwards the sequencer to the end of all loops -- which means next time you start the player, it will start from the end and will play nothing.
These change should do the trick:
#1 In method BeatModel.buildTrackAndStart, add sequencer.setLoopCount as follows:
public void buildTrackAndStart() {
// ...
try {
sequencer.setSequence(sequence);
sequencer.setLoopCount(Integer.MAX_VALUE); // play forever
} catch(Exception e) {
// ...
}
#2 Remove all statements from method BeatModel.meta(MetaMessage):
public void meta(MetaMessage message) {
}
#3 Remove setBPM(0) from method BeatModel.off():
public void off() {
// -- remove this -- setBPM(0);
sequencer.stop();
}
On Java 8 just adding the
sequencer.setMicrosecondPosition(0);
to the BeatModel.meta() makes it work just fine!
Greetings to all,
hebgeenbrug
I meet the similar error when reading. in my computer the processBar doesn`t update.
1.First I add "sequencer.setMicrosecondPosition(0);" in "public void meta(MetaMessage message)" ;
2.Second I delete "sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);" in "public void setUpMidi()"; it continuous sound but "meta(MetaMessage message)" will not be notice,so ProcessBar not update.
3.Then it works
may be my experience can help others.
I am using JChart2D for my Java desktop application and followed that example:
http://jchart2d.sourceforge.net/usage.shtml
That example makes connections between points however I need individual points.
I mean I get something like:
But I want something like:
PS: Graphic examples are different just I wanted to show difference between individual points and line between points.
Close, but no cigar. The correct API Call is:
Chart2D chart = new Chart2D();
ITrace2D trace = new Trace2DSimple();
// Add the trace to the chart:
chart.addTrace(trace);
trace.setTracePainter(new TracePainterDisc(4));
The call
trace.setTracePainter(new TracePainterDisc(4));
does the trick.
I think the answer lies in the link you posted above.
Create a trace (instance of ITrace2D) and set the PointPainter e.g. to PointPainterDisc.
Derived from the API javadoc:
Chart2D test = new Chart2D();
JFrame frame = new JFrame("Chart2D- Debug");
frame.setSize(400,200);
frame.setVisible(true);
ITrace2D atrace = new Trace2DLtd(100);
atrace.setPointHighlighter(new PointPainterDisc(5));
test.addTrace(atrace);
while(expression){
atrace.addPoint(adouble,bdouble);
....
}
trace.setTracePainter(new TracePainterDisc());