List of blocks to a whole matrix - java - java

So I'm having the following problem: I have a method that breaks a big matrix into smaller blocks of the same size. After I do some operations on the blocks, I want to reconstruct the big matrix in the right order, but I'm going wrong at it somehow.
The following code reconstructs correctly a 4x4 matrix that breaks into 2x2, but for any other dimensions, it's not working properly.
public long[][] blocksToMatrix(List<long[][]> blocks, int blockDimension, int width, int height ){
long[][] yuvMatrix = new long[height][width];
int heightPos = 0;
int widthPos = 0;
for (int i = 0; i < blocks.size(); i++) {
long[][] yuvBlock = blocks.get(i);
int heightPosTemp = heightPos;
for (int j = 0; j < blockDimension * blockDimension; j++) {
yuvMatrix[heightPos][widthPos] = yuvBlock[j / blockDimension][j % blockDimension];
widthPos++;
if (widthPos >= width){
widthPos = (i * blockDimension) % width;
heightPos++;
}
if (widthPos == ((i + 1) * blockDimension) % width){
widthPos = (i * blockDimension) % width;
heightPos++;
}
}
if (heightPos == height ){
heightPos = heightPosTemp;
}
else {
heightPos = (i * blockDimension) % height;
}
widthPos = ((i + 1) * blockDimension) % width;
}
return yuvMatrix;
}
The method I used to break the matrix:
public List<long[][]> matrixToBlocks(long[][] yuvMatrix, int blockDimension, int width, int height){
int blocksSize = width / blockDimension * (height / blockDimension);
List<long[][]> blocks = new ArrayList<long[][]>();
for (int i = 0; i < blocksSize; i++) {
long[][] subBlock = new long[blockDimension][blockDimension];
int heightPos = (blockDimension * (i / blockDimension)) % height;
int widthPos = (blockDimension * i) % width;
if (widthPos + blockDimension > width) {
widthPos = 0;
}
for (int row = 0; row < blockDimension; row++) {
for (int col = 0; col < blockDimension; col++) {
subBlock[row][col] = yuvMatrix[heightPos + row][col + widthPos];
}
}
blocks.add(subBlock);
}
return blocks;
}
The way I tested it:
public static void testareMatBlo(int height, int width, int blockdim){
long[][] test = new long[height][width];
int val = 1;
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
test[i][j] = val;
val++;
}
}
List<long[][]> blocks = matrixToBlocks(test, blockdim, width, height);
long[][] matrix = blocksToMatrix(blocks, blockdim, width, height);
if (Arrays.deepEquals(test, matrix)){
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
This works:
testareMatBlo(4, 4, 2);
But anything else doesn't. Can anyone explain what I did wrong?

I didn't thoroughly read your code for matrixToBlocks(...) but all those calculations like int blocksSize = width / blockDimension * (height / blockDimension); are very likely to introduce hard to spot errors - and you actually don't need them:
public static List<long[][]> matrixToBlocks(long[][] yuvMatrix, int blockDimension){
//Check matrix and block dimension match
if( yuvMatrix.length == 0 || yuvMatrix.length % blockDimension != 0
|| yuvMatrix[0].length == 0 || yuvMatrix[0].length % blockDimension != 0 ) {
throw new IllegalArgumentException("whatever message you like");
}
List<long[][]> blocks = new ArrayList<long[][]>();
//Iterate over the blocks in row-major order (down first, then right)
for( int c = 0; c < yuvMatrix.length; c += blockDimension ) {
for( int r = 0; r < yuvMatrix[c].length; r += blockDimension ) {
long[][] subBlock = new long[blockDimension][blockDimension];
//Iterate over the block in row-major order
for(int bc = 0; bc < blockDimension; bc++ ) {
for(int br = 0; br < blockDimension; br++ ) {
subBlock[bc][br]=yuvMatrix[c+bc][r+br];
}
}
blocks.add(subBlock);
}
}
return blocks;
}
That method doesn't look shorter but it is: discounting the preliminary check yours is missing there are only 8 actual lines of code compared to 13 in your code. That's not the point however. What's more important is that the logic is easier since there are only a few calculations involved (like c+bc).
You might think this is inefficient but it isn't: you're accessing each element only once and thus even though there are 4 nested loops the overall complexity is still O(n) with n being the size of the matrix.
Constructing the matrix back is equally easy. The major thing you need to take care of is the ordering of the blocks: if you create them in row-major order (blocks below each other are next to each other in the list) you need to recreate the matrix in the same way:
public static long[][] blocksToMatrix( List<long[][]> blocks, int width, int height ) {
long[][] yuvMatrix = new long[width][height];
int c = 0;
int r = 0;
for( long[][] block : blocks ) {
int blockWidth = block.length;
int blockHeight = block[0].length;
for( int bc = 0; bc < block.length; bc++ ) {
for( int br = 0; br < block[bc].length; br++ ) {
yuvMatrix[c + bc][r + br] = block[bc][br];
}
}
//calculate the next offset into the matrix
//The blocks where created in row-major order so we need to advance the offset in the same way
r += blockHeight;
if( r >= height ) {
r = 0;
c += blockWidth;
}
}
return yuvMatrix;
}

Related

How can I make this ImageBrightener method function properly?

This ImageBrightener method is supposed to brighten the image by increasing the color values. Each value should increase half the distance between it and 255. Thus, 155 would go to 205 while 205 would go to 230 and so on. Can anyone help figure out the issue with ImageBrightener! Thanks
import squint.SImage;
public class ImageBrightener implements ImageTransformer {
#Override
public SImage transform(SImage picture) {
return BrightenImage(picture);
}
private static SImage BrightenImage(SImage si) {
int[][] newReds = BrightenImageSingleChannel(si.getRedPixelArray());
int[][] newGreens = BrightenImageSingleChannel(si.getGreenPixelArray());
int[][] newBlues = BrightenImageSingleChannel(si.getBluePixelArray());
return new SImage(newReds, newGreens, newBlues);
}
// Here is the code to brighten the image and is not functioning properly
private static int[][] BrightenImageSingleChannel(int[][] pixelArray) {
private static int[][] BrightenImageSingleChannel(int[][] pixelArray) {
int columns = pixelArray.length;
int rows = pixelArray[0].length;
int[][] answer = new int[columns][rows];
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
answer[x][y] = 255 - pixelArray[x][y] ;
answer[x][y] = answer[x][y] + pixelArray[x][y] ;
}
}
return answer;
}
}
// Here is the properly functioning code for darkening my image.
private static int[][] DarkenImageSingleChannel(int[][] pixelArray) {
int columns = pixelArray.length;
int rows = pixelArray[0].length;
int[][] answer = new int[columns][rows];
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
answer[x][y] = (255 * 2) / 3 - pixelArray[x][y];
}
}
return answer;
}
}
The problem is here
answer[x][y] = 255 - pixelArray[x][y] ;
answer[x][y] = answer[x][y] + pixelArray[x][y] ;
answer[x][y] will always be 255.
Try this
answer[x][y] = (pixelArray[x][y] + 255) / 2;

