Numerical Recipes and JAVA


remagnino
04-26-2002, 04:16 AM
Good Morning

An obvious question. When are you going to port NR to JAVA?


Thank you

Paolo

William Vetterling
04-27-2002, 08:07 AM
Paolo,

Actually, I have been doing some JAVA translations on the side for a few months, and I currently have cursory translations for nearly all of the 350 Recipes and about 80 of the Example routines. (By "cursory", I mean that they all compile, but until the example routines are finished I won't know how many of them need debugging.)

It would premature to foist them upon any NR users before rudimentary testing, and there are many fundamental issues of style and organization to be resolved as well. Perhaps in a few months we will have some available for beta testing and comment. In the meantime, I may post some questions for public comment on this forum, to help educate myself on the best way to handle some of the programming problems. I hope you can give us some good ideas!

kieran
04-29-2002, 12:03 AM
I'd love a copy of polint.java for a plugin I'm working on to integrate into ImageJ (see http://rsb.info.nih.gov/ij/) - so that I can investigate properties of a computerized scatter correction scheme for digital radiographic images.

Kieran
--

ing
07-07-2002, 08:41 PM
Since the syntax for C# and Java are nearly identical, I hope it's okay for a C# programmer to use this thread instead of starting a C# thread.

William had mentioned beta versions of NR in Java. I would be interested in getting ahold of some Java (or C#) code, as a return favor I would be willing to try and help with some of the beta testing or code conversion (I can read in C and write in C#/Java). Right now I want to get ahold of Chapter 11 (Eigensystems), although I am generally interested in any code I can get.

I am in the process of porting some NR code over to C#. I'm just starting, so not too much work has been done so far. I've got some (minimal) interpolation stuff and I'm working on Eigensystems right now. Is anybody else doing the same thing? Wanna combine some code?:D I don't have too much yet, but give me a month or two and I'll have libraries.

Bilbo
11-01-2002, 01:42 PM
Helo :)

We had been using NR extensively for two years in school. I would be glad at that time to have had Recipes in Java, because I've been very happy about doing physics simulations in Java, and not always successful in porting C code.

The message form William Vetterling about his translating NR to java is very cool :cool:, it would be interesting to hear updates from him.

What are the plans about releasing NR in any other language?



Thank you for answering

William Vetterling
11-03-2002, 06:31 PM
Well, Bilbo, since you asked:

We are delighted to have so much interest in the JAVA code currently in development. Several or our readers have written encouraging email messages to show support, offer help, and request advance versions of various codes. Here is a short progress report:

Code development is steady, but not fast. There are about 600 translations to accomplish (Recipes and Examples combined), and conversion into structured code is a thoughtful and time-consuming process. First pass translations of all the code has been accomplished, and a large number of them actually work! We are currently in the process of establishing a more standard coding format, adding "javadoc" documentation, and revising and testing original translations.

In this work, we are consulting with two JAVA officionados, who are helping us to maintain consistency with common practice in JAVA coding. We have had many more offers of help, but we are heeding the addage that "too many cooks" will spoil the broth. In any case, it is difficult to find any two experts that agree on style, and if this doesn't spoil the broth, it certainly thickens it.

Sorry, but we are not honoring requests for advance copies of the code at this time. At some point, perhaps in late spring of 2003, the code will be close enough to final form that we will invite a limited number of beta testers to take a look at it, and then a few months later we will make it more generally available.

We will post periodic progress reports on this board, particularly if there are any substantial changes in this schedule. We will also ask for help here if we run into any really tacky problems.

Patience will be rewarded!

kutta
11-17-2002, 12:03 AM
While wishing for a great success at the subject target of the NRForum,as a onepointed target of contributing towards the goal,may I request the author to make use of the the javaprogram that has been submitted under NR in other laguage which will definitely enable the maker of the javacode for NR easier(Pl Ref functiion6.zip attachment for example)
Inorder to get myself continued on these lines of help pl let me know what are NP class?Last but not the least pl pass ur commendable feed back on thes codes?Ur reply in the making of the codes be availble by 2003 is rather very much good but try for an earlier publishing as u know languages become outdated

alchemist
02-26-2003, 10:01 PM
Guys,

Would any of you happen to have "tred2" and "tgli" methods from 11.2 and 11.3 coded in Java? :confused: Please help!

kutta
03-21-2003, 06:44 AM
Hello
Even though the coding of the subject item has not been made

I sincerely feel that you (or Whosoever wants to code) try out the

possibility of using any one of the general purpose data structure

before going for coding.In this connection necessary guidance for

the selection of data structure has been enclosed for your perusal

Best Wishes

:)

alchemist
03-22-2003, 12:51 PM
thanks, kutta

Kay
05-07-2003, 02:08 PM
Hi, since it is late spring of 2003 already, I am wondering how is the author's porting NR to Java going? Is it ready for testing yet? I am really interested in using some routines in my project, and I am not very fond of JNI everything.

thank,
-Kay

William Vetterling
05-08-2003, 07:29 PM
Kay,

Thanks for your very timely question.

Here is the state of affairs. As of early March, I have had all of the Recipes and their corresponding example routines translated, except for approximately ten. Those ten generally have some difficult or peculiar nature to them, such as maintaining arrays of file streams, or doing some sort of tricky manipulations that are very sensitive to details of data representation. There is nothing left that couldn't be solved with a week of uninterrupted work.

Unfortunately, for the past four weeks I have not been able to devote any time to the translation, due to competing responsibilities, but I do expect to be free to continue in approximately two weeks.

Keep a good thought. The job is nearly done!

agatlin
05-30-2003, 04:44 PM
I am an experienced C# developer and am very interested in the C# port. I would be interested in helping.

Kay
05-30-2003, 10:23 PM
Hi,

I am wondering how the java porting is going...Is it finished? I am eager to try it out. How to apply for being a beta tester?

thanks,
-Kay

stdsoft
12-09-2003, 01:09 AM
After reviewing posts from the last two years, it seems the Java port has been going on for quite some time. Is the port still in process, or has it been suspended? If an early version is available, I would certainly be interested in taking a look.


Thanks,
Michael

agatlin
12-09-2003, 08:52 AM
I am still interested in a beta version as well.

adaptor
01-19-2004, 12:59 PM
I'm currently working on porting some NR routines to Java. I've done LU decomposition and am working on SVD right now. I'm having a problem such that the routine won't converge. I believe I've made all the appropriate corrections, etc, and have gone over my code many times to ensure that there are no typos (there still could be, but I'm pretty sure there aren't). If anyone would be interested in helping me track down the problem, or if you've ported it successfully yourself and would be willing to share, I'd really appreciate it. I've attached my java code as svtest.txt. Please post reply here, or email me at minerva@techemail.com.
Thanks,
m

vjsaraswat
04-02-2004, 07:57 AM
Let me add my voice ... anyone know of an NR implementation accessible from Java?

Also, if people have tried to implement NR in Java (as opposed to making C libraries available via JNI) and run into performance problems, or language limitations, I would be very interested.

(Full disclosure: I am currently a researcher at IBM, though my interest in this topic is a long-standing one.)

tdunning
01-19-2005, 01:12 AM
Could Bill Vetterling's partial port please be released or could he release his claim that he is working on a port?

A claim like that tends to inhibit alternative efforts. Since no apparent progress is being, alternatives are sorely needed!

Bianca Franco
01-24-2005, 06:49 PM
Hi all,
I really need a help to make sure Quasi Newton algorithm from topic 10.7 is gonna retrieve Fpr, Feq and Fpj values just like Statistica tool does, from the formula:
E=( (w1*ps + w2*pm + w3*pc)*Fpr )/(p*Feq*Fpj)
The values w1, w2, w3, ps, pm, pc, p values are known and then I could find the Effort E.

Even before being sure the algorithm is the right one, I´ve translated it from C to Java and it is attached.
Can someone help me on this?
Thanks in advance,
Bianca.

tdunning
01-24-2005, 08:42 PM
Apparently the code you posted was the result of a C to Java translator. As such, it is pretty hideous.

I frankly would not have enough confidence in code like this to use it. Moreover, the heavy-handed shoehorn that the translator has to use to get Java to be C makes the code essentially unmaintainable.

Here is a version of linsrch alone that follows somewhat more reasonable structure. This version depends on a class called RealFunction (also enclosed) and the Jama matrix package. RealFunction is an interface which describes functions that can be called with Matrix or double[] arguments and which return a scalar double quantity. Jama is a simple public domain matrix package that suits my needs. The version I use has been slightly modified (for instance, I added the max function and cousins).

This translation illustrates what I mean when I say that we shouldn't slavishly translate the current C code to Java. Instead, we should use the capabilities of Java to make things more clear.

Please note that I haven't built a test suite for this code, nor debugged it. The transformations applied have not been massive, but it is quite possible that I have introduced small errors.

This doesn't help the previous poster very much, but it does further the topic. To help Bianca, I would suggest an off-line conversation since the function she is trying to solve appears relatively simple. My direct email address starts with tdunning and ends with san.rr.com and has the normal character in between.

tdunning
01-24-2005, 09:17 PM
The code I translated looks like it is more likely to be correct than I thought. Here is a Junit test case that demonstrates at least minimal function:

package com.tdunning.nr;

import Jama.Matrix;
import com.tdunning.MatrixTestClass;
import com.tdunning.math.AbstractRealFunction;
import com.tdunning.math.RealFunction;

/**
* Tests the java port of LineSearch (based on linsrch from Numerical Recipes.
*/
public class TestLineSearch extends MatrixTestClass {
public void test1() {
// these can be altered to give a more interesting problem
final Matrix A = new Matrix(new double[]{1, 0, 0, 0, 1, 0, 0, 0, 1}, 3);
final Matrix b = new Matrix(new double[]{1, 2, 3}, 3);

// quadratic bowl
RealFunction f = new AbstractRealFunction() {
public double eval(Matrix x) {
x = x.minus(b);
return x.transpose().times(A.times(x)).get(0, 0);
}
};

// gradient of said bowl
MatrixFunction df = new AbstractMatrixFunction() {
public Matrix eval(Matrix x) {
x = x.minus(b);
return A.times(x);
}
};

LineSearch opt = new LineSearch(10, f);
// start at 0
Matrix x = new Matrix(3, 1);
Matrix gradient = df.eval(x);

// take a step
boolean flag = opt.findMin(x, f.eval(x), gradient, gradient.times(-1));

// should have taken entire newton step
assertFalse(flag);
// and found the answer
assertEquals(0, opt.getF(), 1e-9);
x = opt.getX();
assertEquals(b, x, 1e-9);

// next step should go nowhere
flag = opt.findMin(x, f.eval(x), gradient, gradient.times(-1));
assertTrue(flag);
assertEquals(0, opt.getF(), 1e-9);
x = opt.getX();
assertEquals(b, x, 1e-9);

}
}


This test case depends on this extension of TestCase:

package com.tdunning;

import junit.framework.TestCase;
import Jama.Matrix;

/**
* Allows test cases to be written with matrix comparison built in.
*/
public class MatrixTestClass extends TestCase {
protected void assertEquals(String msg, double[] a, double[] b) {
assertEquals(msg, a.length, b.length);
for (int i = 0; i < a.length; i++) {
assertEquals(msg, a[i], b[i], 1e-14);
}
}

protected void assertEquals(String msg, double[][] a, double[][] b) {
assertEquals(msg, a.length, b.length);
for (int i = 0; i < a.length; i++) {
assertEquals(msg, a[i].length, b[i].length);
for (int j = 0; j < a.length; j++) {
assertEquals(msg, a[i][j], b[i][j], 1e-14);
}
}
}

private void assertMatrixEquals(String msg, Matrix X, Matrix Y, double eps) {
if (msg.length() > 0) {
msg += ": ";
}
if (X.norm1() == 0. & Y.norm1() < 10 * eps) return;
if (Y.norm1() == 0. & X.norm1() < 10 * eps) return;
double[][] xdata = X.getArray();
double[][] ydata = Y.getArray();
for (int i = 0; i < xdata.length; i++) {
for (int j = 0; j < xdata[i].length; j++) {
assertEquals(msg + "Element " + i + ", " + j, xdata[i][j], ydata[i][j], eps);
}
}
}

protected void assertEquals(Matrix X, Matrix Y) {
assertMatrixEquals("", X, Y);
}

protected void assertMatrixEquals(String s, Matrix expected, Matrix actual) {
assertMatrixEquals(s, expected, actual, 1e-9);
}

protected void assertEquals(Matrix expected, Matrix actual, double eps) {
assertMatrixEquals("", expected, actual, eps);
}
}

tdunning
01-25-2005, 01:25 AM
Silly me.

I went ahead and translated the dfpmin routine into reasonably idiomatic Java. In the process, I renamed it to the more appropriate BFGSMinimizer (see the text for the reason why).

I also added a test suite that shows that the program solves two simple problems correctly. I am slightly suspicious, however, in that the value does not always decrease from iteration to iteration. I don't know (and can't afford to find out) if this is correct or not.

