Python Convolution equivalent in Java? - Java - Python - java

I am implementing a Weighted Moving Average algorithm with the help of convolution.
It is quite easy in Python using the convolution function provided by numpy.
The codes are as follows:
# Method 2 WMA
WINDOW_SIZE = 70
DATA_SET_NUMBER = 7090
smoothedAcc = ndarray(DATA_SET_NUMBER)
weights = ndarray(WINDOW_SIZE)
accWindow = ndarray(WINDOW_SIZE)
for i, v in enumerate(weights):
weights[i] = (WINDOW_SIZE - i) / (WINDOW_SIZE * (WINDOW_SIZE + 1) / 2)
for x in xrange(0, (DATA_SET_NUMBER - WINDOW_SIZE)):
for y in xrange(0, WINDOW_SIZE):
accWindow[y] = acc[x + y]
smoothedAcc[x] = np.convolve(weights, accWindow, 'valid')
However, in the end I have to implement this in Java. I tried to find the readily-built convolution API in Java, but failed.
Anyone can help me get the equivalent Java codes of the above-mentioned Python snippet?
Thanks in advance!

Related

Levenberg-Marquardt minimization in Java

I generally code in MATLAB, but for some reasons I decided to switch to a JAVA approach.
The question is quite easy: I'd like understanding how to translate the following MATLAB code into a working JAVA's one.
Within MATLAB I have a target function called findZ0:
function F = findZ0(V, Z, Latitude, TI, x)
%%% Inputs
% V = Average Wind Speed at Hub Height
% Z = Hub Height;
% Latitude = Specific Site Latitude (default value equal to 50 deg);
% x = Tryout Roughness length;
% TI = Target Turbulent Intensity;
%%% Outputs
% F = Roughness Length tuned to match Target Turbulent Intensity
Latitude = deg2rad(Latitude);
omega = 72.9E-06;
f = 2*omega*sin(Latitude);
ustar = ( 0.4*V - 34.5*f*Z)/log(Z/x);
mu = 1 - ((6*f*Z)/(ustar));
p = mu^(16);
sigmaTarget = (V*TI)/100;
F = sigmaTarget - (( 7.5*mu*ustar*((0.538 + .09*log(Z/x))^p) )/(1 + .156*log(ustar/(f*x))));
end
I then called this lines:
Uhub = 8;
HubHt = 90;
Latitude = 50;
x_trial = 0.01;
TI_target = 24;
find_z0 = #(x) findZ0(Uhub,HubHt,Latitude,TI_target, x);
z0 = fsolve(find_z0,x_trial,{'fsolve','Jacobian','on','levenberg-marquardt',.005,'MaxIter',15000,'TolX',1e-07,'TolFun',1E-07,'Display','off'});
I am aware that Fortran packages have been imported in Java, but I don't really have a clue how to achieve my goal by applying the mentioned tools. Hence, I'd welcome any suggestion on how to overcome this problem.
I'd suggest using an existing solution like Apache Commons - it's a robust library containing a lot of tools you may find helpful.
The LM optimization method is implemented by this class - you can either use it directly or just look at it for inspiration.

Spline Interpolation Performance in Scala vs Java

I translated this spline interpolation algorithm from apache.commons.math from Java into Scala in the most straightforward way I could think of (see below). The function I ended up with runs 2 to 3 times slower than the original Java code. My guess is that the problem stems from the extra loops coming from the calls to Array.fill, but I can't think of a straightforward way to get rid of them. Any suggestions on how to make this code perform better? (It would also be nice to write it in a more concise and/or functional way -- suggestions on that front would be appreciated as well.)
type Real = Double
def mySplineInterpolate(x: Array[Real], y: Array[Real]) = {
if (x.length != y.length)
throw new DimensionMismatchException(x.length, y.length)
if (x.length < 3)
throw new NumberIsTooSmallException(x.length, 3, true)
// Number of intervals. The number of data points is n + 1.
val n = x.length - 1
// Differences between knot points
val h = Array.tabulate(n)(i => x(i+1) - x(i))
var mu: Array[Real] = Array.fill(n)(0)
var z: Array[Real] = Array.fill(n+1)(0)
var i = 1
while (i < n) {
val g = 2.0 * (x(i+1) - x(i-1)) - h(i-1) * mu(i-1)
mu(i) = h(i) / g
z(i) = (3.0 * (y(i+1) * h(i-1) - y(i) * (x(i+1) - x(i-1))+ y(i-1) * h(i)) /
(h(i-1) * h(i)) - h(i-1) * z(i-1)) / g
i += 1
}
// cubic spline coefficients -- b is linear, c quadratic, d is cubic (original y's are constants)
var b: Array[Real] = Array.fill(n)(0)
var c: Array[Real] = Array.fill(n+1)(0)
var d: Array[Real] = Array.fill(n)(0)
var j = n-1
while (j >= 0) {
c(j) = z(j) - mu(j) * c(j + 1)
b(j) = (y(j+1) - y(j)) / h(j) - h(j) * (c(j+1) + 2.0 * c(j)) / 3.0
d(j) = (c(j+1) - c(j)) / (3.0 * h(j))
j -= 1
}
Array.tabulate(n)(i => Polynomial(Array(y(i), b(i), c(i), d(i))))
}
You can get rid of all the Array.fill since a new array is always initialized with 0 or null, depending on whether it is a value or a reference (booleans are initialized with false, and characters with \0).
You might be able to simplify the loops by zipping arrays, but you'll only make it slower. The only way functional programming (on the JVM anyway) is going to help you make this faster is if you make it non-strict, such as with a Stream or a view, and then you go ahead and not use all of it.