Gabor wavelets in 2d image

I use lire, java for image retrieval project and I want to calculate the amplitude of gabor wavelet for every pixel of my input image ref here. The default function in lire library return a downsampled feature vector. What I want the computed amplitude of the gabor wavelets. I am trying to create a function getMagnitude:
public double[][] getMagnitude(BufferedImage image) {
image = ImageUtils.scaleImage(image, MAX_IMG_HEIGHT);
Raster imageRaster = image.getRaster();
System.out.println(imageRaster);
int[][] grayLevel = new int[imageRaster.getWidth()][imageRaster.getHeight()];
int[] tmp = new int[3];
for (int i = 0; i < imageRaster.getWidth(); i++) {
for (int j = 0; j < imageRaster.getHeight(); j++) {
grayLevel[i][j] = imageRaster.getPixel(i, j, tmp)[0];
}
}
double[][] magnitudes = computeMagnitudes(grayLevel);
return magnitudes;
}
The gabor features are class gabor private variables:
private static final double U_H = .4;
private static final double U_L = .05;
private static final int S = 1, T = 1; // filter mask size
private static final int M = 4, N = 5; // scale & orientation
private static final int MAX_IMG_HEIGHT = 64;
Moreover, it seems that the size of the final magnitude array is affected from the size of M, N scale and orientation. What I ve got to do in order to get the case I want?
COmpute magnitude function:
private double[][] computeMagnitudes(int[][] image) {
double[][] magnitudes = new double[M][N];
for (int i = 0; i < magnitudes.length; i++) {
for (int j = 0; j < magnitudes[0].length; j++) {
magnitudes[i][j] = 0.;
}
}
if (this.gaborWavelet == null) {
precomputeGaborWavelet(image);
}
for (int m = 0; m < M; m++) {
for (int n = 0; n < N; n++) {
for (int x = S; x < image.length; x++) {
for (int y = T; y < image[0].length; y++) {
magnitudes[m][n] += Math.sqrt(Math.pow(this.gaborWavelet[x - S][y - T][m][n][0], 2) + Math.pow(this.gaborWavelet[x - S][y - T][m][n][1], 2));
}
}
}
}
return magnitudes;
}
I think that you ve got to use 5d private double[][][][][] gaborWavelet which is actually calculate the convolution between the image and mother wavelets.
private double[] gaborWavelet(int[][] img, int x, int y, int m, int n) {
double re = 0;
double im = 0;
for (int s = 0; s < S; s++) {
for (int t = 0; t < T; t++) {
re += img[x][y] * selfSimilarGaborWavelets[s][t][m][n][0];
im += img[x][y] * -selfSimilarGaborWavelets[s][t][m][n][1];
}
}
return new double[]{re, im};
}
You have to choose M, N , S, T and the returned wavelets contains two matrices for re and im.

