CPLEX warm start error when using OPL model in Java API - java

I am trying to do a warm start using the Java API and having some issues when passing the initial solution to the model.
In my model file(.mod) I have a 2D decision variable defined as,
range nodes = 1..5;
range vehicles = 1..2;
dvar int service_time[nodes][vehicles];
In my java file I am building the model as below and trying to pass an initial solution to the above decision variable using the addMipStart() function (as described here),
static public void main(String[] args) throws Exception {
int status = 127;
try {
IloOplFactory.setDebugMode(true);
IloOplFactory oplF = new IloOplFactory();
IloOplErrorHandler errHandler = oplF.createOplErrorHandler(System.out);
IloOplModelSource modelSource = oplF.createOplModelSource(DATADIR + "/myModFile.mod");
IloOplSettings settings = oplF.createOplSettings(errHandler);
IloOplModelDefinition def = oplF.createOplModelDefinition(modelSource, settings);
IloCplex cplex = oplF.createCplex();
IloOplModel opl = oplF.createOplModel(def, cplex);
//adding the custom data source
IloOplDataSource dataSource = new VRPDataSource(oplF);
opl.addDataSource(dataSource);
//generating the model
opl.generate();
//creating the initial solution
int i = 5;
int j = 2;
IloIntVar[][] var2D = new IloIntVar[i][];
double[][] var2D_startingVals = new double[i][];
for(int index1=0; index1 < i; index1++){
var2D[index1] = new IloIntVar[j];
var2D_startingVals[index1] = new double[j];
for(int index2 = 0; index2 < j; index2++){
String varName = "service_time("+ (index1+1) +")("+ (index2+1) +")";
var2D[index1][index2] = cplex.intVar(0, 50, varName);
//lets assume a unit matrix as the starting solution
var2D_startingVals[index1][index2] = 1;
}
}
//flatten the multi-dimensional IloNumVar and double arrays
IloNumVar[] flat_var2D = new IloNumVar[i*j];
double[] flat_var2D_startingVals = new double[i*j];
for(int index1=0; index1 < i; index1++){
for(int index2=0; index2 < j; index2++){
flat_var2D[index1*j + index2] = var2D[index1][index2];
flat_var2D_startingVals[index1*j + index2] = var2D_startingVals[index1][index2];
}
}
// adding the MIPStart
cplex.addMIPStart(flat_var2D, flat_var2D_startingVals, IloCplex.MIPStartEffort.Auto, "addMIPStart start");
if(cplex.solve()){
// more code
}else{
// more code
}
// more code
}catch(Exception ex){
// more code
}
}
Unfortunately I am having an exception in the line which calls the cplex.addMIPStart() function as,
[java] ### CONCERT exception: The referenced IloExtractable has not been extracted by the IloAlgorithm
[java] ilog.concert.IloException: The referenced IloExtractable has not been extracted by the IloAlgorithm
[java] at ilog.cplex.cppimpl.cplex_wrapJNI.IloCplex_addMIPStart__SWIG_0(Native Method)
[java] at ilog.cplex.cppimpl.IloCplex.addMIPStart(IloCplex.java:866)
[java] at ilog.cplex.IloCplex.addMIPStart(IloCplex.java:13219)
[java] at ilog.cplex.IloCplex.addMIPStart(IloCplex.java:13228)
[java] at myJavaClass.myJavaClass.main(myJavaClass.java:412)
I am thinking the error is due to the way I prepare the initial solution, can somebody please help me to sort this out.
Thank you very much.

The problem is that you're creating new variables, not referencing the existing variables in the model. These new variables do not exist in the objective, constraints, etc., so you get the IloException (see this technote).
You should be able to access the existing variables doing something like the following (note that this code has not been tested):
IloIntRange nodes = opl.getElement("nodes").asIntRange();
IloIntRange vehicles = opl.getElement("vehicles").asIntRange();
IloIntVarMap serviceTime = opl.getElement("service_time").asIntVarMap();
final int nbNodes = nodes.getSize();
final int nbVehicles = vehicles.getSize();
IloNumVar[] startX = new IloNumVar[nbNodes * nbVehicles];
double[] startVals = new double[nbNodes * nbVehicles];
for (int i = 0; i < nbNodes; i++) {
IloIntVarMap inner = serviceTime.getSub(nodes.getValue(i));
for (int j = 0; j < nbVehicles; j++) {
int idx = i * nbVehicles + j;
startX[idx] = inner.get(vehicles.getValue(j));
startVals[idx] = 1.0;
}
}
cplex.addMIPStart(startX, startVals);
Take a look at the Iterators.java example and the documentation for getElement.

