Numerical error for a graph implementantion - java

I am working for a project for my university and i am getting always the same error message
java.lang.NullPointerException at
Assignment2.ColumnGen$SubProblem.createModel(ColumnGen.java:283)
The problem is in these lines
double M = 0;
for (int i=0; i<all_customers.size(); i++) {
for (int j=0; j<all_customers.size(); j++) {
double val = all_customers.get(i).time_to_node(all_customers.get(j)) + all_customers.get(i).time_at_node();
if (M<val) M=val;
}
}
When I delete these lines everything works perfectly but obviously I am not getting the best result as long as my algorithm, because i miss this parameter.
I know what is a null pointer exception but i tried everything and still i miss something.
My all other declarations for the things that you see in code are
public Map<Integer, Customer> all_customers = new HashMap<Integer, Customer>();
public double a() {
return ready_time;
}
public double b() {
return due_date;
}
public Node(int external_id, double x, double y, double t) {
this.id = all_nodes.size();
this.id_external = external_id;
this.xcoord = x;
this.ycoord = y;
this.t_at_node = t;
all_nodes.put(this.id, this);
}
public double time_to_node(Node node_to) {
return Math.round(Math.sqrt(Math.pow(this.xcoord - node_to.xcoord, 2) + Math.pow(this.ycoord - node_to.ycoord, 2)));
}
public double time_at_node() {
return t_at_node;
}
What i do wrong?

I think your exception comes from all_customers.get(i) , debug your code and make sure all the keys u request are in the map, or you can add a condition to check whether the map contains your key

Your problem is that one of your Map.get() operations returns a null. Obviously, one of the keys is missing from your map. You are not showing us how you populate your map, so the problem is not in the code that you are showing us.
Replace the following line of spaghetti code:
double val = all_customers.get(i).time_to_node(all_customers.get(j)) + all_customers.get(i).time_at_node();
with the following block of code:
Customer ci = all_customers.get(i);
assert ci != null : "Not found:" + i;
Customer cj = all_customers.get(j);
assert cj != null : "Not found:" + j;
double val = ci.time_to_node(cj) + ci.time_at_node();
and run your program passing the -enableassertions argument to the VM. (-ea for short.) This should give you a very good hint as to what is going wrong.

Related

Return multiple values separately from Netlogo extension

I am trying to return two values from an Netlogo extension separability. In the extension code below :
package distribution;
import java.util.Random;
import org.nlogo.api.*;
public class V2G extends DefaultReporter {
public Syntax getSyntax() {
return Syntax.reporterSyntax(new int[] {Syntax.ListType(), Syntax.NumberType(), Syntax.NumberType(), Syntax.NumberType(), Syntax.NumberType()}, Syntax.ListType());
}
public Object report(Argument args[], Context context) throws ExtensionException {
LogoList coalizao;
double gamma;
double amdc;
double op;
int constante;
double mep=0;
double sum = 0;
try {
coalizao = args[0].getList();
gamma = args[1].getDoubleValue();
amdc = args[2].getDoubleValue();
constante = args[3].getIntValue();
op = args[4].getDoubleValue();
}
catch(LogoException e) {
throw new ExtensionException( e.getMessage() ) ;
}
if (coalizao.size() < 2 || coalizao.size() > gamma) return 0;
for (int i = 0; i < coalizao.size(); i++) {
int agente = (int)((Double)coalizao.get(i)).doubleValue();
int min = 0;
int max = 30;
Random r = new Random(agente*constante);
mep += r.nextInt(max - min + 1) + min;
return mep;
}
sum = amdc + mep - op ;
return sum;
}
}
In the code above there are two values to be return mep and sum .
I am using the following code in Netlogo to import the values
to-report getCoalitionValue [coalition]
report distribution:V2G coalition gamma amdc constante op
end
Now, my problem is how can i import the values of mep and sum separately in Netlogo.
Please can anyone help me with this ?
Thanks in advance.
NetLogo doesn't really have a concept of returning multiple values from a primitive. The most NetLogo-ish way of accomplishing this is to return a list of values in a standard order.
Here is some Scala code to accomplish this. Users of this primitive in NetLogo would have to know to do item 0 sample-scala:two-values to get "apples" and item 1 sample-scala:two-values to get 0.
object TwoValues extends api.Reporter {
override def getSyntax = reporterSyntax(ret = ListType)
def report(args: Array[api.Argument], context: api.Context): AnyRef = {
import org.nlogo.api.ScalaConversions.toLogoList
Seq( "apples", 0 ).toLogoList // returns the NetLogo list ["apples", 0]
}
}
I see you're writing Java code, so a good reference for building a NetLogo list using a LogoListBuilder would be in the Java extension sample code:
public Object report(Argument args[], Context context)
throws ExtensionException {
// create a NetLogo list for the result
LogoListBuilder list = new LogoListBuilder();
int n;
// use typesafe helper method from
// org.nlogo.api.Argument to access argument
try {
n = args[0].getIntValue();
} catch (LogoException e) {
throw new ExtensionException(e.getMessage());
}
if (n < 0) {
// signals a NetLogo runtime error to the modeler
throw new ExtensionException
("input must be positive");
}
// populate the list
// note that we use Double objects; NetLogo numbers
// are always doubles
for (int i = 0; i < n; i++) {
list.add(Double.valueOf(i));
}
return list.toLogoList();
}