In doing this translation, I have again taken the liberty to use the matrix package Jama rather than hand-coding any matrix manipulations. I have also taken full license to rename variables to readable forms (such as hessian in the place of hessin).

Yes, Bianca, there is a Santa Claus.

drjrkuhnyale
03-20-2005, 04:58 PM
I have been slowly translating C++ NR code to Java as needed. It is not as difficult as one might think.

First, each NR function is given its own class so that any C++ static variables become Java class variables and each NR function gets its own file. For consistency, I have named each class in capitals and each function in lower-case. For example, the class RAN1 contains a single function ran1().

Second, since several NR C++ function place return values in function parameters (pass by reference), C++ references are translated as java arrays of length one.

Third, I have created a set of Java utility classes for vector/matrix instantiation and the classes COStream and CIStream, which mimmick the C++ I/O streams. These latter classes allow C++ "cin >>" and "cout <<" to be quickly translated to Java. These makes it especially easy to translate the test code supplied for each NR function into a JUnit test (an absolute necessity)!

For example, the NR C++ function

double ran1(int &idum)
{
const int IA=..., IM=...;
static int iy=0;
...
if (idum <= 0 || (iy==0))...
}

With C++ test

double ran1(int&); // Function declaration
int i, idum=-13;
double val;
for (i=0; i<10; i++) {
val = ran1(idum);
cout << "Next value is " << setw(16) << setprecision(14) << val << endl;
cout << "Next seed is " << setw(4) << idum << endl;
}

