/******************************************************************************* * Copyright (c) 2007, 2010 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.equation.solver; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; import org.simantics.db.exception.DatabaseException; import org.simantics.equation.EquationResources; public class Solver { private static Map solvers = new HashMap(); public static void addSolver(Resource res, ExpressionSolver solver) { if (res == null || solver == null) throw new NullPointerException("Expression solver must be bound to valid resource"); solvers.put(res, solver); } public void evaluate(ReadGraph g, Resource r) throws DatabaseException { if (g.isInstanceOf(r, EquationResources.equationResource.Expression)) { Collection types = g.getTypes(r); ExpressionSolver solver = null; for (Resource res : types) { solver = solvers.get(res); if (solver != null) break; } solver.evaluate(this, g, r); } else { throw new IllegalArgumentException("Input is not an equation"); } } Map valueMap = new HashMap(); public Object getCachedValue(Resource res) { return valueMap.get(res); } public void setValue(Resource res, Object o) { valueMap.put(res, o); } public void clear() { valueMap.clear(); } public double getDoubleValue(ReadGraph g, Resource d) throws DatabaseException { Object o = getValue(g, d); if (o instanceof double[]) return ((double[])o)[0]; if (o instanceof float[]) return ((float[])o)[0]; if (o instanceof int[]) return ((int[])o)[0]; if (o instanceof long[]) return ((long[])o)[0]; throw new RuntimeException("Cannot cast object to double " + o + " " + o.getClass()); } public Object getValue(ReadGraph graph, Resource res) throws DatabaseException { Object o = getCachedValue(res); if (o == null) { o = graph.getValue(res); } return o; } public void pushToGraph(WriteGraph graph) throws DatabaseException { for (Resource r : valueMap.keySet()) { if (graph.isInstanceOf(r, EquationResources.builtins.Literal)) { Object value = valueMap.get(r); if (value instanceof boolean[] || value instanceof byte[] || value instanceof int[] || value instanceof long[] || value instanceof float[] || value instanceof double[] || value instanceof String[]) graph.claimValue(r, value); else { throw new RuntimeException("Internal error, unknown datatype " + value.getClass()); } } } } }