Skip to content

Instantly share code, notes, and snippets.

@MatthewRDodds
Created September 29, 2015 16:16
Show Gist options
  • Save MatthewRDodds/dad452286830b2e8043a to your computer and use it in GitHub Desktop.
Save MatthewRDodds/dad452286830b2e8043a to your computer and use it in GitHub Desktop.
Ruby Graph Sample Data Generator
require 'json'
class NodeConnectionGenerator
attr_reader :node_count
attr_accessor :nodes, :edges
def initialize(node_count)
@node_count = node_count
@nodes = []
@edges = []
end
def generate
node_count.times do |n|
nodes << new_nodes_element(n)
next if n == 0 # Need other nodes to connect with first
add_new_interconnected_edges(n)
end
end
private
def new_nodes_element(n)
{ data: { id: n.to_s } }
end
def add_new_interconnected_edges(n)
edges << new_edges_element(n)
n.times do |i|
begin
if n % i == 0
edges << new_edges_element(n, (n - i))
end
rescue ZeroDivisionError
end
end
end
def new_edges_element(n, target = nil)
source = n.to_s
target ||= (n - 1).to_s
{ data: { id: "#{source}#{target}", source: source, target: target } }
end
end
generator = NodeConnectionGenerator.new(250)
generator.generate
File.open('nodes.json', 'w') { |file| file.puts generator.nodes.to_json }
File.open('edges.json', 'w') { |file| file.puts generator.edges.to_json }
@MatthewRDodds
Copy link
Author

With 1000 nodes and 7000 connections using cytoscape.js:

screencapture-file-users-matt-code-20spokes-third_party-graph-examples-cytoscape-js-cytoscape-html-1443542916787

screencapture-file-users-matt-code-20spokes-third_party-graph-examples-cytoscape-js-cytoscape-html-1443542993048

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment