I'm trying to solve a constrained non-linear 267 dimensional optimization problem with the java optimization library supplied by Apache Commons.
After 3 days of deciphering, this is what I have:
public class optimize2 {
public static void main(String []args){
double[] point = {1.,2.};
double[] cost = {3., 2.};
MultivariateFunction function = new MultivariateFunction() {
public double value(double[] point) {
double x = point[0];
double y = point[1];
return x * y;
}
};
MultivariateOptimizer optimize = new BOBYQAOptimizer(5);
optimize.optimize(
new MaxEval(200),
GoalType.MAXIMIZE,
new InitialGuess(point),
new ObjectiveFunction(function),
new LinearConstraint(cost, Relationship.EQ, 30));
}
}
For whatever reason optimize.optimize() is throwing a null pointer error. Maybe I'm just being dumb but I can't figure out how to get this to work.
Here is the error:
Exception in thread "main" java.lang.NullPointerException
at org.apache.commons.math3.optim.nonlinear.scalar.noderiv.BOBYQAOptimizer.setup(BOBYQAOptimizer.java:2401)
at org.apache.commons.math3.optim.nonlinear.scalar.noderiv.BOBYQAOptimizer.doOptimize(BOBYQAOptimizer.java:236)
at org.apache.commons.math3.optim.nonlinear.scalar.noderiv.BOBYQAOptimizer.doOptimize(BOBYQAOptimizer.java:49)
at org.apache.commons.math3.optim.BaseOptimizer.optimize(BaseOptimizer.java:143)
at org.apache.commons.math3.optim.BaseMultivariateOptimizer.optimize(BaseMultivariateOptimizer.java:66)
at org.apache.commons.math3.optim.nonlinear.scalar.MultivariateOptimizer.optimize(MultivariateOptimizer.java:64)
at Test.Code.optimize2.main(optimize2.java:39)
Looking directly into the BOBYQA code, it actually seems like the problem is that you have not explicitly defined any variable bounds. Line 2401 (setup method) reads as follows:
boundDifference[i] = upperBound[i] - lowerBound[i];
In the doOptimze method, prior to calling setup the bounds are set using these methods:
final double[] lowerBound = getLowerBound();
final double[] upperBound = getUpperBound();
These methods are defined in BaseMultivariateOptimizer like this:
public double[] getLowerBound() {
return lowerBound == null ? null : lowerBound.clone();
}
(and analogously for getUpperBound()). But lowerBound and upperBound in BaseMultivariateOptimizer are only set if the optimization data in the optimize call contains bounds information. If the bounds are not set in the call to optimize, you should therefore receive a NullPointerException.
Looking at the BOBYQA test code it seems like it should be sufficient if you add the following argument to the optimize call:
SimpleBounds.unbounded(point.length)
Having said that, I also do not think you will be able to completely solve your problem using any of the nonlinear optimizers in Apache Commons Math, since as far as I can tell none of these optimizers can handle linear or nonlinear constraints. I recommend that you take a look at for example Michael Powell's COBYLA2 algorithm instead. I have migrated the original FORTRAN code of this algorithm to Java, and you can find the code here and here.
Related
This question already has answers here:
What does the "Assigned value is never used" warning mean?
(5 answers)
Closed 3 months ago.
I'm following Princeton's introductory computer science course (I'm not a student, just teaching myself). I working on this assignment.
Main is calling two methods: amplify and reverse, both of which return an array. Amplify multiplies all values in the array by a constant alpha. Reverse returns an array that lists the original array values in reverse order, ex. {1,2,3} -> {3,2,1}.
Amplify works fine, but nothing happens when I call reverse and I get a bug that states: The Value Assigned Is Never Used
public class audiocollage {
// Returns a new array that rescales a[] by a factor of alpha.
public static double[] amplify(double[] a, double alpha) {
for (int i = 0; i < a.length; i++) {
a[i] = a[i] * alpha;
}
return a;
}
// Returns a new array that is the reverse of a[].
public static double[] reverse(double[] a) {
double[] b = new double[a.length];
for (int i = a.length - 1, j = 0; i >= 0; i--, j++) {
b[j] = a[i];
}
return b;
}
// Creates an audio collage and plays it on standard audio.
public static void main(String[] args) {
double[] samples = StdAudio.read("cow.wav");
double alpha = 2.0;
samples = amplify(samples, alpha);
samples = reverse(samples);
}
}
It sounds like you have two questions:
Why doesn't anything happen when I call reverse(samples)?
The code you're showing does nothing with the result of reverse(samples) other than store it in the variable samples (overwriting its previous value). You will need to do something with samples after that to observe the new array (like printing samples, which should now appear to be reversed).
Which leads into the next question:
Why do I get a warning about "the value assigned to samples is never used"?
This is a warning saying that the code you wrote doesn't do anything.
Dead store to local variable is the first line of the warning, which describes what's happening: the value stored to samples is "dead" -- it is never used again, and so we may as well have skipped that line altogether. That causes your compiler (or extension) to give us a warning because it's almost certain that the code you wrote is not doing what you intended, so in many cases that warning can be helpful for spotting mistakes.
This warning can be resolved by using samples somehow, such as by printing it, calling another function with it, etc.
The previous line
samples = amplify(samples, alpha);
doesn't generate that warning because it's output is used in the following call to reverse():
samples = reverse(samples);
// ^ usage of `samples` variable!
This is made even clearer by using different variables for all your arrays:
public static void main(String[] args) {
// No warning; samplesRaw used later
double[] samplesRaw = StdAudio.read("cow.wav");
double alpha = 2.0;
// No warning; samplesAmplified used later
samplesAmplified = amplify(samplesRaw, alpha);
// WARNING! samplesReversed is never used!
samplesReversed = reverse(samplesAmplified);
}
If the hint is related to the last line, it means you have a local variables samples which has not used ( you assigned a value but never read it)
Main:
public class Main{
public static void main(String[] args){
System.out.println(Convert.BtoI("10001"));
System.out.println(Convert.BtoI("101010101"));
}
}
Class:
public class Convert{
public static int BtoI(String num){
Integer i= Integer.parseInt(num,2);
return i;
}
}
So I was working on converters, I was struggling as I am new to java and my friend suggested using integer method, which works. However, which method would be most efficient to convert using the basic operators (e.g. logical, arithmetic etc.)
.... my friend suggested using integer method, which works.
Correct:
it works, and
it is the best way.
However, which method would be most efficient to convert using the basic operators (e.g. logical, arithmetic etc.)
If you are new to Java, you should not be obsessing over the efficiency of your code. You don't have the intuition.
You probably shouldn't optimize this it even if you are experienced. In most cases, small scale efficiencies are irrelevant, and you are better off using a profiler to validate your intuition about what is important before you start to optimize.
Even if this is a performance hotspot in your application, the Integer.parseint code has (no doubt) already been well optimized. There is little chance that you could do significantly better using "primitive" operations. (Under the hood, the methods will most likely already be doing the same thing as you would be doing.)
If you are just asking this because you are curious, take a look at the source code for the Integer class.
If you want to use basic arithmetic to convert binary numbers to integers then you can replace the BtoI() method within the class Convert with the following code.
public static int BtoI(String num){
int number = 0; // declare the number to store the result
int power = 0; // declare power variable
// loop from end to start of the binary number
for(int i = num.length()-1; i >= 0; i--)
{
// check if the number encountered is 1
/// if yes then do 2^Power and add to the result
if(num.charAt(i) == '1')
number += Math.pow(2, power);
// increment the power to use in next iteration
power++;
}
// return the number
return number;
}
Normal calculation is performed in above code to get the result. e.g.
101 => 1*2^2 + 0 + 1*2^0 = 5
I have a program with one class, which looks like this.
public class Functions {
public static void main(String[] args) {
System.out.println(summationFunction(1)); //Prints 13
System.out.println(summationFunction(2)); //Prints 29
System.out.println(summationFunction(3)); //Prints 48
System.out.println(summationFunction(4)); //Prints 70
}
public static int summationFunction(int input) {
int summedNumber = 0;
int i = input;
while (i > 0) {
summedNumber += i * 3;
i--;
}
return 10 * input + (summedNumber);
}
}
So, this program will take in a given number and apply this function to it:
And this all works well (I have run the class Functions and everything prints just as it's supposed to.) BUT, I need to find the inverse of this function, and I need to be able to translate it to code; I do not know how to do this.
I basically need a function that will return values like this:
public static void main(String[] args) {
System.out.println(summationFunction(13)); //Prints 1
System.out.println(summationFunction(29)); //Prints 2
System.out.println(summationFunction(48)); //Prints 3
System.out.println(summationFunction(70)); //Prints 4
}
which, (as you can tell) is the opposite of the original function.
So to sum everything up, I need a function that will return the inverse of my original function (summationFunction), and I would like to know how I would model this or if there is a quick solution, in code.
One more thing: I know that I can have the method take an input and search for the most similar output of the original method, but I would like to see if there is a simpler way to do this which does not involve searching, thus giving a quicker output speed. And if you wish you can safely assume that the input of the inversed function will always be a number which will give an integer output, like 13, 29, 48, 70, etc...
By the way, if you are going to downvote the question, will you at least give a reason somewhere? The comments perhaps? I can not see any reason that this question is eligible for being downvoted, and a reason would help.
Wolfram Alpha to the rescue !
It tells you that this function can be written as :
1/24*(6*x+23)^2-529/24
So if you want to solve f(x)=a, you have :
x = 1/6*(sqrt(24*a+529)-23)
a = 70
# => x = 4
Note : Using Wolfram shouldn't prevent you from finding the answer on your own.
sum(something*i) is equal to something*sum(i) because something (3 in this case ) doesn't depend on i.
sum(i,i=1..n) is equal to n*(n+1)/2, and it's easy to prove (see Wikipedia)
So your function becomes 10*x+3*x*(x+1)/2
Expanded, it is :
(3 x^2)/2+(23 x)/2
You need to solve (3 x^2)/2+(23 x)/2 = 70, in other words :
(3 x^2)/2+(23 x)/2 - 70 = 0
It is a quadratic equation, with a=3/2, b=23/2 and c=-70 or c=-29 or c=....
You sum can be written like this 3*x*(x+1)/2 so you have equation 10*x + 3*x*(x+1)/2 = y you need to solve it.
Wolfram alpha tells that result will be 1/6.0 * (-23.0+sqrt(529.0+24.0 * y))
I got this warning on Sonar as a violation. I want proper solution to remove this warning from sonar.
My code is like this:
void method(){
try {
int x;
x=5;
}
catch{
//handling code
}
}
I got warning for this code like:
'5' is a magic number.
So, I want proper solution to remove such warning.
Magic number is the direct usage of the number in the code(i.e., hard-coded number in the code in your case using 5 directly)
to get rid of the warning try this:
int x;
static final int SOME_NUMBER=5;
x=SOME_NUMBER;
Sonar is asking you to document why you use that particular number by giving it a name. You can do so by declaring a constant (with an expressive name):
static final int NUMBER_OF_RETRIES = 5;
and then use that constant instead of the "magic" number, thereby expressing the intent of that assignment more clearly:
x = NUMBER_OF_RETRIES;
This also has the advantage that if NUMBER_OF_RETRIES needs to be changed, you can do so in one place, rather than whereever that "magic" number is used.
Well, I'm aware that this question has already been answered satisfactorily, but I'd like to add here the own Sonar explanation, since it's quite well elaborated:
A magic number is a number that comes out of nowhere, and is directly
used in a statement. Magic numbers are often used, for instance to
limit the number of iterations of a loops, to test the value of a
property, etc.
Using magic numbers may seem obvious and straightforward when you're
writing a piece of code, but they are much less obvious and
straightforward at debugging time.
That is why magic numbers must be demystified by first being assigned
to clearly named variables before being used.
-1, 0 and 1 are not considered magic numbers.
Noncompliant Code Example
public static void doSomething() {
for(int i = 0; i < 4; i++){ // Noncompliant, 4 is a magic number
...
}
}
Compliant Solution
public static final int NUMBER_OF_CYCLES = 4;
public static void doSomething() {
for(int i = 0; i < NUMBER_OF_CYCLES ; i++){
...
}
}
Exceptions
This rule ignores hashCode methods.
I know the first thing you are thinking is "look for it in the documentation", however, the documentation is not clear about it.
I use the library to get the FFT and I followed this short guide:
http://www.digiphd.com/android-java-reconstruction-fast-fourier-transform-real-signal-libgdx-fft/
The problem arises when it uses:
fft.forward(array);
fft_cpx=fft.getSpectrum();
tmpi = fft.getImaginaryPart();
tmpr = fft.getRealPart();
Both "fft_cpx", "tmpi", "tmpr" are float vectors. While "tmpi" and "tmpr" are used for calculate the magnitude, "fft_cpx" is not used anymore.
I thought that getSpectrum() was the union of getReal and getImmaginary but the values are all different.
Maybe, the results from getSpectrum are complex values, but what is their representation?
I tried without fft_cpx=fft.getSpectrum(); and it seems to work correctly, but I'd like to know if it is actually necessary and what is the difference between getSpectrum(), getReal() and getImmaginary().
The documentation is at:
http://libgdx-android.com/docs/api/com/badlogic/gdx/audio/analysis/FFT.html
public float[] getSpectrum()
Returns: the spectrum of the last FourierTransform.forward() call.
public float[] getRealPart()
Returns: the real part of the last FourierTransform.forward() call.
public float[] getImaginaryPart()
Returns: the imaginary part of the last FourierTransform.forward()
call.
Thanks!
getSpectrum() returns absolute values of complex numbers.
It is calculated like this
for (int i = 0; i < spectrum.length; i++) {
spectrum[i] = (float)Math.sqrt(real[i] * real[i] + imag[i] * imag[i]);
}