package org.mwg.ml.common;

import org.mwg.Callback;
import org.mwg.Graph;
import org.mwg.Node;
import org.mwg.ml.common.mathexp.impl.MathExpressionEngine;
import org.mwg.plugin.AbstractNode;

/**
 * Created by assaad on 04/05/16.
 */
public abstract class AbstractMLNode extends AbstractNode {
    public static String FROM_SEPARATOR = ";";
    public static String FROM = "FROM";

    public AbstractMLNode(long p_world, long p_time, long p_id, Graph p_graph, long[] currentResolution) {
        super(p_world, p_time, p_id, p_graph, currentResolution);
    }

    @Override
    public Object get(String propertyName) {
        if (propertyName != null && propertyName.startsWith("$")) {
            Object expressionObj = super.get(propertyName.substring(1));
            //ToDo this is dangerous for infinite loops or circular dependency, to fix
            org.mwg.ml.common.mathexp.MathExpressionEngine localEngine = MathExpressionEngine.parse(expressionObj.toString());
            return localEngine.eval(this);
        } else {
            return super.get(propertyName);
        }
    }


    public void setTrainingVector(double[] vec){
        String setFrom="";
        for(int i=0;i<vec.length;i++){
            set("f"+i,vec[i]);
            setFrom=setFrom+"f"+i+FROM_SEPARATOR;
        }
        set(FROM,setFrom);
    }

    public void extractFeatures(Callback<double[]> callback) {
        String query = (String) super.get(FROM);
        double[] result;
        if (query != null) {
            String[] split = query.split(FROM_SEPARATOR);
            result = new double[split.length];
            for (int i = 0; i < result.length; i++) {
                result[i] = Double.parseDouble(get(split[i]).toString());
            }
            callback.on(result);
        } else {
            callback.on(null);
        }
    }


}

@@ -1092,16 +1092,69 @@
     %7D%0A%0A%0A
+    //ToDo ouch this is hurting eyes for performance%0A
     publ
@@ -1192,16 +1192,17 @@
 e%5B%5D vec)
+ 
 %7B%0A      
@@ -1217,17 +1217,19 @@
  setFrom
-=
+ = 
 %22%22;%0A    
@@ -1239,19 +1239,25 @@
  for
+ 
 (int i
-=0;i%3C
+ = 0; i %3C 
 vec.
@@ -1263,20 +1263,22 @@
 .length;
+ 
 i++)
+ 
 %7B%0A      
@@ -1294,11 +1294,14 @@
 (%22f%22
-+
+ + 
 i,
+ 
 vec%5B
@@ -1328,23 +1328,31 @@
 From
-=
+ = 
 setFrom
-+%22f%22+i+
+ + %22f%22 + i + 
 FROM
@@ -1390,16 +1390,17 @@
 et(FROM,
+ 
 setFrom)

add some comments