diff examples/maths/Optimizer.java @ 1:5df24c91468d

Oh my what a mess.
author samer
date Fri, 05 Apr 2019 16:26:00 +0100
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/maths/Optimizer.java	Fri Apr 05 16:26:00 2019 +0100
@@ -0,0 +1,68 @@
+package eg.maths;
+import  samer.core.*;
+import  samer.core.types.*;
+import  samer.maths.*;
+import  samer.maths.opt.*;
+import  samer.nn.nonlin.*;
+
+public class Optimizer implements Agent
+{
+	Node     node=Node.push(new Node("optimizer"));
+	Function fn;
+	VDouble	a = new VDouble("a",-1);
+	VDouble	b = new VDouble("b",0);
+	VDouble	c = new VDouble("c",1);
+
+	MinimumBracket	br = new MinimumBracket();
+	BrentMinimiser min = new BrentMinimiser();
+
+	public Optimizer()
+	{
+		Object obj = (Function)Space.get("function");
+		if (obj==null) {
+			fn = new CompoundFunction( new Square(), new Quadratic(1,0,-1));
+		} else {
+			if (obj instanceof Function) fn=(Function)obj;
+			else if (obj instanceof FunctionOfVector) {
+				FunctionOfVector vfn=(FunctionOfVector)obj;
+				VVector x = (VVector)Space.get("vector");
+				VVector d = new VVector("d",x.size());
+				LineFunction linefn = new LineFunction(vfn,x.size());
+				linefn.setBase(x.array());
+				linefn.setDirection(d.array());
+				fn=linefn;
+			}
+		}
+
+		br.setFunction(fn);
+		min.setFunction(fn);
+		min.setFractionalTolerance(0.0001);
+		min.setAbsoluteTolerance(0.0001);
+		min.setBracket(br);
+
+		Shell.showViewer(new FunctionPlotter( node, fn), "Function");
+		Shell.showViewer(new FunctionPlotter( node, fn.derivative()), "Derivative");
+		Shell.exposeCommands(this);
+		Shell.exposeViewables();
+	}
+
+	public void getCommands(Agent.Registry r) { 
+		r.add("bracket").add("minimise"); 
+	}
+
+	public void execute(String cmd, Environment env)
+	{ 
+		if (cmd.equals("bracket")) {
+			br.setInitialPoints(a.value,b.value);
+			br.run();
+			a.value = br.ax; a.changed();
+			b.value = br.bx; b.changed();
+			c.value = br.cx; c.changed();
+		} else if (cmd.equals("minimise")) {
+			min.run();
+			Shell.print("minimum at x="+min.getArgument());
+			Shell.print("function value f(x)="+min.getValue());
+			Shell.print("took "+min.getIterations()+" iterations");
+		}
+	}
+}
\ No newline at end of file