Image-mouse intersection / hover effect issue when using arrays

I'm working on a small exercise that involves making an interface of six die faces. The goal is to change the color of each die face when I hover over it. The issue I'm having is that I can only change the color of the first die face, not the proceeding. I've been reluctant to come here and ask because I feel my issue is so insignificant but I've been trying to get this to work for the last 4 days and I just can't figure it out. I feel there is something about iteration that I'm just quite not understanding yet.
Dice[] dice = new Dice[6];
void setup(){
size(600,100);
for(int i = 0; i < dice.length; i++){
dice[i] = new Dice(i*100,0,100,100);
}
imageMode(CORNER);
}
void draw(){
for(int i = 0; i < dice.length; i++){
for(int j = 0; j < dice.length; j++){
if(j!=i && dice[i].checkHover(mouseX,mouseY)){
dice[i].drawDice(i,true);
} else {
dice[i].drawDice(i,false);
}
}
}
}
class Dice{
PImage[] diceFace = new PImage[6];
PImage[] diceFaceHover = new PImage[6];
int x;
int y;
int w;
int h;
Dice(int bx, int by, int bw, int bh){
x = bx;
y = by;
w = bw;
h = bh;
for(int i = 0; i < dice.length; i++){//loads the images
diceFace[i] = loadImage(i+".png");
diceFaceHover[i] = loadImage(i+"h.png");
}
}
void drawDice(int i, boolean hover){
if(hover){
image(diceFaceHover[i],x,y,w,h);
} else {
image(diceFace[i],x,y,w,h);
}
}
boolean checkHover(float mx, float my){
if((mx > x && mx < w) && (my > y && my < h)){
return true;
} else {
return false;
}
}
}
I'll continue searching for a solution in the meantime.
You have bad condition for checking hover. Don't forget that w and h are same for all dices but you need position not size.
if( (mx > x & mx < x+w) && ( my >y && my < y+h ) )

java version of bat algorithm in matlab

