Skip to content

Instantly share code, notes, and snippets.

@hjroh0315
Created January 20, 2023 14:47
Show Gist options
  • Save hjroh0315/712b101e9a3fc0d1e1c99f02272a923b to your computer and use it in GitHub Desktop.
Save hjroh0315/712b101e9a3fc0d1e1c99f02272a923b to your computer and use it in GitHub Desktop.
barrier method optimization using nlsolve on ruby (buggy and inefficient tho)
require "bigdecimal"
require "bigdecimal/newton"
require "bigdecimal/util"
include Newton
class Function # :nodoc: all
def initialize(tval,ineq_constraints,maximize,dim)
@zero=BigDecimal("0.0")
@one=BigDecimal("1.0")
@two=BigDecimal("2.0")
@ten=BigDecimal("10.0")
@eps=BigDecimal("1.0e-20")
@t=tval
@ineq=ineq_constraints # array of arrays of bigdecimals with dim + 1 length, cons[0] being constant
@mxm=maximize # array of bigdecimals with dim length
@dim=dim
end
def zero;@zero;end
def one ;@one ;end
def two ;@two ;end
def ten ;@ten ;end
def eps ;@eps ;end
def values(x)
ineqtotal=["0".to_d]*@dim
ineqs=[]
@ineq.each do|cons|
ineqval="0".to_d
(1..@dim).each do|i|
ineqval-=cons[i]*x[i-1]
end
ineqval+=cons[0]
nvec=cons[1..]
ans="0".to_d
nvec.each{|v|ans+=v*v}
(0...@dim).each{|i|nvec[i]/=ans**(1/2r)}
(0...@dim).each{|i|nvec[i]/=ineqval}
(0...@dim).each{|i|ineqtotal[i]+=nvec[i]}
#p nvec
end
(0...@dim).each{|i|ineqtotal[i]*=-@t}
(0...@dim).each{|i|ineqtotal[i]+=@mxm[i]}
#p ineqtotal
ineqtotal
end
end
BigDecimal.limit(30)
ineq_constraints=[]
n=gets.to_i
x=["0".to_d]*n
pts=n.times.map{gets.split.map &:to_i}
(0...n).each do|i|
(i+1...n).each do|j|
dist=((pts[i][0]-pts[j][0])**2+(pts[i][1]-pts[j][1])**2)**(1/2r)
ineq=["0".to_d]*(n+1)
ineq[0]+=dist
ineq[i+1]+=1
ineq[j+1]+=1
ineq_constraints<<ineq.dup
end
end
t="10".to_d
begin
(1..200).each do|i|
f=Function.new(t*(97/100r)**i,ineq_constraints,["1".to_d]*n,n)
nlsolve(f,x)
end
rescue RuntimeError => e
p (x.sum*2*"3.141592653589793238".to_d).to_f
exit 0
end
p (x.sum*2*"3.141592653589793238".to_d).to_f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment