* @param inst the JSON object to turn into an Instance
* @param data the data so far (only used for header information)
* @return the Instance, null in case of an error
*/
protected static Instance toInstance(JSONNode inst, Instances data) {
Instance result;
boolean sparse;
double weight;
JSONNode values;
int i;
int index;
int pos;
String value;
double[] vals;
sparse = (Boolean) inst.getChild(SPARSE).getValue(new Boolean(false));
weight = (Double) inst.getChild(WEIGHT).getValue(new Double(1.0));
values = inst.getChild(VALUES);
vals = new double[data.numAttributes()];
for (i = 0; i < values.getChildCount(); i++) {
if (sparse) {
value = "" + ((JSONNode) values.getChildAt(i)).getValue();
pos = value.indexOf(SPARSE_SEPARATOR);
index = Integer.parseInt(value.substring(0, pos));
value = value.substring(pos + 1);
}
else {
index = i;
value = "" + ((JSONNode) values.getChildAt(i)).getValue();
}
try {
if (data.attribute(index).isNumeric()) {
vals[index] = Double.parseDouble(value);
}
else if (data.attribute(index).isNominal()) {
vals[index] = data.attribute(index).indexOfValue(value);
if ((vals[index] == -1) && value.startsWith("'") && value.endsWith("'"))
vals[index] = data.attribute(index).indexOfValue(Utils.unquote(value));
if (vals[index] == -1) {
System.err.println("Unknown label '" + value + "' for attribute #" + (index+1) + "!");
return null;
}
}
else if (data.attribute(index).isDate()) {
vals[index] = data.attribute(index).parseDate(value);
}
else if (data.attribute(index).isString()) {
vals[index] = data.attribute(index).addStringValue(value);
}
else {
System.err.println("Unhandled attribute type '" + Attribute.typeToString(data.attribute(index).type()) + "'!");
return null;
}
}
catch (Exception e) {
System.err.println("Error parsing value #" + (index+1) + ": " + e.toString());
return null;
}
}
result = new DenseInstance(weight, vals);
result.setDataset(data);
return result;
}