Cannot execute Force Directed Graph

i have make coding but cannot execute what is the issues.

// # Force Directed Graph

var VerletPhysics2D = toxi.physics2d.VerletPhysics2D,
    VerletParticle2D = toxi.physics2d.VerletParticle2D,
    VerletSpring2D = toxi.physics2d.VerletSpring2D,
    VerletMinDistanceSpring2D = toxi.physics2d.VerletMinDistanceSpring2D,
    Vec2D = toxi.geom.Vec2D,
    Rect = toxi.geom.Rect;

function times(n, fn){
    var arr = [];
    for(var i=0; i<n; i++){
        arr.push(fn(i,n));
    }
    return arr;
};

// utility to provide an iterator function with everly element
// and every element after that element
function forEachNested(arr, fn){
    for(var i=0; i<arr.length; i++){
        for(var j=i+1; j<arr.length; j++){
            var result = fn(arr[i], arr[j], i, j, arr);
            if(result === false){
                return;
            }
        }
    }
}

var options = {
    numClusters: 8,
    particleRadius: 16,
    showPhysics: true,
    showParticles: true,
    springStrength: 0.01,
    minDistanceSpringStrength: 0.05
};

var gui = new dat.gui.GUI();
gui.add(options, 'numClusters', 5, 16).step(1);
gui.add(options, 'showPhysics');
gui.add(options, 'showParticles');
gui.add(options, 'springStrength', 0, 0.1).step(0.001);
gui.add(options, 'minDistanceSpringStrength', 0, 0.1).step(0.001);
gui.add({ makeGraph: makeGraph }, 'makeGraph').name('New Graph');


var clusters,
    physics;

var bottomPadding = 200;

function setup(){
    var p5Renderer2D = createCanvas(window.innerWidth, window.innerHeight - bottomPadding);
    document.getElementById('example-container').appendChild(p5Renderer2D.canvas);

    physics = new VerletPhysics2D();
    physics.setWorldBounds(new Rect(10, 10, width-20, height-20));

    // Spanw a new random Graph
    makeGraph();
}

function makeGraph(){
    physics.clear();

    clusters = times(options.numClusters, function(){
        return new Cluster(
            Math.floor(random(3,8)),
            Math.floor(random(20, 100)),
            new Vec2D(width/2, height/2)
        );
    });

    forEachNested(clusters, function(ci, cj){
        ci.connect(cj);
    })
}

function draw(){

    // update the physics world
    physics.update();

    background(255);

    // display all points
    if(options.showParticles){
        clusters.forEach(function(c){
            c.display();
        });
    }

    // show the physics
    if(options.showPhysics){
        forEachNested(clusters, function(ci, cj){
            //cluster internal connections
            ci.showConnections();
            // cluster connections to other clusters
            ci.showConnections(cj);
        });
    }
}

// A Cluster class, based on [The Nature of Code](http://natureofcode.com/)
// Initialize a Cluster with a number of nodes, a diameter and a centerpoint
function Cluster(n, d, center){
    this.diameter = d;
    this.nodes = times(n, function(){
        return new Node(center.add(Vec2D.randomVector()));
    });

    for(var i=1; i<this.nodes.length; i++){
        var pi = this.nodes[i];
        for(var j=0; j<i; j++){
            var pj = this.nodes[j];
            physics.addSpring(new VerletSpring2D(pi, pj, d, options.springStrength));
        }
    }
}

Cluster.prototype.display = function(){
    this.nodes.forEach(function(n){
        n.display();
    });
};


Cluster.prototype.connect = function(other){
    var selfDiam = this.diameter;
    this.nodes.forEach(function(pi){
        other.nodes.forEach(function(pj){
            physics.addSpring(
                new VerletMinDistanceSpring2D(
                    pi,
                    pj,
                    (selfDiam + other.diameter) * 0.5,
                    options.minDistanceSpringStrength
                )
            );
        })
    });
};

Cluster.prototype.showConnections = function(other){
    if(!other){
        //draw all the internal connections
        stroke(0, 150);
        forEachNested(this.nodes, function(pi, pj){
            line(pi.x, pi.y, pj.x, pj.y);
        });
    } else {
        stroke(0, 15);
        this.nodes.forEach(function(pi){
            other.nodes.forEach(function(pj){
                line(pi.x, pi.y, pj.x, pj.y);
            });
        });
    }
};



// Node inherits from `toxi.physic2d.VerletParticle2D`
// and adds a `display()` function for rendering with p5.js
function Node(pos){
    // extend VerletParticle2D!
    VerletParticle2D.call(this, pos);
}

Node.prototype = Object.create(VerletParticle2D.prototype);

Node.prototype.display = function(){
    fill(0, 150);
    stroke(0);
    ellipse(this.x, this.y, options.particleRadius, options.particleRadius);
};

Help me

How are you running it?

What specific error message are you getting?

I using p5.js mode. Once execute run the code no error its going server running at http://127.0.0.1:8486/ at internet explorer but empty interface.

If you open the console under developers tools (under Chrome for instance), do you get any error msgs?

