#!/usr/bin/env ruby
require("gsl")
include GSL::MultiFit

Rng.env_setup()
  
r = GSL::Rng.new(Rng::DEFAULT)

n = 19
dim = 3
X = Matrix.new(n, dim)
y = Vector.new(n)
w = Vector.new(n)

file0 = "testmultifit-0.dat"
file1 = "multifit.gp"

a = 0.1
File.open(file0, "w") do |f|
  for i in 0...n
    y0 = Math::exp(a)
    sigma = 0.1*y0
    val = r.gaussian(sigma)
    X.set(i, 0, 1.0)
    X.set(i, 1, a)
    X.set(i, 2, a*a)
    y[i] = y0 + val
    w[i] = 1.0/(sigma*sigma)
    f.printf("%g %g %g\n", a, y[i], sigma)
    a += 0.1
  end
end

c, cov, chisq, status = MultiFit.wlinear(X, w, y)
str = c[0].to_s
if c[1] > 0.0
  str += "+ #{c[1].abs}*x"
else
  str += "- #{c[1].abs}*x"
end
if c[2] > 0.0
  str += "+ #{c[2].abs}*x*x"
else
  str += "- #{c[2].abs}*x*x"
end
File.open(file1, "w") do |f|
  f.puts("set grid")
  f.puts("plot '#{file0}' w e, #{str}")
end

#puts("Try \"gnuplot -persist multifit.gp\"")
system("gnuplot -persist multifit.gp")
File.delete(file0)