Becomes the Java class

public class RAN1 {
private final int IA=...,IM=...;
private int iy=0;
...
public double ran1(int []idum) {
if (idum[0] <= 0 || (iy==0))...
}
}

With Java test

RAN1 ran1 = new RAN1(); // Create object ran1 of class RAN1
COStream cout = new COStream(System.out);
int i, idum[]={-13};
double val;
for (i=0; i<10; i++) {
val = ran1.ran1(idum);
cout . print("Next value is ") . setw(16) . setprecision(14) . print(val) . endl();
cout . print("Next seed is ") . setw(4) . print(idum[0]) . endl();
}

With these utility routines, it is a piece of cake to translate each NR C++ function and its test. It mainly involves copy and paste of the C++ code into a java class file, a few global search-and-replaces (eg. "&" -> "[]"), and a little house-keeping. One can also been add Javadoc comments based on the NR text available online as PDF files. So far, I have needed to translate about 30 NR functions along with their test cases.

I would love to just ZIP up all of the code I have so far and share it with the group. Unfortunately, I think that this would violate the NR license agreement. Does anyone know of a way for us to share our different Java translations of NR code within the terms of the license agreement?

-- Jeff Kuhn <jeffrey.kuhn@yale.edu>

tdunning
03-23-2005, 03:29 AM
My own take on this is that there are three serious problems with this sort of translation.

