Skip to content

Instantly share code, notes, and snippets.

View mortenjohs's full-sized avatar

Morten Johannes Ervik mortenjohs

  • International Agency for Research on Cancer
  • Lyon, France
View GitHub Profile
def cluster_plot_2D(clusters, seq = 1, title = "Random noise", get_x = 'x', get_y = 'y')
if defined? Gnuplot
Gnuplot.open do |gp|
Gnuplot::Plot.new(gp) do |plot|
plot.terminal "png"
plot.output File.expand_path("../outfiles/clusters-#{seq}.png", __FILE__)
plot.title title
# Plot each cluster's points
clusters.each do |cluster|
def k_means (points, k = 5, delta = 0.001, plot_on = false)
k = points.length if points.length < k
clusters = []
k.times { clusters << Cluster.new(points.sample) }
iterations = 0
while (clusters.any?(&:moved?))
class Cluster
attr_reader :center
def initialize(center)
@center = center
@points = []
@moved = true
end
def add_point(point)
@points << point
end
class Point2D < Point
def initialize(x, y = nil)
y.nil? ? super(x) : super({x: x, y: y})
end
end
class Point
def initialize(coords)
@coords = coords
end
def distance_to(point)
Math.sqrt( @coords.keys.inject(0) { |sum, key| sum + (@coords[key] - point.send(key))**2 } )
end
def to_s
"#{@coords.values.join(", ")}"
end
require 'benchmark'
require 'benchmark/ips'
array = []
1000.times { array << rand(1000) }
N = 10000
module Enumerable
def count_by_function function
map = Hash.new(0)
@mortenjohs
mortenjohs / partitions.rb
Last active December 10, 2015 02:48
A small script to automate the creation of groups in a class of students - to maximize the variation within each group, but minimize the difference between them. (As seen on: http://m635j520.blogspot.fr/2012/12/partitioning-or-students-into-n-groups.html )
require 'csv'
require 'pp'
require './names.rb'
require './countries.rb'
number_of_runs = 10000
number_of_groups = 4
participants_file = "participants.txt"
col_sep = "\t"
encoding = "UTF-8"
@mortenjohs
mortenjohs / k-means.rb
Last active October 13, 2015 19:07
k-means hack in Ruby
begin
require 'gnuplot'
rescue LoadError
puts "No usable Gnuplot..."
end
class Point
def initialize(coords)
@coords = coords
end
a = ["test", "tull", "tøys"]
=> ["test", "tull", "tøys"]
$ rvm get latest
$ rvm pkg install readline --verify-downloads 1
$ rvm reinstall all --force --verify-downloads 1