given 3 vectors and angle, how to find the fourth vector so that 2 line segments are formed through all vectors

I have one line segment formed by two vectors, let's say v1 and v2, a vector v3 and an angle a. How do I write a method in Java (I'm also using Apache Commons Math to represent a vector) which gives me a vector v4, so that the line segments v1-v2 and v3-v4 are at angle a? There are infinite v4 elements, it would even be better if I could give a size to that method so that the line segment v3-v4 has that size. (all in 2d space, angle can be radians or degrees, doesn't matter)
Edit: as promised I have included an image of the problem I'm trying to solve. I have a line segment defined by 2 vectors (the line is a bit longer but that doesn't matter), an angle, and a third point. I need to draw the second line which intersects the first one at angle a. Since all lines in Javafx (which I'm using here) are drawn by defining two points, I needed to find the red point (or any of the possible ones).
Edit: Using Ali's answer I got the following method which does what I need:
public Pair<Vector2D, Vector2D> calculateFourthPoint(Vector2D v1, Vector2D v2, Vector2D v3, double angleInDegrees) {
Vector2D r = v1.subtract(v2);
double rx = r.getX();
double ry = r.getY();
double angle = toRadians(angleInDegrees);
double a = pow(rx, 2) + pow(ry, 2);
double b = 2 * sqrt(pow(rx, 2) + pow(ry, 2)) * cos(angle) * rx;
double c = pow(rx, 2) * pow(cos(angle), 2) + pow(ry, 2) * pow(cos(angle), 2) - pow(ry, 2);
double discriminant = sqrt(pow(b, 2) - (4 * a * c));
double sx1 = (-b + discriminant) / (2 * a);
double sx2 = (-b - discriminant) / (2 * a);
double sy1 = sqrt(1 - pow(sx1, 2));
double sy2 = sqrt(1 - pow(sx2, 2));
Vector2D s1 = new Vector2D(sx1, sy1);
Vector2D s2 = new Vector2D(sx2, sy2);
Vector2D v4_1 = v3.subtract(s1);
Vector2D v4_2 = v3.subtract(s2);
return new Pair<Vector2D, Vector2D>(v4_1, v4_2);
}
I don't know Apache Commons Math so I am writing in pseudo code. Let vx and vy denote the x and y components of vector v, respectively.
Let r=v1-v2 and s=v3-v4. You have 2 unknowns (namely sx and sy; and v4=v3-s) so you need 2 equations. These should be:
dot_product(r,s)=length(r)*cos a // forces the desired angle
dot_product(s,s)=1 // just sets the length of s to 1
To spell it out, the above equations are:
(1) rx*sx + ry*sy = sqrt(rx^2+ry^2)*cos a
(2) sx^2 + sy^2 = 1
The first equation is linear in both sx and sy. Let's eliminate sy from the first equation (assuming that ry is not zero)
sy = (1/ry)*(sqrt(rx^2+ry^2)*cos a - rx*sx)
and substitute this sy into the second equation. You get a quadratic equation in sy (I don't want to write it here because it is complicated) and that has 2 solutions. You get the corresponding sx by substituting the sy values into (assuming rx is not zero):
sx = (1/rx)*(sqrt(rx^2+ry^2)*cos a - ry*sy).
Finally, v4=v3-s. You get 2 solutions for v4, one for each of the solutions to the quadratic equation. (Degenerate cases, such as r being a null vector, are ignored in my answer.)
Shame we can't do LaTeX-style equations here (or can we? I dunno, never done it here...), but here goes:
v1-v2 · v3-v4 = |v1-v2| * |v3-v4| * cos(a) (by definition)
define |v3-v4| to be a unit vector, so that
v1-v2 · v3-v4 = |v1-v2|*1*cos(a) = |v1-v2|*cos(a)
working the left hand side out gives
v1·v4 + v2·v4 = |v1-v2|*cos(a) - v1·v3 + v2·v3
or
(v1+v2)·v4 = |v1-v2|*cos(a) - (v1-v2)·v3
while
|v3-v4| = (v3-v4)·(v3-v4) = 1
So, there are 2 equations in 2 unknowns. Now, for brevity,
aa = (v1+v2|x
bb = (v1+v2|y
x1 = v4|x
x2 = v4|y
A = |v1-v2|*cos(a) - (v1-v2)·v3
where |x means x-component, etc. With this, trivial substitution gives us
( (A-aa*x1)/bb )^2 + (aa*x1)^2 = 1 (-> 2 solutions)
( (A-bb*x2)/aa )^2 + (bb*x2)^2 = 1 (-> another 2 solutions)
The solutions are a bit too messy to write down here, but they are plain quadratic equations that can be easily solved.
You then have 4 unique vectors which lie on a unit circle around v3 (see picture). These 4 vectors result in only 2 distinct lines, but it is still a good idea to find all 4 vectors (as a self-check, and to improve robustness -- there can be some fringe cases where one of the vectors is such that something like catastrophic cancellation occurs).
Which line is best suited for you, depends of course on your use case.
Whatever the solution you pick, you should of course always verify whether
arccos(((v1-v2)·(v3-v4))/|v1-v2|) = a
as it should be.

Simulated Binary Crossover (SBX) crossover operator in Scala genetic algorithm (GA) library

I work on a very little research team to create/adapt a Genetic Algorithm library in Scala for distributed computation with Scientific Worklow System, in our case we use the open source OpenMole software (http://www.openmole.org/).
Recently, i try to understand and re-implement the SBX crossover operator written in JMetal Metaheuristics library (http://jmetal.sourceforge.net/) to adapt it in functionnal version in our Scala library.
I write some code, but i need our advice or your validation about the SBX defined into java library, because the source code (src in svn) doesn't appear equal to the original equation written here : http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.33.7291&rep=rep1&type=pdf at page 30, in annexe A
First question, i don't understand the java version of JMetal, why they use two different beta values ?!
beta1 which use in the equation the first arg of min[(y1 - yL), ...] and
beta2 which use the second arg of min [... , (yu - y2)])
Beta 1 and 2 are used for computation of alpha value and two (so here and in jmetal we have also two alpha different value alpha1 and 2) ...
Same problem/question, we have in jmetal two computation for betaq (java code) or in Deb equation, result of :
Second question, what is the meaning of the symbol used in (2) and (3) procedure in pseudo-algorithm of SBX, and the difference with simple beta ? Especially when we want to compute children/offsprings of crossover parents, like here :
Edit
Correct a no-op if/else block
Author of code in jmetal give me the link of original source code of Nsga-II algorithm, and he explain me that description of SBX by Deb differs from his implementation :/
http://www.iitk.ac.in/kangal/codes.shtml
I don't understand the difference between the description and the implementation in jmetal and original source code, do you have an explanation ?
Correct if/else return for map
Start of translation into scala
class SBXBoundedCrossover[G <: GAGenome, F <: GAGenomeFactory[G]](rate: Random => Double = _.nextDouble) extends CrossOver [G, F] {
def this(rate: Double) = this( _ => rate)
def crossOver (genomes : IndexedSeq [G], factory: F) (implicit aprng : Random) = {
val g1 = genomes.random
val g2 = genomes.random
val crossoverRate = rate(aprng)
val EPS = 1.0e-14
val numberOfVariables = g1.wrappedValues.size
val distributionIndex = 2
val variableToMutate = (0 until g1.wrappedValues.size).map{x => !(aprng.nextDouble < 0.5)}
//crossover probability
val offspring = {
if (aprng.nextDouble < crossoverRate) {
(variableToMutate zip (g1.wrappedValues zip g2.wrappedValues)) map {
case (b, (g1e, g2e)) =>
if(b) {
if (abs(g1e - g2e) > EPS){
val y1 = min(g1e, g2e)
val y2 = max(g2e, g1e)
var yL = 0.0 //g1e.getLowerBound
var yu = 1.0 //g1e.getUpperBound
var rand = aprng.nextDouble // ui
var beta1 = 1.0 + (2.0 * (y1 - yL)/(y2 - y1))
var alpha1 = 2.0 - pow(beta1,-(distributionIndex+1.0))
var betaq1 = computebetaQ(alpha1,distributionIndex,rand)
//calcul offspring 1 en utilisant betaq1, correspond au β barre
var c1 = 0.5 * ((y1 + y2) - betaq1 * (y2 - y1))
// -----------------------------------------------
var beta2 = 1.0 + (2.0 * (yu - y2) / (y2 - y1))
var alpha2 = 2.0 - pow(beta2, -(distributionIndex + 1.0))
var betaq2 = computebetaQ(alpha2,distributionIndex,rand)
//calcul offspring2 en utilisant betaq2
var c2 = 0.5 * ((y1 + y2) + betaq2 * (y2 - y1))
if (c1 < yL) c1 = yL
if (c1 > yu) c1 = yu
if (c2 < yL) c2 = yL
if (c2 > yu) c2 = yu
if (aprng.nextDouble <= 0.5) {
(c2,c1)
} else {
(c1, c2)
}
}else{
(g1e, g2e)
}
}else{
(g2e, g1e)
}
}
}else{
// not so good here ...
(g1.wrappedValues zip g2.wrappedValues)
}
}
(factory.buildGenome(offspring.map{_._1}), factory.buildGenome(offspring.map{_._2}))
}
def computebetaQ(alpha:Double, distributionIndex:Double, rand:Double):Double = {
if (rand <= (1.0/alpha)){
pow ((rand * alpha),(1.0 / (distributionIndex + 1.0)))
} else {
pow ((1.0 / (2.0 - rand * alpha)),(1.0 / (distributionIndex + 1.0)))
}
}
Thanks a lot for your advice, or help in this problem.
SR
Reyman64, your question is the answer I was looking for. Thank you.
I took the paper you linked and the code of Deb's implementation and tried to understand both. For that, I commented almost every line of the code. They differ only in the calculation of beta.
Since Deb used this code in his implementation of the NSGA-II, I'll stick to this version of the algorithm.
If anyone is in the same situation I was (not understanding how to implement SBX), I left my commentaries in the following gist, take a look.
https://gist.github.com/Tiagoperes/1779d5f1c89bae0cfdb87b1960bba36d
I did an implementation of the SBX (it is called Simulated Binary Crossover btw) for HeuristicLab (C#). You can take a look at the implementation of our SimulatedBinaryCrossover. I took the description from a different reference however (paper title: "Simulated binary crossover for continuous search space" from 1995). The full citation is given in the source code.

Designing a symbolic equation solver

For a class I was assigned to a project to do a basic equation solver. It needs to solve linear equations. E.g. of some equations I should be able to solve:
a*x + b = c
ax + b = cx + d
16*x – 9*x = a
x/16 – x/9 = a
8*(x+3) – 5*(x + 4) = 12
x^2 + 2*x + 1 = 0
(x + 1)*(x – 1) = 0
(x + 1)(x – 1) = 2(x-1)
x – 2*sqrt(x) + 1 = 0
log 3*x - log 6 = 1
log 3*x – log 6*x^2 = a
2^(x-1) * a = 2^(3*x+1)
I have looked and only found a handful of helpful suggestions. I tried to understand this implementation but failed to see where I put the arithmetic rules. I tried to read the Sympy source code but I don't know were to look for what I am looking for. I thought of defining certain rules in a txt files. For example u - v + v = u and tried look how to apply this rule to the equations.
Do any of you have an idea how I could design this?
First, you should think about how to declare an equation (or polynomials) for that purpose. For example you could define
data Polynomial = Polynomial [Polynomial]
| Sum Polynomial Polynomial
| Ln Polynomial
| Log10 Polynomial Polynomial
| Var String -- a named Variable
| ...
For easily dealing with Polynomials you could create instances for your data type Polynomial for Eq, Ord, Num, and so on, so that you could deal with a Polynomial just like with numbers.
instance Num Polynomial where
a + b = ...
For creating these functions you can easily use Pattern Matching:
(Sum a b) + (Sum c d) = Sum (Sum a b) (Sum c d)
For an equation you could simply use tupels and create a new type for it:
type Equation = (Polynomial, Polynomial)
For solving it, a function like this could be used:
solve :: Equation -> String -> Polynomial
...where the String is the Name of a Variable.
Solve would than need to do the real work. Again, for this Pattern Matching could be used for the first steps:
solve ((Sum (Var a) b, e) x -- solves polynomials of type a + b = c + d
| a == x = Sum e (negate b)
| ...
Of course this is very basic and you could do it a lot smarter, by cutting down the number of possible cases using a normalization that e.g. combines "a + a + a" into "3 * a".
You have the choice to either writing your own math expression parser/interpreter or use an existing one. Jep is a good example of an open source math expression parser.
Otherwise, if you would like to know what compilers and syntactic analyzers do under the hood then you can write your own expression parser using jFlex and CUP
Also, here is an excellent tutorial on antlr that might help you get started.

Categories

Resources