The first problem is the authors of the NR software. They really don't want people to do their own translation. I think that they have threatened legal action against one person for posting very loose translations into Modula.

The second problem is that while the algorithms described in the NR books are very useful (if not bleeding edge), the code in the books is just barely this side of icky-poo. Translating the NR coding conventions into java is just plain painful ... witness your use of cout in a junit test. Your test actually isn't even a test.

A third major problem is that there are high quality routines already available for things like linear algebra (c.f. Jama or Colt) and for random number generation. Translating the NR implementations makes very little sense and without those translations, much of the remaining code requires major rework to use a better package. For that matter, none of the NR code makes very good use of level 2 or level 3 BLAS so performance is often much lower than it could be.

My own approach for using NR algorithms is to go to the math rather than the code. Sometimes, the math is only expressed in the code, but usually this isn't the case. Then I build classes that are reasonably well-designed and which use the underlying matrix and special function libraries that I prefer. The only real use of the NR code is to produce test cases so that I can regress to identical results. This isn't a clean-room approach, but we aren't talking trade secrets here, just code quality and avoiding any copyright hassles in case I were to ever distribute my code.

d.wachss
08-11-2005, 09:17 PM
I have written a chemical kinetics simulation program
www.geocities.com/tenua4java
that uses many of the NR algorithms implemented in JAVA.
My thoughts are similar to tdunning's above:
The code is usually too FORTRAN-y for dedicated JAVA programmers, and never uses object-oriented programming well.

