import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.core.neighboursearch.LinearNNSearch;

// Sourced from:
//   https://stackoverflow.com/questions/31350506/how-to-calculate-the-nearest-neighbors-using-weka-from-the-command-line

public class WekaCLFindNN
{
    public static void main(String[] args) throws Exception
    {

	//report that the code is running
	System.out.println("Weka Command Line Find Nearest " + args[0] + " Neighbors for each Instance in "  + args[1]); 
	
	//setup datasources, grab instances, and calculate the nearest neighbors
	DataSource source = new DataSource(""+args[1]);
	Instances instances = source.getDataSet();  
	weka.core.neighboursearch.LinearNNSearch knn = new LinearNNSearch(instances);
	
	//cycle through the dataset and get instances for the nearestneighbors
	for (int j=0; j<instances.numInstances(); j++) {
            Instances nearestInstances= knn.kNearestNeighbours(instances.instance(j), Integer.parseInt(args[0]));
	    
            //cycle through the instances and printout the nearestneighbors
            System.out.println("\n\n" + instances.instance(j));
            for(int i =0; i<Integer.parseInt(args[0]); i++) {
		System.out.println("\n\t" + nearestInstances.instance(i));
		
	    }

	}
	
	//close the code
	System.out.println("\n"+"Nearest Neighbors found"); // Display the string.
    }
}
