package netstats;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;
import java.util.TreeSet;

import javax.sound.sampled.ReverbType;

import misc.ComparableIndexedValue;
import misc.ExtToolsDriver;

import generator.GraphGenerator;
import graph.APSP;
import graph.Graph;

public class NodeLatency {
	public static void AvgPathLengthNodeLatency(Graph g, String name) {
		
		Random r = new Random();
		
		Arrays.fill(g.we, 1.0);
		Arrays.fill(g.wn, 0.0);
		
		Graph grand = g.getStructure();
		Arrays.fill(grand.we, 1.0);
		Arrays.fill(grand.wn, 0.0);
		Graph gtarg = g.getStructure();
		Arrays.fill(gtarg.we, 1.0);
		Arrays.fill(gtarg.wn, 0.0);
		
		double[][] avg = new double[6][2];
		APSP ar = new APSP(grand);
		ar.computeFloydWarshallNodeLatencies();
		avg[0][0] = ar.avg();
		
		APSP at = new APSP(gtarg);
		at.computeFloydWarshallNodeLatencies();
		avg[0][1] = at.avg();
		
		TreeSet<ComparableIndexedValue> top = new TreeSet<ComparableIndexedValue>(Collections.reverseOrder());
		
		for (int i = 1; i < 6; i++) {
			double[] degs = at.centrality();
//			for(int j=1; j < degs.length; j++) degs[j] += degs[j-1];
//			for(int j=1; j < degs.length; j++) degs[j] /= degs[degs.length-1];
			top.clear();
			for (int n=0; n < degs.length; n++) {
				ComparableIndexedValue civ = new ComparableIndexedValue(n, degs[n]);
				top.add(civ);
				if (top.size() > 0.2*gtarg.getn()) top.remove(top.last());
			}
			
			// add node latencies randomly
			for (int j = 0; j <= 0.2*grand.getn(); j++) 
				grand.wn[r.nextInt(grand.getn())] += 2.0;
			ar.computeFloydWarshallNodeLatencies();
			avg[i][0] = ar.avg();
			
			// add node latency according to the degree
//			for (int j = 0; j <= 0.1*gtarg.getn(); j++) {
//				double prob = r.nextDouble();
//				int t = Arrays.binarySearch(degs, prob);
//				if (t < 0) t = t*(-1);
//				t = t-1;
//				gtarg.wn[t] += 2.0;
//			}
			for (ComparableIndexedValue ci: top) gtarg.wn[ci.ind] += 2.0;
			at.computeFloydWarshallNodeLatencies();
			avg[i][1] = at.avg();
		}
		
		String[] x = new String[11]; 
		for (int i=0; i <6; i++) x[i] = "" + i*20;
		String[] curve_names = {name+"-rand", name+"-targ"};
		
		ExtToolsDriver.plotCurves(x,curve_names, avg, 
								  "% Increased Latency", 
								  "Average path Length", 
								  name, "/home/petko/Dropbox/Comp_Net_Latency/");
		
	}
	
	public static void main(String[] args) {
		Graph gsf = GraphGenerator.generateScaleFree(200);
		AvgPathLengthNodeLatency(gsf,"sf");
		
		Graph gr = GraphGenerator.generateRandom(gsf.getn(), gsf.getm()/2);
		AvgPathLengthNodeLatency(gr,"er");
	}
	
	
}