I implemented my own matrix and vector classes but used the JAMA routines for the linear algebra (including LU and SVD decomposition) and implemented the algorithms from NR for ODE solving and multi-variable minimization, using the descriptions in the text and referring to NR's source code as little as possible. To the best of my knowledge, the source does not violate NR's copyright.
I implemented the algorithms represented by the routines:
rkqs, rkck,mmid, bsstep, simpr, stifbs, amoeba, fdjac (but using the symmetric form represented by equation 5.7.7), polint

benoitx
12-13-2005, 06:45 PM
Surely... this thread is 3y old and I cannot seem to find a definite answer... When is the NR for Java going to be available?

Thanks

sipke
02-01-2006, 09:30 PM
Hello, I am porting an application written in Pascal for the Macintosh, to Java. This application uses NR routines.
I realise from this forum thread that NR in Java is not yet available. However for my purposes, it would be enough to receive information on how NR for Java will be structured - Class interfaces would be ideal.
The routines in question are
qromo
polint
mnbrak
midpnt
brent
covsrt
gaussj
mrqcof
mrqmin
This way I can do write the code myself, but at least I have the correct interface and structure in use already, for that time that NR in Java becomes available (or at least the interfaces will be close to the released version of NR for Java, that they can be adapted easily).

simonjpalmer
02-05-2006, 09:32 AM
What oh Dunning old boy,

looks like Vetterling wasn't as close as he thought in 2003, ah well. Completely agree with the notion of doing a Java re-write rather than a Java port and love the use of interfaces instead of those ugly function pointers, and real variable names rather than hieroglyphs. Hurrah for the era of modern computing!

Thanks awfully for making your translation of the Quasi-Newton available, absolutely tip-top. Any chance you could give a sneak-peek of the MatrixFunction interface and whatever code you have added to the jama package for the Matrix.abs() methods?

