Related
My grid
Im trying to implement Dijkstra algorithm for grid-like graph attached above to find shortest path from source node to every other node. Having watched many tutorials I fail to understand how I am supposed to define my starting node and graph.
As far as I understand grid doesnt change how algorithm/implementation works. In every tutorial I read/watched source is always "0". For example I read this: Javatpoint article. This is their input: Javapoint graph, Javatpoint Driver class.
So I wonder do the order of rows in input 'graph' matter? Does first row always have to be the row of source node?
This is my attempt at implementing driver class for my grid:
int grph[][] = new int[][] {
//S A B C D E F G H I J K
{ 0,-1,-1, 1,-1,-1, 1, 1,-1,-1, 2,-1 }, // S
{-1, 0, 1,-1,-1, 4,-1,-1,-1,-1,-1,-1 }, // A
{-1, 1, 0, 4,-1,-1, 9,-1,-1,-1,-1,-1 }, // B
{ 1,-1, 4, 0, 3,-1,-1,-1,-1,-1,-1,-1 }, // C
{-1,-1,-1, 3, 0,-1,-1, 8,-1,-1,-1,-1 }, // D
{-1, 4,-1,-1,-1, 0, 2,-1, 2,-1,-1,-1 }, // E
{ 1,-1, 9,-1,-1, 2, 0,-1,-1, 3,-1,-1 }, // F
{ 1,-1,-1,-1, 8,-1,-1, 0,-1,-1,-1, 6 }, // G
{-1,-1,-1,-1,-1, 2,-1,-1, 0, 1,-1,-1 }, // H
{-1,-1,-1,-1,-1,-1, 3,-1, 1, 0, 2,-1 }, // I
{ 2,-1,-1,-1,-1,-1,-1,-1,-1, 2, 0, 2 }, // J
{-1,-1,-1,-1,-1,-1,-1, 6,-1,-1, 2, 0 }, // K
};
DijkstraExample obj = new DijkstraExample();
obj.dijkstra(grph, 0);
}
Is my graph and source correct?
do the order of rows in input 'graph' matter?
No.
Does first row always have to be the row of source node?
No.
For instance, you could reorganise the order, so that "S" is ordered after "F":
int grph[][] = new int[][] {
//A B C D E F S G H I J K
{ 0, 1,-1,-1, 4,-1,-1,-1,-1,-1,-1,-1 }, // A
{ 1, 0, 4,-1,-1, 9,-1,-1,-1,-1,-1,-1 }, // B
{-1, 4, 0, 3,-1,-1, 1,-1,-1,-1,-1,-1 }, // C
{-1,-1, 3, 0,-1,-1,-1, 8,-1,-1,-1,-1 }, // D
{ 4,-1,-1,-1, 0, 2,-1,-1, 2,-1,-1,-1 }, // E
{-1, 9,-1,-1, 2, 0, 1,-1,-1, 3,-1,-1 }, // F
{-1,-1, 1,-1,-1, 1, 0, 1,-1,-1, 2,-1 }, // S
{-1,-1,-1, 8,-1,-1, 1, 0,-1,-1,-1, 6 }, // G
{-1,-1,-1,-1, 2,-1,-1,-1, 0, 1,-1,-1 }, // H
{-1,-1,-1,-1,-1, 3,-1,-1, 1, 0, 2,-1 }, // I
{-1,-1,-1,-1,-1,-1, 2,-1,-1, 2, 0, 2 }, // J
{-1,-1,-1,-1,-1,-1,-1, 6,-1,-1, 2, 0 }, // K
};
This involves moving both the S-row and S-column.
You would then call the solver with the appropriate index:
DijkstraExample obj = new DijkstraExample();
obj.dijkstra(grph, 6);
Is my graph and source correct?
The matrix and the main code (2 statements) are correct, but much depends on what your class does.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
How can I produce 5 x 7 dot matrix type digits for a clock project?
Here's an example of what I'm looking for.
I manually coded the position of each dot in each digit.
Is there a better way to create dot matrix digits?
By better I mean easier to code, easier to verify, makes use of existing fonts or other components, or anything else an experienced Swing developer might consider as an important consideration.
The rest of this question is the context for the naysayers that claim I didn't put enough effort into formulating my question.
Since I'm providing an answer to this question, I'm not posting fake bad code in the question. Sure, we appreciate it when people show their efforts. The code and text in my answer should supplement the question, in my opinion.
A few days ago, as I'm writing this, someone posted a question about making a clock with dot-matrix digits. The person posting the question provided code and a picture of what they had created. The person had created a BufferedImage where they had hardcoded the position of each square dot in his 4 x 7 dot matrix digits.
I was impressed with how much work the person had put into his BufferedImage, so I went off to my Eclipse to figure out how to generalize what he had done.
While I was away, people commented and closed his question. By the time I got back with my answer, the person had deleted his question.
Since I had what I thought was a good answer, I searched for an appropriate question. When I didn't find an appropriate question, I created a question.
Sure, I focused more on my answer than my question. Silly me, I thought that the answer would help provide context for the question.
Well, I hope that this explanation sheds some more light on why I thought this topic was important enough to create a question and ask for answers.
Unfortunately, you have to code the position of each dot in each digit.
However, you can do this in a flexible way.
Here's what I mean. A 5 x 7 dot matrix digit can be represented as a two-dimensional int array. It could also be represented as a boolean array, but a matrix of 0 and 1 values is easier to visually verify.
As an example. here's a method to code the zero digit. You can see that the ones create a visual outline that can be easily verified.
private int[][] defineZeroMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 1, 0, 0, 0, 1 };
matrix[3] = new int[] { 1, 0, 0, 0, 1 };
matrix[4] = new int[] { 1, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
It took me about 15 minutes to code all of the dot matrix digit matrices.
It's possible to code a dot matrix digit using a sparse matrix. Unfortunately, that idea leads to more code that's visually harder to verify.
Here's an example of the dot matrix digit two coded as a sparse matrix of coordinates.
private Point[] defineTwoCoordinates() {
Point[] array = new Point[14];
array[0] = new Point(0, 1);
array[1] = new Point(1, 0);
array[2] = new Point(2, 0);
array[3] = new Point(3, 0);
array[4] = new Point(4, 1);
array[5] = new Point(4, 2);
array[6] = new Point(3, 3);
array[7] = new Point(2, 4);
array[8] = new Point(1, 5);
array[9] = new Point(0, 6);
array[10] = new Point(1, 6);
array[11] = new Point(2, 6);
array[12] = new Point(3, 6);
array[13] = new Point(4, 6);
return array;
}
After we've coded all of the digit matrices, we'll create an array of matrices.
private int[][][] matrices;
The leftmost index is the digit, from 0 to 9. The second index is the row of the digit matrix. The third index is the column of the digit matrix.
Finally, we extend a JPanel and override the paintComponent method to actually paint the dot matrix digit.
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(dotColor);
for (int row = 0; row < matrices[digit].length; row++) {
for (int column = 0; column < matrices[digit][row].length; column++) {
if (matrices[digit][row][column] != 0) {
int x = margin + column * pixelWidth;
int y = margin + row * pixelWidth;
g.fillOval(x, y, dotWidth, dotWidth);
}
}
}
}
Here's a complete runnable example of how you would create a dot matrix digit panel by extending a JPanel, and use several dot matrix digit panels to create whatever GUI you want.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DotMatrixDigits implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new DotMatrixDigits());
}
#Override
public void run() {
JFrame frame = new JFrame("Dot Matrix Digits");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(defineTopPanel(), BorderLayout.BEFORE_FIRST_LINE);
frame.add(defineBottomPanel(), BorderLayout.AFTER_LAST_LINE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel defineTopPanel() {
JPanel panel = new JPanel();
panel.add(new DotMatrixDigit(0, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(1, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(2, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(3, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(4, Color.YELLOW, Color.BLACK));
return panel;
}
private JPanel defineBottomPanel() {
JPanel panel = new JPanel();
panel.add(new DotMatrixDigit(5, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(6, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(7, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(8, Color.YELLOW, Color.BLACK));
panel.add(new DotMatrixDigit(9, Color.YELLOW, Color.BLACK));
return panel;
}
/**
* <p>
* The <code>DotMatrixDigit</code> class creates a dot-matrix digit panel by
* extending <code>JPanel</code>. The dot matrix digit is 5 positions across and
* 7 positions down. The size of the dot and distance between dots are defined
* in the constructor of this class. The shape of the dot is determined in the
* <code>paintComponent</code> method.
* </p>
*
* #author Gilbert G. Le Blanc
* #version 1.8 - 20 October 2020
*
* #see JPanel
* #see Color
*/
public class DotMatrixDigit extends JPanel {
private static final long serialVersionUID = 1L;
/** int field to hold the digit to display **/
private int digit;
/** int field to hold the width of the dot in pixels **/
private int dotWidth;
/** int field to hold the distance between the
* top left corner of the dots in pixels **/
private int pixelWidth;
/** int field to hold the margin size in
* pixels surrounding the digit **/
private int margin;
private final Color dotColor;
private int[][][] matrices;
/**
* <p>
* This constructor creates a dot matrix digit panel. The preferred size of the
* panel is determined by the pixel width of each dot, including the space
* between the dots.
* </p>
*
* #param digit - The initial digit to display from 0 through 9.
* #param dotColor - The <code>Color</code> of the dots.
* #param backgroundColor - The background <code>Color</code> of the dot matrix
* digit panel.
*
*/
public DotMatrixDigit(int digit, Color dotColor, Color backgroundColor) {
this.digit = digit;
this.dotColor = dotColor;
this.dotWidth = 10;
this.pixelWidth = 15;
this.margin = dotWidth;
this.matrices = defineDigitMatricies();
int width = 4 * pixelWidth + dotWidth + margin + margin;
int height = 6 * pixelWidth + dotWidth + margin + margin;
this.setBackground(backgroundColor);
this.setPreferredSize(new Dimension(width, height));
}
private int[][][] defineDigitMatricies() {
int[][][] matrices = new int[10][][];
matrices[0] = defineZeroMatrix();
matrices[1] = defineOneMatrix();
matrices[2] = defineTwoMatrix();
matrices[3] = defineThreeMatrix();
matrices[4] = defineFourMatrix();
matrices[5] = defineFiveMatrix();
matrices[6] = defineSixMatrix();
matrices[7] = defineSevenMatrix();
matrices[8] = defineEightMatrix();
matrices[9] = defineNineMatrix();
return matrices;
}
private int[][] defineZeroMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 1, 0, 0, 0, 1 };
matrix[3] = new int[] { 1, 0, 0, 0, 1 };
matrix[4] = new int[] { 1, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
private int[][] defineOneMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 0, 1, 0, 0 };
matrix[1] = new int[] { 0, 1, 1, 0, 0 };
matrix[2] = new int[] { 1, 0, 1, 0, 0 };
matrix[3] = new int[] { 0, 0, 1, 0, 0 };
matrix[4] = new int[] { 0, 0, 1, 0, 0 };
matrix[5] = new int[] { 0, 0, 1, 0, 0 };
matrix[6] = new int[] { 1, 1, 1, 1, 1 };
return matrix;
}
private int[][] defineTwoMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 0, 0, 0, 0, 1 };
matrix[3] = new int[] { 0, 0, 0, 1, 0 };
matrix[4] = new int[] { 0, 0, 1, 0, 0 };
matrix[5] = new int[] { 0, 1, 0, 0, 0 };
matrix[6] = new int[] { 1, 1, 1, 1, 1 };
return matrix;
}
private int[][] defineThreeMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 0, 0, 0, 0, 1 };
matrix[3] = new int[] { 0, 0, 1, 1, 0 };
matrix[4] = new int[] { 0, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
private int[][] defineFourMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 0, 0, 1, 0 };
matrix[1] = new int[] { 0, 0, 1, 1, 0 };
matrix[2] = new int[] { 0, 1, 0, 1, 0 };
matrix[3] = new int[] { 1, 0, 0, 1, 0 };
matrix[4] = new int[] { 1, 1, 1, 1, 1 };
matrix[5] = new int[] { 0, 0, 0, 1, 0 };
matrix[6] = new int[] { 0, 0, 0, 1, 0 };
return matrix;
}
private int[][] defineFiveMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 1, 1, 1, 1, 1 };
matrix[1] = new int[] { 1, 0, 0, 0, 0 };
matrix[2] = new int[] { 1, 0, 0, 0, 0 };
matrix[3] = new int[] { 1, 1, 1, 1, 0 };
matrix[4] = new int[] { 0, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
private int[][] defineSixMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 1, 0, 0, 0, 0 };
matrix[3] = new int[] { 1, 1, 1, 1, 0 };
matrix[4] = new int[] { 1, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
private int[][] defineSevenMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 1, 1, 1, 1, 1 };
matrix[1] = new int[] { 0, 0, 0, 0, 1 };
matrix[2] = new int[] { 0, 0, 0, 0, 1 };
matrix[3] = new int[] { 0, 0, 0, 1, 0 };
matrix[4] = new int[] { 0, 0, 1, 0, 0 };
matrix[5] = new int[] { 0, 0, 1, 0, 0 };
matrix[6] = new int[] { 0, 0, 1, 0, 0 };
return matrix;
}
private int[][] defineEightMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 1, 0, 0, 0, 1 };
matrix[3] = new int[] { 0, 1, 1, 1, 0 };
matrix[4] = new int[] { 1, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
private int[][] defineNineMatrix() {
int[][] matrix = new int[7][];
matrix[0] = new int[] { 0, 1, 1, 1, 0 };
matrix[1] = new int[] { 1, 0, 0, 0, 1 };
matrix[2] = new int[] { 1, 0, 0, 0, 1 };
matrix[3] = new int[] { 0, 1, 1, 1, 1 };
matrix[4] = new int[] { 0, 0, 0, 0, 1 };
matrix[5] = new int[] { 1, 0, 0, 0, 1 };
matrix[6] = new int[] { 0, 1, 1, 1, 0 };
return matrix;
}
/**
* <p>
* The <code>setDigit</code> method sets the digit to display and repaints the
* panel.
* </p>
*
* #param digit - A digit from 0 through 9.
*/
public void setDigit(int digit) {
this.digit = digit;
this.repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(dotColor);
for (int row = 0; row < matrices[digit].length; row++) {
for (int column = 0; column < matrices[digit][row].length; column++) {
if (matrices[digit][row][column] != 0) {
int x = margin + column * pixelWidth;
int y = margin + row * pixelWidth;
g.fillOval(x, y, dotWidth, dotWidth);
}
}
}
}
}
}
Is there a better way to create dot matrix digits?
Don't know if 'better' (depends on whether effort or accuracy is the primary consideration) but there is a way to calculate the array based on the Shape of the digit.
Here is the result for a (bold) version of the default Monospaced font on this machine.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.font.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class FontToDotMatrix {
private JComponent ui = null;
Shape[] shapes = new Shape[10];
JComboBox fonts;
PixelArray[] pixelArrays = new PixelArray[10];
FontToDotMatrix() {
initUI();
}
public final void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
String[] fontFamilies = GraphicsEnvironment.
getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
fonts = new JComboBox(fontFamilies);
ui.add(fonts, BorderLayout.PAGE_START);
JPanel digitPanel = new JPanel(new GridLayout(2, 5, 4, 4));
ui.add(digitPanel);
digitPanel.setBackground(Color.RED);
for (int ii = 0; ii < 10; ii++) {
PixelArray pixelArray = new PixelArray();
pixelArrays[ii] = pixelArray;
digitPanel.add(pixelArray);
}
ActionListener listener = (ActionEvent e) -> {
for (int ii = 0; ii < 10; ii++) {
pixelArrays[ii].updatePixels(getLitPixels("" + ii));
}
};
fonts.addActionListener(listener);
fonts.setSelectedItem("Monospaced");
}
private Shape moveShapeToCenter(Shape shape) {
int w = 50;
int h = 70;
Rectangle2D b = shape.getBounds2D();
double xOff = -b.getX() + ((w - b.getWidth()) / 2d);
double yOff = -b.getY() + ((h - b.getHeight()) / 2d);
AffineTransform move = AffineTransform.getTranslateInstance(xOff, yOff);
return move.createTransformedShape(shape);
}
private boolean[][] getLitPixels(String digit) {
Font font = new Font(fonts.getSelectedItem().toString(), Font.BOLD, 70);
Shape shape = getShapeOfCharacter(font, digit);
Rectangle2D rect = shape.getBounds2D();
double h = rect.getHeight();
double ratio = 70d / h;
AffineTransform scale = AffineTransform.getScaleInstance(ratio, ratio);
shape = moveShapeToCenter(scale.createTransformedShape(shape));
boolean[][] bools = new boolean[5][7];
for (int yy = 0; yy < 7; yy++) {
for (int xx = 0; xx < 5; xx++) {
Point point = new Point((xx * 10) + 5, (yy * 10) + 5);
bools[xx][yy] = shape.contains(point);
}
}
return bools;
}
public JComponent getUI() {
return ui;
}
private Shape getShapeOfCharacter(Font font, String digit) {
BufferedImage bi = new BufferedImage(
1, 1, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
FontRenderContext frc = g.getFontRenderContext();
GlyphVector gv = font.createGlyphVector(frc, digit);
return gv.getOutline();
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
FontToDotMatrix o = new FontToDotMatrix();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
class PixelArray extends JPanel {
JLabel[][] labels = new JLabel[5][7];
PixelArray() {
setLayout(new GridLayout(7, 5));
BufferedImage bi = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
ImageIcon icon = new ImageIcon(bi);
for (int yy = 0; yy < labels[0].length; yy++) {
for (int xx = 0; xx < labels.length; xx++) {
JLabel l = new JLabel(icon);
labels[xx][yy] = l;
l.setOpaque(true);
add(l);
}
}
}
public void updatePixels(boolean[][] bools) {
for (int xx = 0; xx < labels.length; xx++) {
for (int yy = 0; yy < labels[0].length; yy++) {
JLabel l = labels[xx][yy];
if (bools[xx][yy]) {
l.setBackground(Color.WHITE);
} else {
l.setBackground(Color.BLACK);
}
}
}
}
}
I need to find the best fitting regression line for a set of points.
For example for this matrix:
int b [][] = { { 3, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 2, 3, 1, 0, 1, 0, 0, 0 },
{ 0, 1, 2, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 3, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 3, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 2, 3, 1 },
{ 0, 0, 0, 0, 0, 1, 1, 1, 2 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 1 } };
Every number represents the amount of data points (weight I suppose) at that location (where rows are the X axis and Columns are for the Y).
I have attempted to use the SimpleRegression class from the apache mathematics library and am having some issues.
First, it doesn't appear to support weights. Second I believe that I'm doing something wrong, even for a matrix that is nothing but 1's on the main diagonal the slope/intercept results make no sense.
public static void main(String[] args) {
double a[][] = new double[9][9];
for (int i = 0; i < 9; i++)
a[i][i] = 1;
SimpleRegression r = new SimpleRegression(true);
r.addData(a);
System.out.println("Slope = " + r.getSlope());
System.out.println("Intercept = " + r.getIntercept());
}
This gives me results that are incorrect. I would assume that this matrix represents the function f(x) = x yet the slope I'm getting is -0.12499..
Could anyone point me at what I'm doing wrong?
I have a feeling I'm not only misusing the code but also the mathematics.
As the comments say, addData() expects a 2xN matrix of x y positions or individual x y positions. The following example returns a slope of 1 for a diagonal matrix as expected:
public static void main(String[] args) {
double a[][] = new double[9][9];
for (int i = 0; i < 9; i++)
a[i][i] = 1;
SimpleRegression r = new SimpleRegression(true);
addData(r, a);
System.out.println("Slope = " + r.getSlope());
System.out.println("Intercept = " + r.getIntercept());
}
public static void addData(SimpleRegression r, double[][] data) {
for(int x=0; x<data.length; x++) {
for(int y=0; y<data[0].length; y++) {
for(int i=0; i<data[x][y]; i++) {
r.addData(x, y);
}
}
}
}
The example assumes that index 0 corresponds to a position of 0, index 1 corresponds to a position of 1 and so on. If this is not the case you need to add a function to transform index to position.
I have a problem when build an elman recurrent neural network using encog 3.0 library. I got NaN error after few iteration.
This is my code in MATLAB :
net=newlrn (minmax(usdjpytrain),[4,1], {'logsig', 'purelin'}, 'trainscg', 'learngdm', 'mse');
net.trainParam.epochs = 1000;
net.trainParam.goal = 1e-5;
I wanna to create recurrent neural network like above in java. by default, a learning rate value in MATLAB is 0.01 and momentum is 0.9. but I got NaN error if I use learning rate and momentum like that. this is my code in java :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package modifikasiJSR;
import org.encog.Encog;
import org.encog.engine.network.activation.ActivationSigmoid;
import org.encog.ml.data.MLDataSet;
import org.encog.ml.data.basic.BasicMLDataSet;
import org.encog.ml.train.MLTrain;
import org.encog.neural.networks.BasicNetwork;
import org.encog.neural.networks.training.CalculateScore;
import org.encog.neural.networks.training.TrainingSetScore;
import org.encog.neural.networks.training.propagation.back.Backpropagation;
import org.encog.neural.pattern.ElmanPattern;
import dataSet.DataDefault;
import database.Parameter;
import org.encog.ml.data.MLData;
import org.encog.ml.data.MLDataPair;
import org.encog.ml.train.strategy.HybridStrategy;
import org.encog.neural.networks.structure.AnalyzeNetwork;
import org.encog.neural.networks.training.propagation.scg.ScaledConjugateGradient;
/**
*
* #author Akmal
*/
public class MseTrain{
private String mataUang;
private int jumlahDataSet;
Parameter param = new Parameter();
private double [] bias_hid_out = new double[2];
private double [] bias_hid_in = new double[param.getHidden_node()];
private double [] bobot_hid_out = new double[param.getHidden_node()];
private double [] bobot_hid_in = new double[7*param.getHidden_node()];
public MseTrain(String mataUang){
this.mataUang = mataUang;
}
static BasicNetwork createElmanNetwork() {
// construct an Elman type network
Parameter param = new Parameter();
ElmanPattern pattern = new ElmanPattern();
pattern.setActivationFunction(new ActivationSigmoid());
pattern.setInputNeurons(7);
pattern.addHiddenLayer(param.getHidden_node());
pattern.setOutputNeurons(1);
return (BasicNetwork)pattern.generate();
}
public void mse(double[][] data, double [][] target) {
System.out.println("menjalankan method MSE");
DataDefault dataSet = new DataDefault(mataUang);
jumlahDataSet = dataSet.getJumTraining();
final MLDataSet trainingSet = new BasicMLDataSet(data, target);
final BasicNetwork elmanNetwork = MseTrain.createElmanNetwork();
final double elmanError = trainNetwork("Elman", elmanNetwork,trainingSet);
System.out.println("Best error rate with Elman Network: " + elmanError);
Encog.getInstance().shutdown();
}
private double trainNetwork(final String what,final BasicNetwork network, final MLDataSet trainingSet) {
network.reset();
// train the neural network
System.out.println(network.getActivation(0));
System.out.println(network.getActivation(1));
System.out.println(network.getActivation(2));
CalculateScore score = new TrainingSetScore(trainingSet);
final MLTrain trainMain = new Backpropagation(network, trainingSet, 0.01, 0.9);
final MLTrain trainAlt = new ScaledConjugateGradient(network, trainingSet);
trainMain.addStrategy(new HybridStrategy(trainAlt));
//set Bobot hid In
network.setWeight(0, 0, 0, 3.0439);
network.setWeight(0, 0, 1, 2.8421);
network.setWeight(0, 0, 2, -2.8529);
network.setWeight(0, 0, 3, 2.7013);
network.setWeight(0, 1, 0, 1.2741);
network.setWeight(0, 1, 1, -2.8055);
network.setWeight(0, 1, 2, -1.6862);
network.setWeight(0, 1, 3, 0.3049);
network.setWeight(0, 2, 0, 4.5054);
network.setWeight(0, 2, 1, 3.3152);
network.setWeight(0, 2, 2, -2.6663);
network.setWeight(0, 2, 3, 3.1311);
network.setWeight(0, 3, 0, 4.4113);
network.setWeight(0, 3, 1, -0.1022);
network.setWeight(0, 3, 2, 2.2913);
network.setWeight(0, 3, 3, -2.3347);
network.setWeight(0, 4, 0, -1.2521);
network.setWeight(0, 4, 1, 4.8178);
network.setWeight(0, 4, 2, 3.6979);
network.setWeight(0, 4, 3, 4.9682);
network.setWeight(0, 5, 0, 1.4512);
network.setWeight(0, 5, 1, -3.1329);
network.setWeight(0, 5, 2, 2.5726);
network.setWeight(0, 5, 3, 2.7323);
network.setWeight(0, 6, 0, 2.3088);
network.setWeight(0, 6, 1, 2.4109);
network.setWeight(0, 6, 2, 2.4835);
network.setWeight(0, 6, 3, -0.9406);
//set Bias hid In
network.setWeight(0, 7, 0, -9.3723);
network.setWeight(0, 7, 1, -2.1356);
network.setWeight(0, 7, 2, -5.0966);
network.setWeight(0, 7, 3, -1.5829);
//set Bobot Hid out
network.setWeight(1, 0, 0, -0.6263);
network.setWeight(1, 1, 0, -0.0205);
network.setWeight(1, 2, 0, -0.1088);
network.setWeight(1, 3, 0, 0.2926);
//set Bias Hid out
network.setWeight(1, 4, 0, 0.4187);
int epoch = 0;
do{
trainMain.iteration();
System.out.println("Training " + what + ", Epoch #" + epoch + " Error:" + trainMain.getError());
System.out.println("Error:" + trainMain.getError());
epoch++;
}while(trainMain.getError()>0.00001&&epoch<=1);
System.out.println("Neural Network Results:");
for(MLDataPair pair: trainingSet ) {
final MLData output = network.compute(pair.getInput());
System.out.println(
pair.getInput().getData(0)
+ ","
+ pair.getInput().getData(1)
+ ","
+ pair.getInput().getData(2)
+ ","
+ pair.getInput().getData(3)
+ ","
+ pair.getInput().getData(4)
+ ","
+ pair.getInput().getData(5)
+ ","
+ pair.getInput().getData(6)
+ ", actual="
+ output.getData(0)
+ ",ideal="
+ pair.getIdeal().getData(0));
}
System.out.println("bobot : "+network.dumpWeights());
AnalyzeNetwork bobotBias = new AnalyzeNetwork(network);
int jumBobotIn = param.getHidden_node()*7;
System.out.println("jumBobotIn : "+jumBobotIn);
int indexBobotIn = 0;
int indexBobotOut = 0;
for(int i=0; i<bobotBias.getWeightValues().length; i++){
System.out.println("bobot : "+bobotBias.getWeightValues()[i]);
if(i<jumBobotIn){
bobot_hid_in[indexBobotIn] = bobotBias.getWeightValues()[i];
indexBobotIn++;
}
else{
bobot_hid_out[indexBobotOut] = bobotBias.getWeightValues()[i];
indexBobotOut++;
}
}
int indexBiasIn = 0;
int indexBiasOut = 0;
int jumBiasIn = param.getHidden_node();
for(int i=0; i<bobotBias.getBiasValues().length; i++){
System.out.println("bias : "+bobotBias.getBiasValues()[i]);
if(i<jumBiasIn){
bias_hid_in[indexBiasIn] = bobotBias.getBiasValues()[i];
indexBiasIn++;
}
else{
bias_hid_out[indexBiasOut] = bobotBias.getBiasValues()[i];
indexBiasOut++;
}
}
return trainMain.getError();
}
/**
* #return the bias_hid_out
*/
public double[] getBias_hid_out() {
return bias_hid_out;
}
/**
* #return the bias_hid_in
*/
public double[] getBias_hid_in() {
return bias_hid_in;
}
/**
* #return the bobot_hid_out
*/
public double[] getBobot_hid_out() {
return bobot_hid_out;
}
/**
* #return the bobot_hid_in
*/
public double[] getBobot_hid_in() {
return bobot_hid_in;
}
}
everyone please help me, I got stuck here for several days. T.T
I am developing a steganography program for a computer programming class. It appears to gives random ascii symbols. The output is supposed to be BINARY. The encode message method was given to us by my teacher. We just have to program the decode part.
import java.awt.*;
class HideMessage {
public void encodeMessage(Picture stegoObject, int[] binaryArray) {
Pixel pixelTarget = new Pixel(stegoObject, 0, 0);
Pixel[] pixelArray = stegoObject.getPixels();
Color pixelColor = null;
int redValue = 0;
for (int x = 0; x < binaryArray.length; x++) {
redValue = binaryArray[x];
pixelTarget = pixelArray[x];
pixelTarget.setRed(redValue);
}
pixelTarget = pixelArray[binaryArray.length];
pixelTarget.setRed(255);
System.out.println("FinishedPic");
stegoObject.write("SecretMessage.bmp");
stegoObject.explore();
}
public void decodeMessage(Picture decodepic) {
int redValue = 0;
Pixel targetPixel = null;
Color pixelColor = null;
int sum = 0;
for (int x = 0; redValue < 2; x++) {
//inside nested loop to traverse the image from left to right
for (int count = 1; count < 9; count++) {
targetPixel =
decodepic.getPixel(count + (8 * x), 0);
//gets the x,y coordinate of the target pixel
pixelColor = targetPixel.getColor();
//gets the color of the target pixel
redValue = pixelColor.getRed();
if (redValue == 1) {
if (count == 1) {
sum = sum + 128;
}
if (count == 2) {
sum = sum + 64;
}
if (count == 3) {
sum = sum + 32;
}
if (count == 4) {
sum = sum + 16;
}
if (count == 5) {
sum = sum + 8;
}
if (count == 6) {
sum = sum + 4;
}
if (count == 7) {
sum = sum + 2;
}
if (count == 8) {
sum = sum + 1;
}
}
System.out.println(sum);
}
System.out.println((char)sum);
sum = 0;
} //end of the inner for loop
}
}
public class HideMessageTester {
public static void main(String[] args) {
int[] bitArray =
{ 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,
0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0,
1, 1, 1, 1, 0, 0, 1 };
//int[] bitArray =
{ 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,
0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1,
1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1,
0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1,
0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1,
0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1,
0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1,
1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0,
0, 1, 0, 0, 0, 0, 1};
Picture stegoObject = new Picture("Earth.bmp");
HideMessage stego = new HideMessage();
stego.encodeMessage(stegoObject, bitArray);
Picture decodeObject = new Picture("SecretMessage.bmp");
System.out.println("Now Decoding");
stego.decodeMessage(decodeObject);
}
}
First, some general pieces of advice: I think your program is overly complicated because the functions are commingling their responsibilities:
Picture stegoObject = new Picture("Earth.bmp");
HideMessage stego = new HideMessage();
stego.encodeMessage(stegoObject, bitArray);
Picture decodeObject = new Picture("SecretMessage.bmp");
System.out.println("Now Decoding");
stego.decodeMessage(decodeObject);
I was very surprised to see SecretMessage.bmp; it wasn't at all obvious that were trying to decode the object you had just created. Sure, upon reading the encodeMessage() method it was easy enough to determine where it came from, but I think this flow would have been easier:
/* encode */
Picture pic_to_steg = new Picture("foo.bmp");
HideMessage stego = new HideMessage();
Picture secret = stego.encodeMessage(pic_to_steg, bitArray);
secret.write("SecretMessage.bmp");
/* decode */
Picture pic_with_message = new Picture("SecretMessage.bmp");
int[] hidden = stego.decodeMessage(pic_with_message);
/* output `hidden` and compare against `bitArray` */
In other words: leave the file IO entirely up to the main flow of the program. Perhaps your routines will be called from a network server in the future, and the pictures will never be saved to disk. That modification will be far easier if the routines operate on Pictures and return amended Pictures and int[].
Can you test your encodeMessage() method in isolation? Perhaps look at the differences in what it does between an input file and an output file. This section looks troublesome:
public void encodeMessage(Picture stegoObject, int[] binaryArray) {
Pixel pixelTarget = new Pixel(stegoObject, 0, 0);
Pixel[] pixelArray = stegoObject.getPixels();
Color pixelColor = null;
int redValue = 0;
for (int x = 0; x < binaryArray.length; x++) {
redValue = binaryArray[x];
pixelTarget = pixelArray[x];
pixelTarget.setRed(redValue);
}
pixelTarget = pixelArray[binaryArray.length];
pixelTarget.setRed(255);
Is the pixelArray really a reference into the image that can be updated through simple assignment? I'd really expect the design to look more like this pseudo-code:
pixel p = image.getPixel(x, y);
p.setred(binaryArray[i]);
image.setPixel(x, y, p);
The decoding has some strange loops:
for (int x = 0; redValue < 2; x++) {
//inside nested loop to traverse the image from left to right
for (int count = 1; count < 9; count++) {
This loop might work exactly as you designed it, but upon a first reading, it feels very wrong: You start with x=0, you increment x each time through the loop, but you use redValue < 2 as your loop termination rule.
I would so much rather see the loop written like this:
int x = 0;
while (redValue < 2) {
/* stuff */
x++;
}
(It isn't identical; x is still valid outside the loop, which can be dangerous. However, I think this is much more clear.)
There are cases where the termination clause of a for loop isn't related to the setup or increment clauses -- in my experience, they are very rare.
In this case though, it feels like a mistake; the condition redValue < 2 a loop invariant, but the inner loop assumes it will only happen on pixels that are multiples of 8, which is an assumption that is not enforced in the encodeMessage() method.
Trying to compute an integer value from your redValues as you read them is needlessly complicating your decode routine. I suggest removing the inner loop and return an array exactly like the array passed into the encodeMessage() routine. This will be (a) easier (b) easier to debug (c) easier to test (d) a thousand times easier to handle writing bit arrays that aren't evenly divisible by 8.
Then write a second method that turns the bit array output into the sum, or ASCII characters, or EBCDIC characters, or RSA key parameters, or whatever it is that's being encoded. Don't try to do too much at once. Writing a separate method to decode the array of bits will be (a) easier (b) easier to debug (c) easier to test (d) thousand time easier to handle arbitrary output modifications.
I hope these hints help.