Related

Processing - Array index out of bounds error

I'm trying to use an array of objects to have barrels fall from the top of the screen to the bottom. (Like that old donkey kong game.) However, I can't seem to find a way to create more instances of the object than whatever the initial length of the array was. Anyone know a way to do this?
Here's the code:
Man Man;
Man background;
Man ladders;
PFont font1;
int time;
boolean run;
boolean newBarrel;
int barrelTotal;
Barrel[] barrel = new Barrel[100];
void setup() {
newBarrel = false;
run = true;
barrelTotal = 1;
time = millis();
size(800, 800);
Man = new Man();
background = new Man();
ladders = new Man();
for (int i = 0; i < barrel.length; i++) {
barrel[i] = new Barrel();
}
}
void draw() {
if (run == true) {
for (int i = 0; i < barrel.length; i++) {
if ((Man.bottom-10 >= barrel[i].top)&&(Man.bottom-10 <= barrel[i].bottom)&&(Man.Ladder == barrel[i].randomLadder)) {
print("GAME OVER!");
run = false;
}
if ((Man.top >= barrel[i].top)&&(Man.top <= barrel[i].bottom)&&(Man.Ladder == barrel[i].randomLadder)) {
print("GAME OVER!");
run = false;
}
}
}
if (run == true) {
background.createBackground();
Man.ladders();
Man.movement();
Man.createMan();
//spawns a barrel every second
if (millis()> time + 10) {
newBarrel = false;
print(" " + barrelTotal + " ");
time = time + 10;
barrelTotal = barrelTotal+1;
newBarrel = true;
}
for (int i = 0; i < barrelTotal; i++) {
if (newBarrel == true) {
}
barrel[i].gravity();
barrel[i].createBarrel();
}
//if(barrelTotal == 100){
//for (int i = 0; i < 50; i++){
// barrel[i] = "???";
//}
//}
}
}
Use an ArrayList instead of a native array. ArrayList will expand capacity as needed, whereas an array is fixed size and cannot be changed (you'd need to create a new larger array each time, which under the covers is what an ArrayList handles for you).
You can use ArrayList for this. You will change
// from
Barrel[] barrel = new Barrel[100]; // i suggest naming it to barrels instead of barrel
// to
ArrayList<Barrel> barrel = new ArrayList<>();
// or better
List<Barrel> barrel = new ArrayList<>();
// from
for (int i = 0; i < barrel.length; i++) {
barrel[i] = new Barrel();
}
// to
for (int i = 0; i < barrel.length; i++) {
barrel.add(new Barrel());
}
// from
barrel[i].<some-method()/attribute>
// to
barrel.get(i).<some-method()/attribute>
// etc
I highly recommend this for getting started with lists
https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html

How to use the saved neural network.ser in Android studio

I've trained a neural network in NetBeans and saved it as neural_network.ser by using Serializable ,"all classes implement Serializable" , Now I want to use it in my android application but when loading the network ,ClassNotFoundException raised .
java.lang.ClassNotFoundException: neural_network.BackPropagation
Here is the Classes:
BackPropagation class:
public class BackPropagation extends Thread implements Serializable
{
private static final String TAG = "NetworkMessage";
private static final long serialVersionUID = -8862858027413741101L;
private double OverallError;
// The minimum Error Function defined by the user
private double MinimumError;
// The user-defined expected output pattern for a set of samples
private double ExpectedOutput[][];
// The user-defined input pattern for a set of samples
private double Input[][];
// User defined learning rate - used for updating the network weights
private double LearningRate;
// Users defined momentum - used for updating the network weights
private double Momentum;
// Number of layers in the network
private int NumberOfLayers;
// Number of training sets
private int NumberOfSamples;
// Current training set/sample that is used to train network
private int SampleNumber;
// Maximum number of Epochs before the traing stops training
private long MaximumNumberOfIterations;
// Public Variables
public LAYER Layer[];
public double ActualOutput[][];
long delay = 0;
boolean die = false;
// Calculate the node activations
public void FeedForward()
{
int i,j;
// Since no weights contribute to the output
// vector from the input layer,
// assign the input vector from the input layer
// to all the node in the first hidden layer
for (i = 0; i < Layer[0].Node.length; i++)
Layer[0].Node[i].Output = Layer[0].Input[i];
Layer[1].Input = Layer[0].Input;
for (i = 1; i < NumberOfLayers; i++)
{
Layer[i].FeedForward();
// Unless we have reached the last layer, assign the layer i's //output vector
// to the (i+1) layer's input vector
if (i != NumberOfLayers-1)
Layer[i+1].Input = Layer[i].OutputVector();
}
}
// FeedForward()
// Back propagated the network outputy error through
// the network to update the weight values
public void UpdateWeights()
{
CalculateSignalErrors();
BackPropagateError();
}
private void CalculateSignalErrors()
{
int i,j,k,OutputLayer;
double Sum;
OutputLayer = NumberOfLayers-1;
// Calculate all output signal error
for (i = 0; i < Layer[OutputLayer].Node.length; i++)
{
Layer[OutputLayer].Node[i].SignalError =
(ExpectedOutput[SampleNumber][i] -Layer[OutputLayer].Node[i].Output) *
Layer[OutputLayer].Node[i].Output *
(1-Layer[OutputLayer].Node[i].Output);
}
// Calculate signal error for all nodes in the hidden layer
// (back propagate the errors
for (i = NumberOfLayers-2; i > 0; i--)
{
for (j = 0; j < Layer[i].Node.length; j++)
{
Sum = 0;
for (k = 0; k < Layer[i+1].Node.length; k++)
Sum = Sum + Layer[i+1].Node[k].Weight[j] *
Layer[i+1].Node[k].SignalError;
Layer[i].Node[j].SignalError = Layer[i].Node[j].Output*(1 -
Layer[i].Node[j].Output)*Sum;
}
}
}
private void BackPropagateError()
{
int i,j,k;
// Update Weights
for (i = NumberOfLayers-1; i > 0; i--)
{
for (j = 0; j < Layer[i].Node.length; j++)
{
// Calculate Bias weight difference to node j
Layer[i].Node[j].ThresholdDiff = LearningRate *
Layer[i].Node[j].SignalError +
Momentum*Layer[i].Node[j].ThresholdDiff;
// Update Bias weight to node j
Layer[i].Node[j].Threshold =
Layer[i].Node[j].Threshold +
Layer[i].Node[j].ThresholdDiff;
// Update Weights
for (k = 0; k < Layer[i].Input.length; k++)
{
// Calculate weight difference between node j and k
Layer[i].Node[j].WeightDiff[k] =
LearningRate *
Layer[i].Node[j].SignalError*Layer[i-
1].Node[k].Output +
Momentum*Layer[i].Node[j].WeightDiff[k];
// Update weight between node j and k
Layer[i].Node[j].Weight[k] =
Layer[i].Node[j].Weight[k] +
Layer[i].Node[j].WeightDiff[k];
}
}
}
}
private void CalculateOverallError()
{
int i,j;
OverallError = 0;
for (i = 0; i < NumberOfSamples; i++)
for (j = 0; j < Layer[NumberOfLayers-1].Node.length; j++)
{
OverallError = OverallError +
0.5*( Math.pow(ExpectedOutput[i][j] - ActualOutput[i]
[j],2) );
}
}
public BackPropagation(int NumberOfNodes[],
double InputSamples[][],
double OutputSamples[][],
double LearnRate,
double Moment,
double MinError,
long MaxIter
)
{
int i,j;
// Initiate variables
NumberOfSamples = InputSamples.length;
MinimumError = MinError;
LearningRate = LearnRate;
Momentum = Moment;
NumberOfLayers = NumberOfNodes.length;
MaximumNumberOfIterations = MaxIter;
// Create network layers
Layer = new LAYER[NumberOfLayers];
// Assign the number of node to the input layer
Layer[0] = new LAYER(NumberOfNodes[0],NumberOfNodes[0]);
// Assign number of nodes to each layer
for (i = 1; i < NumberOfLayers; i++)
Layer[i] = new LAYER(NumberOfNodes[i],NumberOfNodes[i-1]);
Input = new double[NumberOfSamples][Layer[0].Node.length];
ExpectedOutput = new double[NumberOfSamples][Layer[NumberOfLayers-
1].Node.length];
ActualOutput = new double[NumberOfSamples][Layer[NumberOfLayers-
1].Node.length];
// Assign input set
for (i = 0; i < NumberOfSamples; i++)
for (j = 0; j < Layer[0].Node.length; j++)
Input[i][j] = InputSamples[i][j];
// Assign output set
for (i = 0; i < NumberOfSamples; i++)
for (j = 0; j < Layer[NumberOfLayers-1].Node.length; j++)
ExpectedOutput[i][j] = OutputSamples[i][j];
}
public void TrainNetwork()
{
int i,j;
long k=0;
do
{
// For each pattern
for (SampleNumber = 0; SampleNumber < NumberOfSamples; SampleNumber++)
{
for (i = 0; i < Layer[0].Node.length; i++)
Layer[0].Input[i] = Input[SampleNumber][i];
FeedForward();
// Assign calculated output vector from network to ActualOutput
for (i = 0; i < Layer[NumberOfLayers-1].Node.length; i++)
ActualOutput[SampleNumber][i] = Layer[NumberOfLayers-
1].Node[i].Output;
UpdateWeights();
// if we've been told to stop training, then
// stop thread execution
if (die){
return;
}
// if
}
k++;
// Calculate Error Function
CalculateOverallError();
System.out.println("OverallError =
"+Double.toString(OverallError)+"\n");
System.out.print("Epoch = "+Long.toString(k)+"\n");
} while ((OverallError > MinimumError) &&(k < MaximumNumberOfIterations));
}
public LAYER[] get_layers() { return Layer; }
// called when testing the network.
public double[] test(double[] input)
{
int winner = 0;
NODE[] output_nodes;
for (int j = 0; j < Layer[0].Node.length; j++)
{ Layer[0].Input[j] = input[j];}
FeedForward();
// get the last layer of nodes (the outputs)
output_nodes = (Layer[Layer.length - 1]).get_nodes();
double[] actual_output = new double[output_nodes.length];
for (int k=0; k < output_nodes.length; k++)
{
actual_output[k]=output_nodes[k].Output;
} // for
return actual_output;
}//test()
public double get_error()
{
CalculateOverallError();
return OverallError;
} // get_error()
// to change the delay in the network
public void set_delay(long time)
{
if (time >= 0) {
delay = time;
} // if
}
//save the trained network
public void save(String FileName)
{
try{
FileOutputStream fos = new FileOutputStream (new File(FileName), true);
// Serialize data object to a file
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
System.out.println("Network Saved!!!!");
}
catch (IOException E){System.out.println(E.toString());}
catch (Exception e){System.out.println(e.toString());}
}
public BackPropagation load(String FileName)
{
BackPropagation myclass= null;
try
{
//File patternDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"INDIAN_NUMBER_RECOGNITION.data");
//patternDirectory.mkdirs();
FileInputStream fis = new FileInputStream(new File(FileName));
//FileInputStream fis =context.openFileInput(FileName);
ObjectInputStream is = new ObjectInputStream(fis);
myclass = (BackPropagation) is.readObject();
System.out.println("Error After Reading = "+Double.toString(myclass.get_error())+"\n");
is.close();
fis.close();
return myclass;
}
catch (Exception e){System.out.println(e.toString());}
return myclass;
}
// needed to implement threading.
public void run() {
TrainNetwork();
File Net_File = new File(Environment.getExternalStorageDirectory(),"Number_Recognition_1.ser");
save(Net_File.getAbsolutePath());
System.out.println( "DONE TRAINING :) ^_^ ^_^ :) !\n");
System.out.println("With Network ERROR = "+Double.toString(get_error())+"\n");
} // run()
// to notify the network to stop training.
public void kill() { die = true; }
}
Layer Class:
public class LAYER implements Serializable
{
private double Net;
public double Input[];
// Vector of inputs signals from previous
// layer to the current layer
public NODE Node[];
// Vector of nodes in current layer
// The FeedForward function is called so that
// the outputs for all the nodes in the current
// layer are calculated
public void FeedForward() {
for (int i = 0; i < Node.length; i++) {
Net = Node[i].Threshold;
for (int j = 0; j < Node[i].Weight.length; j++)
{Net = Net + Input[j] * Node[i].Weight[j];
System.out.println("Net = "+Double.toString(Net)+"\n");
}
Node[i].Output = Sigmoid(Net);
System.out.println("Node["+Integer.toString(i)+".Output = "+Double.toString(Node[i].Output)+"\n");
}
}
// The Sigmoid function calculates the
// activation/output from the current node
private double Sigmoid (double Net) {
return 1/(1+Math.exp(-Net));
}
// Return the output from all node in the layer
// in a vector form
public double[] OutputVector() {
double Vector[];
Vector = new double[Node.length];
for (int i=0; i < Node.length; i++)
Vector[i] = Node[i].Output;
return (Vector);
}
public LAYER (int NumberOfNodes, int NumberOfInputs) {
Node = new NODE[NumberOfNodes];
for (int i = 0; i < NumberOfNodes; i++)
Node[i] = new NODE(NumberOfInputs);
Input = new double[NumberOfInputs];
}
// added by DSK
public NODE[] get_nodes() { return Node; }
}
Node Class:
public class NODE implements Serializable
{
public double Output;
// Output signal from current node
public double Weight[];
// Vector of weights from previous nodes to current node
public double Threshold;
// Node Threshold /Bias
public double WeightDiff[];
// Weight difference between the nth and the (n-1) iteration
public double ThresholdDiff;
// Threshold difference between the nth and the (n-1) iteration
public double SignalError;
// Output signal error
// InitialiseWeights function assigns a randomly
// generated number, between -1 and 1, to the
// Threshold and Weights to the current node
private void InitialiseWeights() {
Threshold = -1+2*Math.random();
// Initialise threshold nodes with a random
// number between -1 and 1
ThresholdDiff = 0;
// Initially, ThresholdDiff is assigned to 0 so
// that the Momentum term can work during the 1st
// iteration
for(int i = 0; i < Weight.length; i++) {
Weight[i]= -1+2*Math.random();
// Initialise all weight inputs with a
// random number between -1 and 1
WeightDiff[i] = 0;
// Initially, WeightDiff is assigned to 0
// so that the Momentum term can work during
// the 1st iteration
}
}
public NODE (int NumberOfNodes) {
Weight = new double[NumberOfNodes];
// Create an array of Weight with the same
// size as the vector of inputs to the node
WeightDiff = new double[NumberOfNodes];
// Create an array of weightDiff with the same
// size as the vector of inputs to the node
InitialiseWeights();
// Initialise the Weights and Thresholds to the node
}
public double[] get_weights() { return Weight; }
public double get_output() { return Output; }
}
I wrote the code in Netbeans exactly like this but it differs in the saving method where the file should be saved!.
How can I load the file correctly so I don't get this exception?
I Solved this by saving the network to XML file and then load it again in android so it just took two hours of training instead of days without any Serialization problems , although it took some time to load that XML I serialized it again to neural_network.ser so it will load much faster
I know it's not the best solution but that what I've done.
Here the is the code:
public void SaveToXML(String FileName)throws
ParserConfigurationException, FileNotFoundException,
TransformerException, TransformerConfigurationException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.newDocument();
Element root = doc.createElement("neuralNetwork");
Element layers = doc.createElement("structure");
layers.setAttribute("numberOfLayers",Integer.toString(this.NumberOfLayers));
for (int il=0; il<this.NumberOfLayers; il++){
Element layer = doc.createElement("layer");
layer.setAttribute("index",Integer.toString(il));
layer.setAttribute("numberOfNeurons",Integer.toString(this.Layer[il].Node.length));
if(il==0)
{
for(int in=0;in<this.Layer[il].Node.length;in++)
{
Element neuron = doc.createElement("neuron");
neuron.setAttribute("index",Integer.toString(in));
neuron.setAttribute("NumberOfInputs",Integer.toString(1));
neuron.setAttribute("threshold",Double.toString(this.Layer[il].Node[in].Threshold));
Element input = doc.createElement("input");
double[] weights = this.Layer[il].Node[in].get_weights();
input.setAttribute("index",Integer.toString(in));
input.setAttribute("weight",Double.toString(weights[in]));
neuron.appendChild(input);
layer.appendChild(neuron);
}
layers.appendChild(layer);
}
else
{
for (int in=0; in<this.Layer[il].Node.length;in++){
Element neuron = doc.createElement("neuron");
neuron.setAttribute("index",Integer.toString(in));
neuron.setAttribute("NumberOfInputs",Integer.toString(this.Layer[il].Node[in].Weight.length));
neuron.setAttribute("threshold",Double.toString(this.Layer[il].Node[in].Threshold));
for (int ii=0; ii<this.Layer[il].Node[in].Weight.length;ii++) {
double[] weights = this.Layer[il].Node[in].get_weights();
Element input = doc.createElement("input");
input.setAttribute("index",Integer.toString(ii));
input.setAttribute("weight",Double.toString(weights[ii]));
neuron.appendChild(input);
}
layer.appendChild(neuron);
layers.appendChild(layer);
}
}
}
root.appendChild(layers);
doc.appendChild(root);
File xmlOutputFile = new File(FileName);
FileOutputStream fos;
Transformer transformer;
fos = new FileOutputStream(xmlOutputFile);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(fos);
transformer.setOutputProperty("encoding","iso-8859-2");
transformer.setOutputProperty("indent","yes");
transformer.transform(source, result);
}
LoadFromXML Function:
public BackPropagation LoadFromXML(String FileName)throws
ParserConfigurationException, SAXException, IOException, ParseException
{
BackPropagation myclass= new BackPropagation();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
File source = new File(FileName);
Document doc = parser.parse(source);
Node nodeNeuralNetwork = doc.getDocumentElement();
if (!nodeNeuralNetwork.getNodeName().equals("neuralNetwork")) throw new ParseException("[Error] NN-Load: Parse error in XML file, neural network couldn't be loaded.",0);
NodeList nodeNeuralNetworkContent = nodeNeuralNetwork.getChildNodes();
System.out.print("<neuralNetwork>\n");
for (int innc=0; innc<nodeNeuralNetworkContent.getLength(); innc++)
{
Node nodeStructure = nodeNeuralNetworkContent.item(innc);
if (nodeStructure.getNodeName().equals("structure"))
{
System.out.print("<stucture nuumberOfLayers = ");
myclass.NumberOfLayers = Integer.parseInt(((Element)nodeStructure).getAttribute("numberOfLayers"));
myclass.Layer = new LAYER[myclass.NumberOfLayers];
System.out.print(Integer.toString(myclass.NumberOfLayers)+">\n");
NodeList nodeStructureContent = nodeStructure.getChildNodes();
for (int isc=0; isc<nodeStructureContent.getLength();isc++)
{
Node nodeLayer = nodeStructureContent.item(isc);
if (nodeLayer.getNodeName().equals("layer"))
{
int index = Integer.parseInt(((Element)nodeLayer).getAttribute("index"));
System.out.print("<layer index = "+Integer.toString(index)+" numberOfNeurons = ");
int number_of_N = Integer.parseInt(((Element)nodeLayer).getAttribute("numberOfNeurons"));
System.out.print(Integer.toString(number_of_N)+">\n");
if(index==0)
{
myclass.Layer[0]=new LAYER(number_of_N,800);
}
else
{
int j=index-1;
myclass.Layer[index]=new LAYER(number_of_N,myclass.Layer[j].Node.length);
}
NodeList nodeLayerContent = nodeLayer.getChildNodes();
for (int ilc=0; ilc<nodeLayerContent.getLength();ilc++)
{
Node nodeNeuron = nodeLayerContent.item(ilc);
if (nodeNeuron.getNodeName().equals("neuron"))
{
System.out.print("<neuron index = ");
int neuron_index = Integer.parseInt(((Element)nodeNeuron).getAttribute("index"));
myclass.Layer[index].Node[neuron_index].Threshold = Double.parseDouble(((Element)nodeNeuron).getAttribute("threshold"));
System.out.print(Integer.toString(neuron_index)+" threshold = "+Double.toString(myclass.Layer[index].Node[neuron_index].Threshold)+">\n");
NodeList nodeNeuronContent = nodeNeuron.getChildNodes();
for (int inc=0; inc < nodeNeuronContent.getLength();inc++)
{
Node nodeNeuralInput = nodeNeuronContent.item(inc);
if (nodeNeuralInput.getNodeName().equals("input"))
{
System.out.print("<input index = ");
int index_input = Integer.parseInt(((Element)nodeNeuralInput).getAttribute("index"));
myclass.Layer[index].Node[neuron_index].Weight[index_input] = Double.parseDouble(((Element)nodeNeuralInput).getAttribute("weight"));
System.out.print(Integer.toString(index_input)+" weight = "+Double.toString(myclass.Layer[index].Node[neuron_index].Weight[index_input])+">\n");
}
}
}
}
}
}
System.out.print("</structure");
}
}
return myclass;
}

What is the best way to loop over an array in JsonValue in libgdx?

I am porting an Android-only Game to libgdx. The world and level info is stored in a json file.
I used to do access the array with getJSONArray(id) like this:
public static WorldVO create(JSONObject worldObject) {
WorldVO worldVO = new WorldVO();
worldVO.id = worldObject.getInt("id");
worldVO.unlock = worldObject.getInt("stars_to_unlock");
worldObject.getChild("levels");
JSONArray levelJsonArray = worldObject.getJSONArray("levels");
int len = levelJsonArray.length();
worldVO.levelVOs = new LevelVO[len];
for (int i = 0; i < len; i++) {
worldVO.levelVOs[i] = LevelVO.create(levelJsonArray.getJSONObject(i));
}
...
which worked fine but I cannot find the correct way to loop through the "levels" child of the "worldObect" Json in libgdx when i use JsonValue instead of JSONObject.
Accessing the integer fields is not a problem but JsonValue does not have a getJSONArray. Any idea what to use? Thanks!
Based on this : http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/JsonValue.html
Try this :
public static WorldVO create(JsonValue worldObject)
{
WorldVO worldVO = new WorldVO();
worldVO.id = worldObject.getInt("id");
worldVO.unlock = worldObject.getInt("stars_to_unlock");
JsonValue levels = worldObject.get("levels");
int len = levels.size;
worldVO.levelVOs = new LevelVO[len];
for (int i = 0; i < len; i++)
{
worldVO.levelVOs[i] = LevelVO.create(levels.get(i));
}

Stuck with Pascal's Triangle in Java

Ok, I need to have a class that re-creates the Pascal Triangle. We are using BlueJ and I can't get my arrays to access each other.
Here's the code:
public class PascalTriangle {
private int currentLineNumber;
private int[] previousLineArray;
private int[] nextLineArray;
public void firstLine()
{
currentLineNumber = 1;
System.out.println("1");
}
public void nextLine()
{
if (currentLineNumber == 1) {
int [] previousLineArray = new int [(currentLineNumber+1)];
previousLineArray[0] = 1;
previousLineArray[1] = 1;
System.out.println("1 1");
currentLineNumber = 2;
}
else if(currentLineNumber >= 2) {
for (int lineCount = currentLineNumber; lineCount <= currentLineNumber; lineCount++) {
int [] nextLineArray = new int [(lineCount+1)];
nextLineArray[0] = 1;
System.out.print(nextLineArray[0] + " ");
for (int nextLineCount = 1; nextLineCount < lineCount; nextLineCount++) {
// The next line is the line with the NullPointerException
nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1)
+ previousLineArray[(nextLineCount)]]);
System.out.print(nextLineArray[(nextLineCount)] + " ");
}
nextLineArray[(lineCount)] = 1;
System.out.print(nextLineArray[(lineCount)] + "\n");
previousLineArray = nextLineArray;
}
currentLineNumber = currentLineNumber+1;
}
}
}
The class will compile but as I get to the third line, which should read 1 2 1, I get a java.lang.NullPointerException at PascalTriangle.nextLine(PascalTriangle.java:29) it highlists the nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1) line. Why will the nextLineArray take the information from previousLineArray which is set when the nextLine() method is called for the first time?
Any help would be appreciated :) Thanks.
the problem is the following:
in the line where int [] previousLineArray = new int [(currentLineNumber+1)]; - you create a local array that shadows your member and only visible inside of if statement. Then when you come to this line: nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1) it uses your member array that was not init.

