simple clustering

by jpeter06

HTML

<canvas id="pcanvas" >
  sin canvas
</canvas>

CSS

html, body{
  margin:0px;
  padding:0px;
  width:100%;
  height:100%;
  overflow:hidden;
}

canvas{

}

JavaScript

/*
- Start with any point from the dataset.
- Find all points within a certain radius around that point.
- Form a new cluster with the nearby points.
- Choose a new point that isn’t part of a cluster, and repeat until we have visited all the points.*/

var nump = 100;
var dist= 70;
var points=[];
var clusters=[];

var canvas = document.getElementById("pcanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var cwidth = canvas.width;
var cheight = canvas.height;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#ffaa22";

// That's how you  draw a point //
function point(x, y, r,ctx,text){
  ctx.beginPath();
  ctx.arc(x, y, r, 0, 2 * Math.PI, false);
  ctx.fill();
}

function text(x, y, text,ctx){
    ctx.beginPath();
    ctx.fillText(text, x, y);
    ctx.fill();
}


function distPoints(p1, p2){
	return Math.sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));
}

function genClusters(){
  var p=null;
  var tratados=[];
  for(var i=0; i< points.length; i++){
    p=points[i];
    if(!tratados.includes(p)){  
    	//Lo usamos como cluster, buscamos cercanos
    	var cluster=[];
      clusters.push(cluster);
      cluster.push(p);
      tratados.push(p);
      //Buscamos cercanos
      for(var j=0 ; j < points.length ; j++){
        var p2=points[j];
      	if(!tratados.includes(p2) && distPoints(p,p2)< dist){
        	cluster.push(p2);
          tratados.push(p2);
        }
      }
    }
  }
  console.log("num clusters:"+clusters.length);
}

function centerCluster(cluster){
  var cx = 0.0;
  var cy = 0.0;
  var l = cluster.length;
  for(var i=0; i<l; i++){
		cx += cluster[i].x;
    cy += cluster[i].y;
  }
  var r = { x:(cx/l), y:( cy/l)};
  return r;
}




function doAll(){
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   points=[];
   clusters=[];
   // Generamos puntos
  for(var i=0; i< nump; i++){
    points.push({x:cwidth*Math.random(), y:cheight*Math.random()});
  }
  
  //Generamos clusters
	genClusters();
  
  // Dibujamos...