Cheerio

kutta
11-15-2006, 03:49 AM
Kay,

Thanks for your very timely question.

Here is the state of affairs. As of early March, I have had all of the Recipes and their corresponding example routines translated, except for approximately ten. Those ten generally have some difficult or peculiar nature to them, such as maintaining arrays of file streams, or doing some sort of tricky manipulations that are very sensitive to details of data representation. There is nothing left that couldn't be solved with a week of uninterrupted work.

Unfortunately, for the past four weeks I have not been able to devote any time to the translation, due to competing responsibilities, but I do expect to be free to continue in approximately two weeks.

Keep a good thought. The job is nearly done!


Hello Mr.Vetterling,
In anticipation of ur favourable reply at other section and also owing to requests that have been made at the other section viz NR in Other Languages,for the release of Java codes for NR at the earliest ,I now have been able to assist u ,especially for the salesman program using annealing technique( A Mechanical engineering subject under thermodynamics) Please let me know if I am able to supply the doc material for the same progrom as i have given them tentatively in txt file.you may peruse the same and expedite .
Thanks as always

kutta
01-26-2007, 03:37 AM
Paolo,

Actually, I have been doing some JAVA translations on the side for a few months, and I currently have cursory translations for nearly all of the 350 Recipes and about 80 of the Example routines. (By "cursory", I mean that they all compile, but until the example routines are finished I won't know how many of them need debugging.)

It would premature to foist them upon any NR users before rudimentary testing, and there are many fundamental issues of style and organization to be resolved as well. Perhaps in a few months we will have some available for beta testing and comment. In the meantime, I may post some questions for public comment on this forum, to help educate myself on the best way to handle some of the programming problems. I hope you can give us some good ideas!
Hello Mr.Vetterling

Has the task of Java coding for the NR,been completed or in the verge completion,or is it only partial.Neverthless pl arrange to kindly try out the samples of javacode for Salesman enclosed herewith using annealing method of Applied Thermodynamics(MechanicalEngineering)
as no information is heard ,though this was forwarded earlier.
This is just co-ordinated try.Any Comments
Thanking You:)

kutta
09-10-2010, 06:31 AM
thanks, kutta

Hello NR-friend,
Better late than never is the fitting proverb Hence
to add some more example on matrix usages before you try to do Tred2 (11.2)in Java,here is a small coded programme in TwoDimensionalMatrix that may be useful for ur further try on the same
Pl confirm if ok
Thanks
As
Kutta(C.R.Muthukumar):)


[Note by webmaster: Sorry, we don't allow copyrighted code to be posted on the Forum.
Code deleted.]

kutta
09-09-2011, 03:13 AM
Kay,

Thanks for your very timely question.

Here is the state of affairs. As of early March, I have had all of the Recipes and their corresponding example routines translated, except for approximately ten. Those ten generally have some difficult or peculiar nature to them, such as maintaining arrays of file streams, or doing some sort of tricky manipulations that are very sensitive to details of data representation. There is nothing left that couldn't be solved with a week of uninterrupted work.

Unfortunately, for the past four weeks I have not been able to devote any time to the translation, due to competing responsibilities, but I do expect to be free to continue in approximately two weeks.

Keep a good thought. The job is nearly done!

Hello reverend Author

It's very nice to hear the status (as stated )in board though this is yet to be started. Now if Java finds a place in NR ,the C++ will having included new chapters /new corollaries/algorithms suggested by readers eventually make the Java version look thin if they dont include them in java. Some how a Synonimus balance is to be found between the two in the contents.But before that the conerned may please review the suggestions constuctively as i find as on date no remarks of a new suggestion i made especially in C++.
I sincerely hope my request is once again be limelighted
Also economical edition / publication which will be a thing to consider in the present day situation of cost rising scenerio.
Thanks
As
C.R.Muthukumar(Kutta)