Problem with getting data to go into an array

So for this program, the mean and median are supposed to calculated and displayed but I do not think the data I am inputting is getting put into the array because it runs without error but does not display any data I have put into it.
public static double Mean(double[] gradeArray, int numGrades) {
double totalArray = 0.0;
double mean;
for (int i = 0; i < numGrades; i++) {
totalArray = gradeArray[i] + totalArray;
}
mean = totalArray / numGrades;
return mean;
}
public static double Median(double[] gradeArray, int numGrades) {
double median;
Arrays.sort(gradeArray, 0, numGrades);
if (numGrades % 2 == 0) {
median = ((gradeArray[(numGrades / 2)] + gradeArray[(numGrades / 2 + 1)]) / 2);
} else {
median = gradeArray[(numGrades / 2)];
}
return median;
}
private void Enter_Grades_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
double[] totalArray = new double[25];
String text_box_input_str = null;
double text_box_input_num = 0;
int numGrades = 0;
String num_grades_str;
DecimalFormat df = new DecimalFormat("#0.0##");
do {
try {
text_box_input_str = JOptionPane.showInputDialog(null, "Enter Item Price", "Enter Price", JOptionPane.PLAIN_MESSAGE);
if (text_box_input_str == null || text_box_input_str.isEmpty()) {
return;
}
if (text_box_input_num > 0) {
double[] gradeArray = null;
gradeArray[numGrades] = text_box_input_num;
numGrades++;
num_grades_str = Integer.toString(numGrades);
num_grades_text.setText(num_grades_str);
Mean_Text.setText(df.format(Mean(gradeArray, numGrades)));
Median_Text.setText(df.format(Median(gradeArray, numGrades)));
}
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught");
JOptionPane.showMessageDialog(null, "You Must Input numeric data!", "Bad Data!", JOptionPane.ERROR_MESSAGE);
}
} while (text_box_input_str != null && !text_box_input_str.isEmpty());
}
I expect the program to calculate the data that is inputted and calculate the mean and median and then display the totals
it looks like text_box_input_num is set to 0, never updated, but then there is an if check if it's > 0
Rather than pointing out the problem with your code directly, I'll give some pointers on how to find it yourself.
break your code down into smaller parts
for each part, write both the method and the tests that prove the method does what you expect
once the individual parts are working, write the method (and tests) that use them.
You'll end up with several methods with names like getValues, hasValue, printError, checkValidValue, showMedian etc. all of which do exactly what you want.
I guarantee that if you do that it'll become pretty clear very quickly what's wrong.