Consider posting a minimum running example.

Kf

I have try it still same issues which is empty interface.

I have error on this coding using p5.js mode.

 x_disp = (x_diff / abs(x_diff)) * (x_diff**2) / k; 

error message shown which is

Syntax Error: Expected an operand but found *

Please help me

If I comment out:
document.getElementById('example-container').appendChild(p5Renderer2D.canvas);

Save your sketch as “sketch.js”.

And use the “index.html” below:

<!DOCTYPE html>

<meta charset=utf-8>
<meta name=viewport content=width=device-width,initial-scale=1>

<script async src=https://CDN.JSDelivr.net/npm/p5></script>

<script defer 
  src=https://CDN.JSDelivr.net/gh/hapticdata/toxiclibsjs/build/toxiclibs.min.js>
</script>

<script defer 
  src=http://CDN.JSDelivr.net/gh/dataarts/dat.gui/build/dat.gui.min.js>
</script>

<script defer src=sketch.js></script>

Your sketch just runs! :sunglasses:

Considering it’s written in JS, you should post it online so we folks can check it out more easily. :crazy_face:

For example, you can use these sites:

  1. https://www.OpenProcessing.org/sketch/create
  2. http://p5js.SketchPad.cc
  3. https://CodePen.io
  4. https://JsBin.com/?html,js,output

And many others to host your sketches online. :star_struck:

Here’s 1 sketch I’ve got w/ toxiclibsjs: :smiley_cat:

2 Likes

Once i run based on your guide. Still no interface on internet explorer. And also there have some statement on console.

java.net.SocketException: Connection reset
	at java.net.SocketInputStream.read(SocketInputStream.java:210)
	at java.net.SocketInputStream.read(SocketInputStream.java:141)
	at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
	at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
	at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
	at java.io.InputStreamReader.read(InputStreamReader.java:184)
	at java.io.BufferedReader.fill(BufferedReader.java:161)
	at java.io.BufferedReader.read(BufferedReader.java:182)
	at processing.core.PApplet.createReader(PApplet.java:6851)
	at processing.mode.p5js.server.HttpWorker.handleClient(HttpWorker.java:64)
	at processing.mode.p5js.server.HttpWorker.run(HttpWorker.java:44)
	at java.lang.Thread.run(Thread.java:748)
java.net.SocketException: Connection reset
	at java.net.SocketInputStream.read(SocketInputStream.java:154)
	at java.net.SocketInputStream.read(SocketInputStream.java:141)
	at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
	at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
	at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
	at java.io.InputStreamReader.read(InputStreamReader.java:184)
	at java.io.BufferedReader.fill(BufferedReader.java:161)
	at java.io.BufferedReader.readLine(BufferedReader.java:324)
	at java.io.BufferedReader.readLine(BufferedReader.java:389)
	at processing.mode.p5js.server.HttpWorker.handleClient(HttpWorker.java:74)
	at processing.mode.p5js.server.HttpWorker.run(HttpWorker.java:44)
	at java.lang.Thread.run(Thread.java:748)

i have try another coding, still not function and also no any issues but no output interface based on the below code. Help me on this…

var numVert;
var dict; // maps unique verteces -> all vertices they point to 
var loc_dict; // maps unique verteces -> current location
var k;
var area;
var edges;
var canvas_x;
var canvas_y;

function preload() {
	table = loadTable("Spellman.csv", "csv", "header");
}

function setup() {

  	canvas_x = 800;
  	canvas_y = 800;

	createCanvas(canvas_x, canvas_y);
	area = canvas_x * canvas_y;

  	dict = {};
  	loc_dict = {};
  	edges = [];
  	numVert = 0;

  	// fill dictionary
  	for (var i = 0; i < table.getRowCount(); i++) {

    	var v1 = int(table.getString(i, 0)); // vertex 1
    	var v2 = int(table.getString(i, 1)); // vertex 2

    	// add [v1, v2] to edges list
    	var a = [v1, v2];
    	edges[i] = a;

	    // add (v1 -> v2) to dict
	    if (v1 in dict) {
	    	var len = dict[v1].length;
	    	dict[v1][len] = v2; 
	    } else {
	    	dict[v1] = [v2];
	    	numVert += 1; 
	    }

	    // add (v2 -> v1 to dict)
	    if (v2 in dict) {
	    	var len = dict[v2].length;
	    	dict[v2][len] = v1;
	    } else {
	    	dict[v2] = [v2];
	    	numVert += 1; 
	    }
  	}

  	k = sqrt(area / numVert);

  	ellipse_width = 10;

  	// fill location dictionary..........vertex -> [x_pos, y_pos, x_disp, y_disp]
  	for (vert in dict) {
  		var x = Math.round(random(ellipse_width, canvas_x - ellipse_width));
  		var y = Math.round(random(ellipse_width, canvas_y - ellipse_width));

  		var array = [x, y, 0, 0];

  		loc_dict[vert] = array;
  	}

}

