view examples/maths/Optimizer.java @ 8:5e3cbbf173aa tip

Reorganise some more
author samer
date Fri, 05 Apr 2019 22:41:58 +0100
parents 5df24c91468d
children
line wrap: on
line source
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");
		}
	}
}