1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.equation.solver;
14 import java.util.Collection;
15 import java.util.HashMap;
18 import org.simantics.db.ReadGraph;
19 import org.simantics.db.Resource;
20 import org.simantics.db.WriteGraph;
21 import org.simantics.db.exception.DatabaseException;
22 import org.simantics.equation.EquationResources;
27 private static Map<Resource,ExpressionSolver> solvers = new HashMap<Resource, ExpressionSolver>();
30 public static void addSolver(Resource res, ExpressionSolver solver) {
31 if (res == null || solver == null)
32 throw new NullPointerException("Expression solver must be bound to valid resource");
33 solvers.put(res, solver);
36 public void evaluate(ReadGraph g, Resource r) throws DatabaseException {
37 if (g.isInstanceOf(r, EquationResources.equationResource.Expression)) {
38 Collection<Resource> types = g.getTypes(r);
39 ExpressionSolver solver = null;
41 for (Resource res : types) {
42 solver = solvers.get(res);
46 solver.evaluate(this, g, r);
48 throw new IllegalArgumentException("Input is not an equation");
52 Map<Resource,Object> valueMap = new HashMap<Resource,Object>();
54 public Object getCachedValue(Resource res) {
55 return valueMap.get(res);
58 public void setValue(Resource res, Object o) {
66 public double getDoubleValue(ReadGraph g, Resource d) throws DatabaseException {
67 Object o = getValue(g, d);
68 if (o instanceof double[])
69 return ((double[])o)[0];
70 if (o instanceof float[])
71 return ((float[])o)[0];
72 if (o instanceof int[])
74 if (o instanceof long[])
75 return ((long[])o)[0];
76 throw new RuntimeException("Cannot cast object to double " + o + " " + o.getClass());
79 public Object getValue(ReadGraph graph, Resource res) throws DatabaseException {
80 Object o = getCachedValue(res);
82 o = graph.getValue(res);
87 public void pushToGraph(WriteGraph graph) throws DatabaseException {
88 for (Resource r : valueMap.keySet()) {
89 if (graph.isInstanceOf(r, EquationResources.builtins.Literal)) {
90 Object value = valueMap.get(r);
91 if (value instanceof boolean[] ||
92 value instanceof byte[] ||
93 value instanceof int[] ||
94 value instanceof long[] ||
95 value instanceof float[] ||
96 value instanceof double[] ||
97 value instanceof String[])
98 graph.claimValue(r, value);
100 throw new RuntimeException("Internal error, unknown datatype " + value.getClass());