I have a Matlab code of bat algorithm and I write java version of this algorithm
Bat algorithm is a simple optimization algorithm for finding the minimum of any function
here is the matlab code and my java version of this code
My java version of this algorithm can't find the optimum result like matlab version
and I can't find where is my mistake in converting the code from matlab to java
Can anyone help me where is my mistake?
import java.util.Random;
public class Bat
{
private int n;
private float A, r;
private float Qmin, Qmax;
private int d;
private int NofGen;
private float fmin;
private int fminIndex;
private float Fnew;
private int loopCounter;
private float Q[], V[][], Sol[][], UL_bound[][], fitness[], S[][], Best[];
private Random myRand;
public Bat(
int NBats,
float loudness,
float pulseRate,
float minFreq,
float maxFreq,
int NofGeneration,
int dimension
)
{
n = NBats;
A = loudness;
r = pulseRate;
Qmin = minFreq;
Qmax = maxFreq;
NofGen = NofGeneration;
d = dimension;
S = new float[n][d];
Best = new float[d];
UL_bound = new float[2][d];
//default bounds
for(int i = 0 ; i < d ; i++)
{
UL_bound[0][i] = -10000;
UL_bound[1][i] = 10000;
}
loopCounter = 0;
myRand = new Random();
Q = new float[n];
for(int i = 0 ; i < n ; i++)
Q[i] = 0;
V = new float[n][d];
for(int i = 0 ; i < n ; i++)
for(int j = 0 ; j < d ; j++)
V[i][j] = 0;
}
public void intial()
{
Sol = new float[n][d];
for(int i = 0 ; i < n ; i++)
for(int j = 0 ; j < d ; j++)
{
float t = myRand.nextFloat();
//(upper -lower)*rand + lower
Sol[i][j] = t * (UL_bound[1][j] - UL_bound[0][j]) + UL_bound[0][j];
}
fitness = new float[n];
for(int i = 0 ; i < n ; i++)
fitness[i] = function(Sol[i]);
//finding fmin
fmin = fitness[0];
fminIndex = 0;
for(int i = 0 ; i < n ; i++)
{
if (fitness[i] < fmin)
{
fmin = fitness[i];
fminIndex = i;
}
}
//setting best
for(int j = 0 ; j < d ; j++)
Best[j] = Sol[fminIndex][j];
}
public void start()
{
while(loopCounter < NofGen)
{
for(int i = 0 ; i < n ; i++)
{
Q[i] = Qmin + (Qmin - Qmax)* myRand.nextFloat();
for(int j = 0 ; j < d ; j++)
V[i][j] = V[i][j] + (Sol[i][j]-Best[j])*Q[i];
for(int j = 0 ; j < d ; j++)
S[i][j] = Sol[i][j] + V[i][j];
Sol[i] = simpleBounds(Sol[i]);
if(myRand.nextFloat() > r)
for(int j = 0 ; j < d ; j++)
S[i][j] = (float) (Best[j] + (.001 * myRand.nextFloat()) );
Fnew = function(S[i]);
if(Fnew <= fitness[i] && myRand.nextFloat() < A)
{
for(int j = 0 ; j < d ; j++)
Sol[i][j] = S[i][j];
fitness[i] = Fnew;
}
if(Fnew <= fmin)
{
fmin = Fnew;
for(int j = 0 ; j < d ; j++)
Best[j] = S[i][j];
}
}
loopCounter++;
}
}
public float[] simpleBounds(float p[])
{
for(int i = 0 ; i < d ; i++)
{
if(p[i] < UL_bound[0][i])
p[i] = UL_bound[0][i];
if(p[i] > UL_bound[1][i])
p[i] = UL_bound[1][i];
}
return p;
}
float function(float p[])
{
// Sphere function with fmin=0 at (0,0,...,0)
float sum = 0;
for(int i = 0 ; i < p.length ; i++)
sum = sum + p[i]*p[i];
return sum;
}
public float printResult()
{
System.out.println("After " + loopCounter + "Repeats :");
for(int i = 0 ; i < d ; i++)
System.out.print(Best[i] + ", ");
System.out.println ( "F(x) = " + fmin);
return fmin;
}
public void set_UL_Bound(int n, float L, float U)
{
if( n < d && n >= 0)
{
UL_bound[0][n] = L;
UL_bound[1][n] = U;
}
}
}
and this is the matlab versian
function [best,fmin,N_iter]=bat_algorithm(para)
% Display help
help bat_algorithm.m
% Default parameters
if nargin<1, para=[20 1000 0.5 0.5]; end
n=para(1); % Population size, typically 10 to 40
N_gen=para(2); % Number of generations
A=para(3); % Loudness (constant or decreasing)
r=para(4); % Pulse rate (constant or decreasing)
% This frequency range determines the scalings
% You should change these values if necessary
Qmin=0; % Frequency minimum
Qmax=2; % Frequency maximum
% Iteration parameters
N_iter=0; % Total number of function evaluations
% Dimension of the search variables
d=5; % Number of dimensions
% Lower limit/bounds/ a vector
Lb=-3*ones(1,d);
% Upper limit/bounds/ a vector
Ub=6*ones(1,d);
% Initializing arrays
Q=zeros(n,1); % Frequency
v=zeros(n,d); % Velocities
% Initialize the population/solutions
for i=1:n,
Sol(i,:)=Lb+(Ub-Lb).*rand(1,d);
Fitness(i)=Fun(Sol(i,:));
end
% Find the initial best solution
[fmin,I]=min(Fitness);
best=Sol(I,:);
for t=1:N_gen,
% Loop over all bats/solutions
for i=1:n,
Q(i)=Qmin+(Qmin-Qmax)*rand;
v(i,:)=v(i,:)+(Sol(i,:)-best)*Q(i);
S(i,:)=Sol(i,:)+v(i,:);
% Apply simple bounds/limits
Sol(i,:)=simplebounds(Sol(i,:),Lb,Ub);
% Pulse rate
if rand>r
% The factor 0.001 limits the step sizes of random walks
S(i,:)=best+0.001*randn(1,d);
end
% Evaluate new solutions
Fnew=Fun(S(i,:));
% Update if the solution improves, or not too loud
if (Fnew<=Fitness(i)) & (rand<A) ,
Sol(i,:)=S(i,:);
Fitness(i)=Fnew;
end
% Update the current best solution
if Fnew<=fmin,
best=S(i,:);
fmin=Fnew;
end
end
N_iter=N_iter+n;
end
% Output/display
disp(['Number of evaluations: ',num2str(N_iter)]);
disp(['Best =',num2str(best),' fmin=',num2str(fmin)]);
% Application of simple limits/bounds
function s=simplebounds(s,Lb,Ub)
% Apply the lower bound vector
ns_tmp=s;
I=ns_tmp<Lb;
ns_tmp(I)=Lb(I);
% Apply the upper bound vector
J=ns_tmp>Ub;
ns_tmp(J)=Ub(J);
% Update this new move
s=ns_tmp;
function z=Fun(u)
% Sphere function with fmin=0 at (0,0,...,0)
z=sum(u.^2);
%%%%% ============ end ====================================
The diff between two codes
In Matlab code:
S(i,:)=best+0.001*randn(1,d);
randn=>standard normal distribution.
While in Java code:
S[i][j] = (float) (Best[j] + (.001 * myRand.nextFloat()) );
java.util.Random.nextFloat()=>uniformly distributed float value between 0.0 and 1.0.
I was looking for the solution in C# and stumbled up on this. It was enough to get the job done. Here is the solution in C# translated from the java with variables renamed and an additional fitness function for finding the solution of two x,y equations xy=6 and x+y = 5. Also included is finding the square root of .3 :
using System;
namespace BatAlgorithmC
namespace BatAlgorithmC
{
class Program
{
static void Main(string[] args)
{
// Mybat x = new Mybat(100, 1000, 0.5, 0.5, 5, Mybat.sphere);
// Mybat x = new Mybat(1000, 1000, 0.5, 0.5, 1, Mybat.squareRoot);
Mybat x = new Mybat(1000, 1000, 0.5, 0.5, 2, Mybat.RootOfXYEquations);
Console.WriteLine("Hit any key to continue.");
Console.ReadLine();
}
}
public class Mybat
{
/**
* #param args the command line arguments
*/
public int _numberOfBats, _generations, Qmin, Qmax, N_iter, _dimension;
public double _volume, _pulseRate, min, max, fnew, fmin;
public double[][] _lowerBound, _upperBound, _velocity, _solution, S;
public double[] _fitness, _tempSolution, _bestSolution, Q;
public Random random;
//public static void main(String[] args) {
// Mybat x = new Mybat(20,1000,0.5,0.5,5, Mybat.sphere);
//}
public static void initJagged(double[][] array, int n, int d)
{
for (int i = 0; i < n; i++) array[i] = new double[d];
}
public Mybat(
int bats,
int generations,
double loud,
double pulse,
int dimension,
Func<double[], int, double> function
)
{
//initialization of variables
_numberOfBats = bats;
_generations = generations;
_volume = loud;
_pulseRate = pulse;
_dimension = dimension;
Random random = new Random();
//plan to change later and added as parameter
min = -15;
max = 15;
fmin = 0;
//decleration for the bounds
_lowerBound = new double[1][];
_upperBound = new double[1][];
Q = new double[_numberOfBats]; // frequency
_velocity = new double[_numberOfBats][]; //velocity
initJagged(_velocity, _numberOfBats, _dimension);
initJagged(_lowerBound, 1, _dimension);
initJagged(_upperBound, 1, _dimension);
//initialize solution array
_solution = new double[_numberOfBats][];
S = new double[_numberOfBats][];
_fitness = new double[_numberOfBats]; // fitness container
_bestSolution = new double[_dimension];
_tempSolution = new double[_dimension]; //temporary holder for a row in array _solution
initJagged(_solution, _numberOfBats, _dimension);
initJagged(S, _numberOfBats, _dimension);
for (int i = 0; i < _numberOfBats; i++)
{
// for minimal coding : added initialize Q[]array with '0' as element
Q[i] = 0;
for (int x = 0; x < _dimension; x++)
{
// for minimal coding : added initialize _velocity[][] array with '0' as element
_velocity[i][x] = 0;
//find random double values from LB to UB
_solution[i][x] = (random.NextDouble()*(max - min)) + min;
_tempSolution[x] = _solution[i][x];
//Console.WriteLine("sol["+i+"]["+x+"] = "+_solution[i][x]); //test line
//Console.WriteLine(rand.nextDouble()); //test line
}
_fitness[i] = function(_tempSolution, _dimension);
//initialize best and the fmin
if (i == 0 || fmin > _fitness[i])
{
fmin = _fitness[i];
for (int x = 0; x < _dimension; x++)
{
_bestSolution[x] = _solution[i][x];
}
}
Console.WriteLine("fitness[" + i + "]" + _fitness[i]); //test
}
Console.WriteLine("fmin = " + fmin); //test
// special note to these variables (below)
// change if required for maximum effectivity
Qmin = 0;
Qmax = 2;
N_iter = 1; //number of function evaluation
// bat proper
for (int loop = 0; loop < N_iter; loop++)
{
// loop over all bats/solutions
for (int nextBat = 0; nextBat < _numberOfBats; nextBat++)
{
Q[nextBat] = Qmin + ((Qmin - Qmax)*random.NextDouble());
// loop for velocity
for (int vel = 0; vel < _dimension; vel++)
{
_velocity[nextBat][vel] = _velocity[nextBat][vel] +
((_solution[nextBat][vel] - _bestSolution[vel])*Q[nextBat]);
}
//new solutions
for (int nextDimension = 0; nextDimension < _dimension; nextDimension++)
{
S[nextBat][nextDimension] = _solution[nextBat][nextDimension] +
_velocity[nextBat][nextDimension];
}
/**
* RESERVED SPOT for the QUESTIONABLE AREA ON THE
* MATLAB CODE (i think it is not needed for the java equivalent)
*/
// pulse rate
if (random.NextDouble() > _pulseRate)
{
for (int nextDimension = 0; nextDimension < _dimension; nextDimension++)
{
S[nextBat][nextDimension] = _bestSolution[nextDimension] + (0.001*random.NextGaussian());
}
}
//putting current row of _solution to a temp array
for (int nextDimension = 0; nextDimension < _dimension; nextDimension++)
{
_tempSolution[nextDimension] = S[nextBat][nextDimension];
}
fnew = function(_tempSolution, _dimension);
// update if solution is improved, and not too loud
if ((fnew <= _fitness[nextBat]) && (random.NextDouble() < _volume))
{
for (int x = 0; x < _dimension; x++)
{
_solution[nextBat][x] = S[nextBat][x];
_fitness[nextBat] = fnew;
}
}
//update current best solution
if (fnew <= fmin)
{
for (int nextDimension = 0; nextDimension < _dimension; nextDimension++)
{
_bestSolution[nextDimension] = S[nextBat][nextDimension];
fmin = fnew;
}
}
}
}
Console.WriteLine(" ");
Console.WriteLine("new fitness");
for (int i = 0; i < _numberOfBats; i++)
{
Console.WriteLine("fitness[" + i + "]" + _fitness[i]);
}
for (int nextDimension = 0; nextDimension < _dimension; nextDimension++)
{
Console.WriteLine("best[" + nextDimension + "]" + _bestSolution[nextDimension]);
}
Console.WriteLine("Fmin = " + fmin);
}
//possible that this function is not needed in java
public void set_bounds(int x, double L, double U)
{
//double temp_Lb[x];
//double temp_Ub[x];
for (int i = 0; i < x; i++)
{
_lowerBound[0][i] = L;
_upperBound[0][i] = U;
}
}
public static double sphere(double[] value, int d)
{
// sphere function where fmin is at 0
double result = 0;
for (int i = 0; i < d; i++)
{
result += (value[i]*value[i]);
}
return result;
}
public static double squareRoot(double[] value, int d)
{
// find the square root of .3
double result = 0;
for (int i = 0; i < d; i++)
{
result += Math.Abs(.3 - (value[i]*value[i]));
}
return result;
}
public static double RootOfXYEquations(double[] value, int d)
{
// solve for x and y xy = 6 and x+y = 5
double result = 0;
result += Math.Abs(5 - (value[0] + value[1]));
result += Math.Abs(6 - (value[0] * value[1]));
return result;
}
}
static class MathExtensiionns
{
public static double NextGaussian(this Random rand)
{
double u1 = rand.NextDouble(); //these are uniform(0,1) random doubles
double u2 = rand.NextDouble();
double mean = 0, stdDev = 1;
double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)
double randNormal =
mean + stdDev * randStdNormal; //random normal(mean,stdDev^2)
return randNormal;
}
}
}
this will be my first time here at stack overflow so i will say sorry beforehand if my response will be a bit ambiguous and has many problems. i just hope that this answer of mine will help future visitors on this thread who wants to study bat algo via java.
anyway, i did look at your code since i am studying bat algorithm at the moment.
tried running it and it does gives far off results compared to the matlab version.
what i noticed is that you just "literally" tried to convert the matlab code without fully understanding each matlab lines. i wanted to point out all of the stuff you missed but i am feeling lazy right now so i will just leave my version of bat algorithm in java.
NOTE: i just made a running bat algorithm in java. not an efficient, fully debugged, matlab's java-equivalent bat algorithm.
import java.util.Random;
public class Mybat {
/**
* #param args the command line arguments
*/
public int n, N_gen, Qmin, Qmax, N_iter, d;
public double A,r,min,max,fnew,fmin;
public double Lb[][],Ub[][],Q[],v[][],Sol[][],S[][],fitness[],temp[],best[];
public Random random;
public static void main(String[] args) {
Mybat x = new Mybat(20,1000,0.5,0.5,5);
}
public Mybat(
int bats,
int generations,
double loud,
double pulse,
int dimension
){
//initialization of variables
n=bats;
N_gen = generations;
A = loud;
r = pulse;
d = dimension;
Random rand = new Random();
//plan to change later and added as parameter
min = -15;
max = 15;
fmin = 0;
//decleration for the bounds
Lb = new double[1][d];
Ub = new double[1][d];
Q = new double[n]; // frequency
v = new double[n][d]; //velocity
//initialize solution array
Sol = new double[n][d];
S = new double[n][d];
fitness = new double[n]; // fitness container
best =new double[d];
temp = new double[d]; //temporary holder for a row in array Sol
for(int i=0;i<n;i++){
// for minimal coding : added initialize Q[]array with '0' as element
Q[i] = 0;
for(int x=0;x<d;x++){
// for minimal coding : added initialize v[][] array with '0' as element
v[i][x] = 0;
//find random double values from LB to UB
Sol[i][x]= (rand.nextDouble()*(max - min)) + min;
temp[x] = Sol[i][x];
//System.out.println("sol["+i+"]["+x+"] = "+Sol[i][x]); //test line
//System.out.println(rand.nextDouble()); //test line
}
fitness[i] = function(temp);
//initialize best and the fmin
if(i==0 || fmin > fitness[i]){
fmin = fitness[i];
for(int x=0;x<d;x++){
best[x] = Sol[i][x];
}
}
System.out.println("fitness["+i+"]"+fitness[i]); //test
}
System.out.println("fmin = "+fmin); //test
// special note to these variables (below)
// change if required for maximum effectivity
Qmin = 0;
Qmax = 2;
N_iter = 1; //number of function evaluation
// bat proper
for(int loop=0;loop<N_iter;loop++){
// loop over all bats/solutions
for(int i=0;i<n;i++){
Q[i] = Qmin+((Qmin-Qmax)*rand.nextDouble());
// loop for velocity
for(int vel=0;vel<d;vel++){
v[i][vel] = v[i][vel]+((Sol[i][vel]-best[vel])*Q[i]);
}
//new solutions
for(int x=0;x<d;x++){
S[i][x] = Sol[i][x] + v[i][x];
}
/**
* RESERVED SPOT for the QUESTIONABLE AREA ON THE
* MATLAB CODE (i think it is not needed for the java equivalent)
*/
// pulse rate
if(rand.nextDouble()>r){
for(int x=0;x<d;x++){
S[i][x] = best[x]+(0.001*rand.nextGaussian());
}
}
//putting current row of Sol to a temp array
for(int x=0;x<d;x++){
temp[x] = S[i][x];
}
fnew = function(temp);
// update if solution is improved, and not too loud
if((fnew<=fitness[i]) && (rand.nextDouble()<A)){
for(int x=0;x<d;x++){
Sol[i][x] = S[i][x];
fitness[i] = fnew;
}
}
//update current best solution
if(fnew<=fmin){
for(int x=0;x<d;x++){
best[x] = S[i][x];
fmin = fnew;
}
}
}
}
System.out.println(" ");
System.out.println("new fitness");
for(int i=0;i<n;i++){
System.out.println("fitness["+i+"]"+fitness[i]);
}
System.out.println("Fmin = "+fmin);
}
//possible that this function is not needed in java
public void set_bounds(int x, double L, double U){
//double temp_Lb[x];
//double temp_Ub[x];
for(int i=0; i<x; i++){
Lb[0][i] = L;
Ub[0][i] = U;
}
}
public double function(double value[]){
// sphere function where fmin is at 0
double result = 0;
for(int i=0;i<d;i++){
result += (value[i]*value[i]);
}
return result;
}
}

