Class: NLopt::Opt

Inherits:
Object
  • Object
show all
Defined in:
lib/nlopt/opt.rb

Instance Method Summary collapse

Constructor Details

#initialize(algorithm, n) ⇒ Opt

Returns a new instance of Opt.



3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/nlopt/opt.rb', line 3

def initialize(algorithm, n)
  algorithm = FFI.nlopt_algorithm_from_string(algorithm)
  if algorithm < 0
    raise ArgumentError, "Invalid algorithm"
  end

  if n <= 0
    raise ArgumentError, "Invalid dimension"
  end

  @opt = FFI.nlopt_create(algorithm, n)
  @opt.free = FFI["nlopt_destroy"]
end

Instance Method Details

#algorithm_nameObject



71
72
73
# File 'lib/nlopt/opt.rb', line 71

def algorithm_name
  FFI.nlopt_algorithm_name(FFI.nlopt_get_algorithm(@opt)).to_s
end

#dimensionObject



75
76
77
# File 'lib/nlopt/opt.rb', line 75

def dimension
  FFI.nlopt_get_dimension(@opt)
end

#numevalsObject



79
80
81
# File 'lib/nlopt/opt.rb', line 79

def numevals
  FFI.nlopt_get_numevals(@opt)
end

#optimize(init) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/nlopt/opt.rb', line 53

def optimize(init)
  if init.size != dimension
    raise ArgumentError, "size does not match dimension"
  end

  x = Fiddle::Pointer[init.pack("d*")]
  opt_f = Fiddle::Pointer.malloc(Fiddle::SIZEOF_DOUBLE)
  res = FFI.nlopt_optimize(@opt, x, opt_f)

  if res < 0 && res != -4
    errmsg = FFI.nlopt_get_errmsg(@opt)
    msg = !errmsg.null? ? errmsg.to_s : "Bad result: #{FFI.nlopt_result_to_string(res).to_s}"
    raise Error, msg
  end

  x.to_s(x.size).unpack("d*")
end

#set_lower_bounds(lb) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/nlopt/opt.rb', line 29

def set_lower_bounds(lb)
  if lb.is_a?(Array)
    check_res FFI.nlopt_set_lower_bounds(@opt, Fiddle::Pointer[lb.pack("d*")])
  elsif lb.is_a?(Numeric)
    check_res FFI.nlopt_set_lower_bounds1(@opt, lb)
  else
    raise TypeError, "expected array or numeric"
  end
end

#set_max_objective(f) ⇒ Object



23
24
25
26
27
# File 'lib/nlopt/opt.rb', line 23

def set_max_objective(f)
  # keep reference
  @f = objective_callback(f)
  check_res FFI.nlopt_set_max_objective(@opt, @f, nil)
end

#set_maxeval(maxeval) ⇒ Object



49
50
51
# File 'lib/nlopt/opt.rb', line 49

def set_maxeval(maxeval)
  check_res FFI.nlopt_set_maxeval(@opt, maxeval)
end

#set_min_objective(f) ⇒ Object



17
18
19
20
21
# File 'lib/nlopt/opt.rb', line 17

def set_min_objective(f)
  # keep reference
  @f = objective_callback(f)
  check_res FFI.nlopt_set_min_objective(@opt, @f, nil)
end

#set_upper_bounds(ub) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/nlopt/opt.rb', line 39

def set_upper_bounds(ub)
  if ub.is_a?(Array)
    check_res FFI.nlopt_set_upper_bounds(@opt, Fiddle::Pointer[ub.pack("d*")])
  elsif ub.is_a?(Numeric)
    check_res FFI.nlopt_set_upper_bounds1(@opt, ub)
  else
    raise TypeError, "expected array or numeric"
  end
end