()
| 7 | use num::pow; |
| 8 | |
| 9 | fn main() { |
| 10 | |
| 11 | let fxy = |x: f64, y: f64| (pow(x, 2) + pow(y, 2)).sqrt(); |
| 12 | // objective function to be minimized |
| 13 | let f = |p: &[f64]| pow(fxy(p[0], p[1]) - 2.0, 2) + 10.0 * (fxy(p[0], p[1]) - 2.0).sin(); |
| 14 | // partial derivatives |
| 15 | let fd = |p: &[f64]| vec![ |
| 16 | 2.0 * (fxy(p[0], p[1]) - 2.0) * p[0] / fxy(p[0], p[1]) + 10.0 * (fxy(p[0], p[1]) - 2.0).cos() * p[0] / fxy(p[0], p[1]), |
| 17 | 2.0 * (fxy(p[0], p[1]) - 2.0) * p[1] / fxy(p[0], p[1]) + 10.0 * (fxy(p[0], p[1]) - 2.0).cos() * p[1] / fxy(p[0], p[1]) |
| 18 | ]; |
| 19 | |
| 20 | // set the number of iterations and the learning rate |
| 21 | let opts = empty_opts() |
| 22 | .iter(15) |
| 23 | .alpha(0.04); |
| 24 | |
| 25 | let r1 = opt(&f, // objective to minimize |
| 26 | &fd, // derivatives |
| 27 | &[2.7, 2.5], // initial parameters |
| 28 | opts // optimization options |
| 29 | ); |
| 30 | |
| 31 | // do a second optimization starting at a different location |
| 32 | let r2 = opt(&f, &fd, &[-6.0, 6.0], opts); |
| 33 | |
| 34 | // ---- plot |
| 35 | |
| 36 | let data1 = r1.matrix(); |
| 37 | let data2 = r2.matrix(); |
| 38 | |
| 39 | let o = builder() |
| 40 | .add("x = linspace(-7, 7, 80); y = linspace(-7, 7, 80)") |
| 41 | .add("[xx, yy] = meshgrid(x, y)") |
| 42 | .add("r = sqrt(xx .^ 2 + yy .^ 2)") |
| 43 | .add("z = (r-2) .^ 2 + 10 * sin(r-2)") |
| 44 | .add("mesh(x, y, z)") |
| 45 | .add("axis([-7,7,-7,7,-10,40])") |
| 46 | .add("view(340, 65)") |
| 47 | .add("hold on") |
| 48 | .add("hidden off") |
| 49 | .add("grid off") |
| 50 | .add_columns("plot3($1, $2, $3, 'linestyle', '-', 'marker', 'o', 'markerfacecolor', 'red', 'color', 'red', 'markersize', 5)", &data1) |
| 51 | .add_columns("plot3($1, $2, $3, 'linestyle', '-', 'marker', 'o', 'markerfacecolor', 'red', 'color', 'blue', 'markersize', 5)", &data2) |
| 52 | .add("print -r50 -dpng /tmp/3dplot.png"); |
| 53 | |
| 54 | o.run("/tmp/3dplot.m").unwrap(); |
| 55 | Window::new() |
| 56 | .show_image(&RgbImage::from_file("/tmp/3dplot.png").unwrap()) |
| 57 | .wait_key(); |
| 58 | } |
nothing calls this directly
no test coverage detected