libsvm classifying - at bad stage so far

Problem: I have certain set of data to be classified - Useful(1)/Useless(0). I will provide full set of data as input for training purpose of the classifier. and test with different data set.
For this, I am trying to convert my data to LIBSVM format. before doing anything, I thought of providing numeric input of one vector and check the result.
Input:
Training: 1 1 2 (the first 1 indicates useful Class in this vector followed by numeric input)
Testing: 1 1 2(I am not sure of input data format)
Output:
(0:0.9982708183417436)(1:0.0017291816582564153)(Actual:1.0 Prediction:0.0)
I dont have class 0 in training set, but it has probEstimated for class 0.
I am not really sure of how to convert my data to numeric vector input and fetch the data from the numeric test data set to equivalent Data as supplied. ANY HELP IN THIS REGARD IS HIGHLY APPRECIATED.
Planned tasks:
1. Load all the data to Hash tables and get the keys to be saved in data sets with respective classifier - USEFUL(1).
2. Supply the data set to the svmTrain and get the model.
3. Prepare test data set(Convert each word/phrase to respective numeric value saved training set, if found. Else, assign a new value).
4. Supply the test set and model to the SVM's EVALUATE method.
5. Get the resultant vectors from the USEFUL class and re-map to the data.
Code: used from different sources.
public class Datatosvmformat {
static double[][] train = new double[1000][3];
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String, Integer> dataSet = new HashMap<String, Integer>();
double[][] test = new double[10][3];
train[1][0] = 1;
train[1][1] = 1;
train[1][2] = 2;
svm_model model = svmTrain();
//Test Data Set
double[] test1 = new double[3];
test1[0] = 1;
test1[1] = 1;
test1[2] = 2;
evaluate(test1,model);
}
private static svm_model svmTrain() {
svm_problem prob = new svm_problem();
int dataCount = train.length;
prob.y = new double[dataCount];
prob.l = dataCount;
prob.x = new svm_node[dataCount][];
for (int i = 0; i <dataCount; i++){
double[] features = train[i];
//ystem.out.println("Features "+features[i]);
prob.x[i] = new svm_node[features.length-1];
for (int j = 1; j < features.length; j++){
svm_node node = new svm_node();
node.index = j;
node.value = features[j];
prob.x[i][j-1] = node;
}
prob.y[i] = features[0];
}
svm_parameter param = new svm_parameter();
param.probability = 1;
param.gamma = 0.5;
param.nu = 0.5;
param.C = 1;
param.svm_type = svm_parameter.C_SVC;
param.kernel_type = svm_parameter.LINEAR;
param.cache_size = 20000;
param.eps = 0.001;
svm_model model = svm.svm_train(prob, param);
return model;
}
public static double evaluate(double[] features, svm_model model)
{
svm_node[] nodes = new svm_node[features.length-1];
for (int i = 1; i < features.length; i++)
{
svm_node node = new svm_node();
node.index = i;
node.value = features[i];
nodes[i-1] = node;
}
int totalClasses = 2;
int[] labels = new int[totalClasses];
svm.svm_get_labels(model,labels);
double[] prob_estimates = new double[totalClasses];
double v = svm.svm_predict_probability(model, nodes, prob_estimates);
for (int i = 0; i < totalClasses; i++){
System.out.print("(" + labels[i] + ":" + prob_estimates[i] + ")");
}
System.out.println("(Actual:" + features[0] + " Prediction:" + v + ")");
return v;
}
}
I'm not completely sure, but the problem could be due to the fact that you need to mark positive examples with +1 and negative examples with -1.
Otherwise, the libsvm software could asssign an arbitraty class (e.g. 0) to the training vector 1 1 2, since it iterprets the first elem of the feature vector as a feature value (and not the label class).
So try to change the class label 1 in +1 for positive examples (and -1 for negative examples).
Usually, for data format for libsvm is the following:
<label> <index1>:<value1> <index2>:<value2>
where:
label is the class label (e.g. +1/-1)
indexN is the feature Id (i.e. the number that identified a certain feature)
valueN is the feature value (i.e. the value assigned to the specified feature: 0/1 for binary features or 0,1,2,... for categorical features)
An example of the data format accepted by the libsvm tool can be found at this page:
LIBSVM Data: Classification (Binary Class)
There are many datasets that you can explore in order to understand the data format accepted by the libsvm tool.

Categories