algorithm for adding the diagonals on a square or rectangular matrix, starting rightwise

I want to add the diagonals in a square or rectangular matrix to emulate the process of adding the partial results in a multiplying algorithm.
Like this:
2412
x 3231
---------
2412
7236
4824
+ 7236
---------
7793172
I need to run this, step by step, to satisfy the requirements of an online judge program. I have already figured out how to get the partial results of the multiplications (the humbers 2412, 7236, 4824, 7236) and I have placed them on a square matrix.
I realized I can get the addition result of this matrix by considering square or rectangular like:
2 4 1 2
7 2 3 6
4 8 2 4
7 2 3 6
and get the result of the addition by adding each diagonal (starting with the upper right one) and taking into account the carry of the addition and using an auxiliary array that has the same number of digits as number_of_digits_in_operand_a + number_of_digits_in_operand_b (operand a being 2412 and operand b being 3231, in this case).
For example, the array result, on its rightmost position should be:
result[(digits_a+digits_b)-1] = partialResult[0][3];
next:
result[digits_a+digits_b]=(partialResult[0][2] + partialResult[1][3] + carry) %10;
newCarry = (partialResult[0][2] + partialResult[1][3] + carry) / 10;
Well, I'm stuck writing the double nested loop that's supposed to add these diagonals starting with the upper right one. Help. Please.
I ended up using this (don't ask why it converts a BigInteger to an ArrayList and viceversa, it's a bizarre homework requirement).
public static BigInteger simpleMultiply(BigInteger x, BigInteger y) throws IOException {
char [] longerNum;
char [] shorterNum;
ArrayList<Integer> multResult= new ArrayList<Integer>(2000);
if(x.compareTo(y)>=0){ // x is a longer/equal num
longerNum = x.toString().toCharArray();
shorterNum = y.toString().toCharArray();
}
else { //y is a longer num
longerNum = y.toString().toCharArray();
shorterNum = x.toString().toCharArray();
}
//shorter num equals the number of rows in partial result
// longer num + 1 equals the number of columns in partial result
int [][] partialResult = new int [shorterNum.length][longerNum.length+1];
int pastCarry=0;
int result=0;
int carry=0;
for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--){
pastCarry=0;
for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
{
int sInt = Integer.parseInt(""+shorterNum[sIndex]+"");
int lInt = Integer.parseInt(""+longerNum[lIndex]+"");
int product = sInt*lInt;
if (lIndex==0){
result = (pastCarry+product)% 10;
carry = (pastCarry+product) / 10;
pastCarry = carry;
partialResult [sIndex][lIndex+1] = result; //one more column element in partialResult
partialResult[sIndex][lIndex] = carry;
}
else {
result = (pastCarry+product) % 10;
carry = (pastCarry+product) / 10;
pastCarry = carry;
partialResult [sIndex][lIndex+1] = result;//one more column element in partialResult
}
}
}
for (int i=0; i<partialResult.length;i++)
for (int j=0; j<partialResult[0].length;j++)
{
System.out.print(partialResult[i][j] + " ");
if (j==partialResult[0].length-1){System.out.println();}
}
int auxColumn=0;
int diagonalAcum=0;
//add diagonals
int copyDigit=0;
int carryDigit=0;
int lastCarry=0;
rowCycle:
for (int column=partialResult[0].length-1; column>=0; column--){
diagonalAcum=0; //carryDigit=0;
diagonalAcum+=carryDigit;
auxColumn=column;
for (int row=0; row<partialResult.length; row++){
if (auxColumn+1 ==partialResult[0].length){
diagonalAcum+=partialResult[row][auxColumn++];
copyDigit=diagonalAcum % 10;
carryDigit=diagonalAcum / 10;
multResult.add(copyDigit);
continue rowCycle;
}
diagonalAcum+=partialResult[row][auxColumn++];
} //end row cycle
copyDigit= diagonalAcum % 10;
carryDigit=diagonalAcum / 10;
multResult.add(copyDigit);
if(column==0){
lastCarry = carryDigit;
}
}
carryDigit=0; //reset
int diagonal2Acum=0;
// diagonal2Acum +=lastCarry;
int auxRow;
int diagCarry=0;
int rowLimit=partialResult.length-1;
int colLimit=partialResult[0].length-1;
int initialRow=1;
int colIndex=0;
for (int row=initialRow;row<=rowLimit;row++){
diagonal2Acum=0;
diagonal2Acum +=lastCarry;
lastCarry=0;
auxRow = row;
colIndex=0;
// partialResult[auxRow][]
while ((auxRow<=rowLimit) && (colIndex<=colLimit)){
diagonal2Acum+= partialResult[auxRow++][colIndex++];
}
if ((colIndex==0)&&(row==rowLimit)) {
copyDigit=(diagonal2Acum+carryDigit)%10;
carryDigit=(diagonal2Acum+carryDigit)/10;
multResult.add(copyDigit);
multResult.add(carryDigit);
}
else {
copyDigit=(diagonal2Acum+carryDigit)%10;
carryDigit=(diagonal2Acum+carryDigit)/10;
multResult.add(copyDigit);
}
} // end row for
StringBuilder appended = new StringBuilder();
for (int i=multResult.size()-1;i>=0;i--){
appended.append(multResult.get(i));
}
System.out.println("result is " + appended.toString());
BigInteger the_result1 = new BigInteger(appended.toString());
return the_result1;
}
Assume your partialResult dimensions are width and height you can add by the following two loops (see it here in action):
int digit = width + height - 1;
int carry = 0;
for (int d1 = width - 1; d1 >= 0; d1--) {
for (int r = 0; r < height && d1 + r < width; r++)
carry += partialResult[r][d1 + r];
result[--digit] = carry % 10;
carry /= 10;
}
for (int d2 = 1; d2 < height; d2++) {
for (int c = 0; c < width && d2 + c < height; c++)
carry += partialResult[d2 + c][c];
result[--digit] = carry % 10;
carry /= 10;
}
Note: Carry may be non-empty at the end meaning another digit before the first one in result.

Categories

Resources