function draw() {

	background(255, 248, 220);

	 textSize(50);
	 fill(143, 216, 210);
	 text("Force Directed Graph", 30, 70);
	 fill(123, 196, 190);
	 text("Force Directed Graph", 32, 72);

	// Algorithm

	// No need for iterations because draw() simply loops infinitely

	// Calculate REPULSIVE forces..........................................
	for (v1 in dict) { // for each vertex

		var x_disp = 0; // displacement of x
		var y_disp = 0; // displacement of y

		loc_dict[v1][2] = 0; // set displacement to 0 
		loc_dict[v1][3] = 0; // set displacement to 0

		var x_v1 = loc_dict[v1][0]; // x-coordinate of v1
		var y_v1 = loc_dict[v1][1]; // y-coordinate of v1
			
		for (v2 in dict) { // for each other vertex

			if (v1 != v2) { // if the vertices are different

				var x_v2 = loc_dict[v2][0]; // x-coordinate of v2
				var y_v2 = loc_dict[v2][1]; // y-coordinate of v2

				var x_diff = x_v1 - x_v2;
				var y_diff = y_v1 - y_v2;

				if (x_diff != 0) { 
					x_disp = x_disp + (x_diff / abs(x_diff)) * (k**2) / abs(x_diff); // update displacement
				}

				if (y_diff != 0) {
					y_disp = y_disp + (y_diff / abs(y_diff)) * (k**2) / abs(y_diff); // update displacement
				}
			}
		}

		loc_dict[v1][2] = x_disp;
		loc_dict[v1][3] = y_disp;
	}

	// Calculate ATTRACTIVE forces...........................................
	
	for (v1 in dict) {

		for (var i = 0; i < dict[v1].length; i++) {

			var v2 = dict[v1][i]; // v2 key value

			var v1_x = loc_dict[v1][0]; // x location of v1
			var v1_y = loc_dict[v1][1]; // y location of v1
			var v2_x = loc_dict[v2][0]; // x location of v2
			var v2_y = loc_dict[v2][1]; // y location of v2

			var x_diff = v1_x - v2_x; // difference between the x of v1 & v2
			var y_diff = v1_y - v2_y; // difference between the x of v1 & v2

			var x_disp = 0; // x displacement of v1
			var y_disp = 0; // y displacement of v1

			if (x_diff != 0) { // check for division by 0
				x_disp = (x_diff / abs(x_diff)) * (x_diff**2) / k; // update displacement
			} 
			if (y_diff != 0) { // check for division by 0
				y_disp = (y_diff / abs(y_diff)) * (y_diff**2) / k; // update displacement
			}

			loc_dict[v1][2] -= x_disp; // update x displacement of v1
			loc_dict[v1][3] -= y_disp; // update y displacement of v1
			loc_dict[v2][2] += x_disp; // update x displacement of v2
			loc_dict[v2][3] += y_disp; // update y displacement of v2

		}
	}

	// Limit max displacement & print
	for (v in dict) {

		var x1_pos = loc_dict[v][0];
		var y1_pos = loc_dict[v][1];

		var x1_disp = loc_dict[v][2];
		var y1_disp = loc_dict[v][3];

		if (x1_disp != 0) {
			x1_pos = x1_pos + (x1_disp / abs(x1_disp));
		}

		if (y1_disp != 0) {
			y1_pos = y1_pos + (y1_disp / abs(y1_disp));
		}

		x1_pos = min(canvas_x - 50, max(10, x1_pos));
		y1_pos = min(canvas_y - 50, max(10, y1_pos));

		loc_dict[v][0] = x1_pos;
		loc_dict[v][1] = y1_pos;

		// Plotting ..................................................

		// Drawing vertex..........................
		strokeWeight(0); // ellipse info
		fill(143, 216, 210); // ellipse info
		ellipse(x1_pos, y1_pos, 20); // draw vertex ellipse

		// Drawing connection......................
		strokeWeight(1); // connection line info
		fill(0); // connection line info

		for (var i = 0; i < dict[v].length; i++) { // for each vertex that connects to vert

			var x2 = loc_dict[dict[v][i]][0];
			var y2 = loc_dict[dict[v][i]][1];

			line(x1_pos, y1_pos, x2, y2); // draw connecting line
		}

		// interaction
		if (dist(mouseX, mouseY, x1_pos, y1_pos) < 5) {

			fill(255, 145, 146); // rect info
			strokeWeight(0); // rect info
			rect(x1_pos, y1_pos - 30, 70, 30);


			fill(255, 248, 220); // text info
			strokeWeight(1); // text info
			
			textSize(25);
			text(v, x1_pos, y1_pos - 10);

			strokeWeight(0); // ellipse info
			fill(255, 145, 146); // ellipse info
			ellipse(x1_pos, y1_pos, 20); // draw vertex ellipse
		}
	}
}

Possiby related: https://forum.processing.org/two/discussion/15013/how-to-place-dots-and-circles-acquired-from-an-image-instead-of-random-dots-and-circles#latest

Kf

Finally i have complete with above coding with result. I can execute in d3.js. Thank you very much guys.