Neural Network Back Propagation XOR

Recently I've been brushing up on my machine learning, and as such decided to implement a basic neural network in Java using the back propagation algorithm. I've gone over the maths and checked against various other tutorials, but am still having problems. Apologies for the size of this post.
I'll first let you know the problems I have been testing on, before going into more detail about the algorithm.
Test problem 1:
A single output neuron with linear activation, learning regression of the function x/2 + 2. This works pretty well, but doesn't really use back propagation yet.
Algorithm works, and converges to near zero error (no pic, since I can't post more than 2 links).
Test problem 2:
My next test was to learn the XOR problem. For this, I tried a simple network with 2 input nodes, 2 hidden nodes and 2 output nodes (input nodes only provide the input and are not trained).
Algorithm always gets stuck on an average of 0.5 error
It doesn't matter how many epochs I run the algorithm for, all errors seem to converge to this point, and the network performs poorly.
Implementation
To implement the algorithm, I represent nodes as objects, and also have objects to represent activation functions.
public class LogisticActivationFunction implements ActivationFunction {
#Override
public double apply(double in) {
return 1.0 / (1.0 + Math.exp(-in));
}
#Override
public double applyDerivative(double in) {
double sig = apply(in);
return sig * (1.0 - sig);
}
}
First, the feed forward process is run like so:
public List<Double> evaluate(List<Double> inputs, boolean training) {
// Set the weights in the first layer.
setInputWeights(inputs);
// Iterate through non-input layers one by one and evaluate.
NodeLayer previousLayer = layers.get(0);
for (int layerIndex = 1; layerIndex < layers.size(); layerIndex++) {
NodeLayer layer = layers.get(layerIndex);
for (int nodeIndex = 0; nodeIndex < layer.size(); nodeIndex++) {
Node node = layer.get(nodeIndex);
evaluateNode(node, previousLayer, training);
}
previousLayer = layer;
}
return getOutputWeights();
}
private void evaluateNode(Node node, NodeLayer previousLayer, boolean training) {
double sum = node.getBias();
// Create sum from all connected nodes.
for (int link : node.links()) {
if (training) {
previousLayer.get(link).registerDownstreamNode(node.getId());
}
sum += node.getUpstreamLinkStrength(link) * previousLayer.get(link).getOutput();
}
// apply the activation function.
double activation = node.getActivation().apply(sum);
node.setHiddenNode(sum, activation);
}
Next, error values are propagated backwards across the network:
protected void backPropogate(List<Double> correct) {
//float error = norm(correct, getOutputWeights());
// Final layer error.
NodeLayer outputLayer = getOutputLayer();
List<Double> output = getOutputWeights();
for (int i = 0; i < outputLayer.size(); i++) {
// Calculate error on the ith output.
double error = correct.get(i) - output.get(i);
System.out.println("error " + i + " = " + error + " = " + correct.get(i) + " - " + output.get(i));
// Set the delta to the error in dimension i multiplied by the activation derivative of the input.
Node node = outputLayer.get(i);
node.setDelta(error * node.getActivation().applyDerivative(node.getInput()));
}
NodeLayer layer = outputLayer.getUpstream(this);
while (layer != getInputLayer()) {
for (Node node : layer) {
double sum = 0;
for (Node downstream : node.downstreamNodes(this, layer)) {
sum += downstream.getDelta() * downstream.getUpstreamLinkStrength(node.getId());
}
node.setDelta(sum * node.getActivation().applyDerivative(node.getInput()));
}
layer = layer.getUpstream(this);
}
}
Finally, weights are updated using gradient descent. Note, I'm using the negative error, so this works by adding the delta * learning rate * output.
private void updateParameters(double learningRate) {
for (NodeLayer layer : this) {
if (layer == getInputLayer()) {
continue;
}
for (Node node : layer) {
double oldBias = node.getBias();
node.offsetBias(node.getDelta() * learningRate);
for (Node upstream : node.upstreamNodes(this, layer)) {
double oldW = node.getUpstreamLinkStrength(upstream);
node.offsetWeight(upstream.getId(), learningRate * node.getDelta() * upstream.getOutput());
}
}
}
}
To tie these all together, I use the train method:
public void trainExample(List<Double> inputs, List<Double> correct, double learningRate) {
System.out.println("training example... " + Data.toString(inputs) + " -> " + Data.toString(correct));
evaluate(inputs, true);
backPropogate(correct);
updateParameters(learningRate);
}
And to do this for a training set I use the following logic:
public List<Double> train(NodeNetwork network, List<List<Double>> trainingInput, List<List<Double>> trainingLabels, double learningRate, int epochs, boolean verbose) {
List<Double> errorLog = new ArrayList<>();
for (int i = 0; i < epochs; i++) {
for (int j = 0; j < trainingInput.size(); j++) {
int example = random.nextInt(trainingInput.size());
network.trainExample(trainingInput.get(example), trainingLabels.get(example), learningRate);
}
if (verbose) {
double error = network.checkErrorSet(trainingInput, trainingLabels);
errorLog.add(error);
System.out.println(i + " " + error);
}
}
return errorLog;
}
Does anyone have any ideas on how I might go about getting this to work? I've spent the last day doing various checks, and seem to be getting no closer to an answer.
Code is viewable on my github (sami016) which I cannot link due to URL restrictions.
I'd really appreciate if anyone could point me in the right direction. Thanks for your help!

Conditionally concatenate strings in for-loop, or use predefined string

I have the following HashMap:
private HashMap<String, Team> allTeams = new HashMap<String, Team>();
I want to return as a String all teams in my league, otherwise return a message "no teams in league".
I have written this code:
public String getTeam()
{
String x = "";
for(Team tm : allTeams.values())
{
if(tm.getStatus().equals("Added"))
{
x = x + tm.toString();
}
else
{
x = "there are no teams in your league";
}
}
return temp;
}
If I remove the "else" part of the conditional statement the code works.
However if I keep the "else" part, I continuously receive "there are no teams in your league" and I understand it is because once all teams have been returned there will be no further teams to return hence the "else" part of the statement is always printed.
How can I get this to work?
One way would be to check if x is empty outside of the loop, and set it if it is.
public String getTeam()
{
String x = "";
for(Team tm : allTeams.values())
{
if(tm.getStatus().equals("Added"))
{
x = x + tm.toString();
}
}
if (x.isEmpty())
{
x = "there are no teams in your league";
}
return x;
}
I assumed you meant to return x, not temp, as temp isn't defined here.

Java - NullPoinerException Array of objects [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Can't figure this out, I've created a simple class of coordinates to hold x and y ints. In another class I have a global array of Coordinates declared called "ords". In my loop I'm adding Coordinates. When trying to use method getX() and getY() from the Coordinates class in my getaction method, I get a null pointer exception. I'm sure the objects are not null, but I still can't figure out whats going wrong. Any help appreciated.
import java.util.*;
import org.w2mind.net.*;
import java.io.Serializable;
public class ConorsMind implements Mind
{
int [][] surroundings = new int [12][16];
Coordinates [] ords = new Coordinates [192];
int currentX;
int currentY;
//====== Mind must respond to these methods: ==========================================================
// newrun(), endrun()
// getaction()
//======================================================================================================
public void newrun() throws RunError
{
}
public void endrun() throws RunError
{
}
private void formTwoDimmensional(int [] someArray)
{
int counter = 0;
int n=0;
for(int i = 0; i < 15; i++)
{
for(int z = 0; z < 12; z++)
{
surroundings[z][i] = someArray[counter];
if(surroundings[z][i] ==0) {
currentX=z;
currentY=i;
}
else if(surroundings[z][i]==4){
ords[n]= new Coordinates(z,i);
n++;
}
System.out.print(z+" , "+i+": "+surroundings[z][i]);
System.out.println();
counter++;
}
}
}
public Action getaction ( State state )
{
String s = state.toString();
String[] x = s.split(",");
int act =MinerWorldUpdated.NO_ACTIONS;
int counter = 0;
int [] surround = new int [192];
//in this way user will have ability to see what surrounds him
for(int i = 11; i < 203; i++)
{
surround[counter] = Integer.parseInt(x[i]);
counter++;
}
formTwoDimmensional(surround);
int [] response = new int [x.length];
for(int i = 0; i < x.length; i++)
{
response[i] = Integer.parseInt ( x[i] );
}
System.out.println("Current position: "+currentX+" ,"+currentY);
int coalX=ords[0].getX();
int coalY=ords[0].getY();
System.out.println("Coal position: "+coalX+" ,"+coalY);
if(coalX != 0 && coalY !=0)
{
if(coalX>currentX)
{
act=MinerWorldUpdated.ACTION_DOWN;
}
else if(coalY<currentY)
{
act=MinerWorldUpdated.ACTION_LEFT;
}
else if(coalX<currentX)
{
act=MinerWorldUpdated.ACTION_DOWN;
}
else if(coalY<currentY)
{
act=MinerWorldUpdated.ACTION_LEFT;
}
}
String a = String.format ( "%d", act );
return new Action ( a );
}
}
class Coordinates implements Serializable
{
private int x;
private int y;
public Coordinates(int x1, int y1)
{
x=x1;
y=y1;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
Error is as follows:
java.lang.NullPointerException
at ConorsMind.getaction(ConorsMind.java:146)
The error is stemming from the following two lines:
int coalX=ords[0].getX();
int coalY=ords[0].getY();
I am calling formTwoDimensional() and its working perfectly, the ords objects are being created successfully and are not null as testing with System.out.println(ords[n].getX()) is printing the expected result when placed in my else if(surroundings[z][i]==4) block.
You need to make sure that you're calling formTwoDimensional(). If you are indeed, then it's likely that you're not ever getting into your else if block in the nested for loop, and hence ords[0] is never actually being set, so when you try to access it, it's null.
The other thing to do, if you don't want to post the rest of your code, is to add some more debugging code. See below the boolean zero_pos_set. But make sure that you see the print "Zero pos set" before your program crashes. My bet is that you don't.
public class ConorsMind implements Mind
{
int [][] surroundings = new int [12][16];
Coordinates [] ords = new Coordinates [192];
boolean zero_pos_set = false;
private void formTwoDimmensional(int [] someArray)
{
int counter = 0;
int n=0;
for(int i = 0; i < 15; i++) {
for(int z = 0; z < 12; z++) {
surroundings[z][i] = someArray[counter];
if(surroundings[z][i] ==0) {
currentX=z;
currentY=i;
} else if(surroundings[z][i]==4) {
zero_pos_set = true;
ords[n]= new Coordinates(z,i);
n++;
}
counter++;
}
}
}
public Action getaction ( State state ) {
if(zero_pos_set) {
System.out.println("Zero pos set!");
}
int coalX=ords[0].getX();
int coalY=ords[0].getY();
System.out.println("Coal position: "+coalX+" ,"+coalY);
return new Action ( a );
}
}
Based on all of the debugging information posted within this thread, it seems that in your getaction() function, you're being passed some state, that doesn't contain 4.
When you parse this information and pass it to formTwoDimensional(), you will never reach the else if block, and so ords[0], or any other ords[n], will never be set.
As a result, when you try to access ords[0] back in your getaction() function, you actually get null, and hence your NullReferenceException.
It's an order of operations issue.
If you never make a call to formTwoDimmensional(), you'll never initialize anything inside of your array. Be sure you're calling that first.
The actual NPE happens when you attempt to call coalX=ords[0].getX();, which won't work if ords[0] is null.

Categories

Resources