checkEnabled="true">\r
</visibleWhen>\r
</command>\r
+ <command\r
+ commandId="org.simantics.sysdyn.ui.importMdl"\r
+ label="vensim import test"\r
+ style="push">\r
+ </command>\r
</menu>\r
<menu\r
id="org.simantics.export"\r
import org.simantics.db.WriteGraph;\r
import org.simantics.db.common.request.WriteRequest;\r
import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.sysdyn.mdlImport.MdlParser;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Model;\r
+import org.simantics.sysdyn.modelImport.MdlParser;\r
+import org.simantics.sysdyn.modelImport.model.Model;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
import org.simantics.sysdyn.ui.Activator;\r
import org.simantics.ui.SimanticsUI;\r
\r
Activator.getDefault().getPreferenceStore().setValue(IMPORTMDLTPATH, (new File(selected)).getParent());\r
\r
// Convert Vensim model to Simantics SysDyn format using MdlParser\r
- final Model model = MdlParser.parse(file);\r
+ final Model model;\r
+ try {\r
+ model = MdlParser.parse(file);\r
+ }\r
+ catch (Exception e) {\r
+ e.printStackTrace();\r
+ return null;\r
+ }\r
\r
SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
\r
@Override\r
public void perform(WriteGraph graph) throws DatabaseException {\r
- model.write(graph, project);\r
+ model.write(graph, project, new WriteContext());\r
}\r
});\r
\r
import org.simantics.db.WriteGraph;\r
import org.simantics.db.common.request.WriteRequest;\r
import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.sysdyn.mdlImport.MdlParser;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Model;\r
+import org.simantics.sysdyn.modelImport.MdlParser;\r
+import org.simantics.sysdyn.modelImport.model.Model;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
import org.simantics.ui.SimanticsUI;\r
\r
public class WizardMdlImportPage extends WizardPage{\r
\r
@Override\r
public void perform(WriteGraph graph) throws DatabaseException {\r
- model.write(graph, project);\r
+ model.write(graph, project, new WriteContext());\r
}\r
});\r
\r
org.simantics.sysdyn.elementaryCycles,
org.simantics.sysdyn.expressionParser,
org.simantics.sysdyn.manager,
- org.simantics.sysdyn.mdlImport,
- org.simantics.sysdyn.mdlImport.mdlElements,
+ org.simantics.sysdyn.modelImport,
+ org.simantics.sysdyn.modelImport.model,
org.simantics.sysdyn.modelParser,
org.simantics.sysdyn.modelica,
org.simantics.sysdyn.representation,
@Override\r
public void perform(WriteGraph graph) throws DatabaseException {\r
SimulationResource SIMU = SimulationResource.getInstance(graph);\r
- System.err.println("CHANGE ACTIVE STATE OF EXPERIMENT");\r
if(activate)\r
graph.claim(experiment, SIMU.IsActive, experiment);\r
else\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport;\r
-\r
-import java.io.BufferedReader;\r
-import java.io.IOException;\r
-import java.io.StringReader;\r
-import java.util.regex.Matcher;\r
-import java.util.regex.Pattern;\r
-\r
-public class ImportUtils {\r
- \r
- public static String escapeExpression(String string) {\r
- string = string.replace("Ä", "A");\r
- string = string.replace("ä", "a");\r
- string = string.replace("ö", "o");\r
- string = string.replace("Ö", "O");\r
- string = string.replace("\\", "\n");\r
- \r
- StringBuilder sb = new StringBuilder();\r
- \r
- if(string.contains("\"")) {\r
- boolean startedQuote = false;\r
- StringBuilder var = new StringBuilder();\r
- for(char c : string.toCharArray()) {\r
- if(c == '"') {\r
- if(!startedQuote) {\r
- startedQuote = true;\r
- var = new StringBuilder();\r
- continue;\r
- } else {\r
- startedQuote = false;\r
- sb.append(var.toString().replaceAll("[^a-zA-Z 0-9]+", ""));\r
- continue;\r
- }\r
- }\r
- if(startedQuote) {\r
- var.append(c);\r
- } else {\r
- sb.append(c);\r
- }\r
- }\r
- \r
- string = sb.toString();\r
- }\r
- \r
- return string;\r
-\r
- }\r
- \r
- public static String escapeName(String string) {\r
- string = string.replace("Ä", "A");\r
- string = string.replace("ä", "a");\r
- string = string.replace("ö", "o");\r
- string = string.replace("Ö", "O");\r
- string = string.replaceAll("[^a-zA-Z 0-9]+", "");\r
- return string;\r
- }\r
-\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport;\r
-\r
-import java.util.ArrayList;\r
-\r
-public class MdlFile {\r
- \r
- private ArrayList<String> variables = new ArrayList<String>();\r
- private ArrayList<String> controls = new ArrayList<String>();\r
- private ArrayList<String> sketchData = new ArrayList<String>();\r
- private ArrayList<String> otherData = new ArrayList<String>();\r
-\r
-\r
-\r
- public void addVariable(String variable) {\r
- variables.add(variable);\r
- }\r
- \r
- public ArrayList<String> getVariables() {\r
- return variables;\r
- }\r
- \r
- public void addControl(String control) {\r
- controls.add(control);\r
- }\r
- \r
- public ArrayList<String> getControls() {\r
- return controls;\r
- }\r
- \r
- public void addSketchData(String sketchRow) {\r
- sketchData.add(sketchRow);\r
- }\r
-\r
- public ArrayList<String> getSketchData() {\r
- return sketchData;\r
- }\r
-\r
- public void addOtherData(String dataRow) {\r
- otherData.add(dataRow);\r
- }\r
-\r
- public ArrayList<String> getOtherData() {\r
- return otherData;\r
- }\r
-\r
-\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport;\r
-\r
-import java.awt.geom.Point2D;\r
-import java.io.BufferedReader;\r
-import java.io.File;\r
-import java.io.FileInputStream;\r
-import java.io.FileReader;\r
-import java.io.IOException;\r
-import java.io.InputStreamReader;\r
-import java.io.Reader;\r
-import java.util.ArrayList;\r
-import java.util.HashMap;\r
-\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Auxiliary;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Cloud;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Connection;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Dependency;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Element;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.EquivalenceSubscript;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Expression;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Flow;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Function;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Model;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Stock;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Subscript;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Valve;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.Variable;\r
-import org.simantics.sysdyn.mdlImport.mdlElements.View;\r
-\r
-public class MdlParser {\r
- \r
- public static Model parse(File file) {\r
- \r
- Model model = new Model();\r
- \r
- String[] name = file.getName().split("\\.mdl");\r
- model.setName(name[0]);\r
- \r
- MdlFile mdlFile = getMdlContents(file);\r
- \r
- getVariableData(model, mdlFile.getVariables());\r
- \r
- getSketchData(model, mdlFile.getSketchData());\r
- \r
- getControlData(model, mdlFile.getControls());\r
- \r
-// getOthertData(model, mdlFile.getOtherData());\r
- \r
- setAllSubscripts(model);\r
- \r
- return model;\r
- }\r
- \r
-\r
- private static MdlFile getMdlContents(File aFile) {\r
- MdlFile mdlFile = new MdlFile();\r
- \r
- try {\r
- BufferedReader input = new BufferedReader(new FileReader(aFile));\r
- \r
- try {\r
- String line = null; //not declared within while loop\r
- \r
- // See if the document is encoded with UTF-8. It will be marked with {UTF-8} on the first line\r
- input.mark(30);\r
- if (( line = input.readLine()) != null &&\r
- line.contains("{UTF-8}")){\r
- Reader in = new InputStreamReader(new FileInputStream(aFile), "UTF-8");\r
- input = new BufferedReader(in);\r
- line = input.readLine();\r
- } else {\r
- input.reset();\r
- }\r
- \r
- \r
- boolean isControl = false;\r
- \r
- while (( line = input.readLine()) != null){\r
- // Build an element (combine the lines to one string)\r
- StringBuilder elementBuilder = new StringBuilder();\r
- while(line != null && !line.contains("\\\\\\---///")) {\r
- // Add a new line for the element\r
- elementBuilder.append(line);\r
- if(line.endsWith("|") && !line.endsWith("~~|")) {\r
- //Element definition has ended\r
- break;\r
- }\r
- line = input.readLine();\r
- }\r
- \r
- if(line.contains("\\\\\\---///"))\r
- break;\r
- \r
- String variable = elementBuilder.toString();\r
-\r
- if(variable.trim().matches("[\\*]{46}.+[\\*]{46}.+")) {\r
- if(variable.contains(".Control")) {\r
- isControl = true;\r
- } else {\r
- isControl = false;\r
- }\r
- continue;\r
- }\r
-\r
- // Add element string to model\r
- if(isControl) {\r
- mdlFile.addControl(variable);\r
- } else {\r
- mdlFile.addVariable(variable);\r
- }\r
- }\r
- \r
- while (( line = input.readLine()) != null && !line.contains("///---\\\\\\")){\r
- mdlFile.addSketchData(line);\r
- }\r
- \r
- while (( line = input.readLine()) != null){\r
- mdlFile.addOtherData(line);\r
- }\r
- }\r
- finally {\r
- input.close();\r
- }\r
- }\r
- catch (IOException ex){\r
- ex.printStackTrace();\r
- }\r
- \r
- return mdlFile;\r
- }\r
- \r
- private static void getVariableData(Model model, ArrayList<String> elements) {\r
- ArrayList<EquivalenceSubscript> equivalenceSubscripts = new ArrayList<EquivalenceSubscript>();\r
- for(String elementString : elements) {\r
- Variable v = createVariable(model, elementString);\r
- if(v instanceof EquivalenceSubscript){\r
- equivalenceSubscripts.add((EquivalenceSubscript) v);\r
- }\r
- }\r
- \r
- // All variables are ready, determine subscript equivalences\r
- for(EquivalenceSubscript es : equivalenceSubscripts) {\r
- Element e = model.getElement(es.getEquivalentToName());\r
- if(e != null && e instanceof Subscript) {\r
- es.setEquivalentTo((Subscript)e);\r
- }\r
- }\r
- }\r
- \r
- \r
- private static void getControlData(Model model, ArrayList<String> controls) {\r
- for(String controlString : controls) {\r
- String[] nameAndData = controlString.split("="); \r
- String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]");\r
- \r
- if(nameAndData[0].trim().equals("FINAL TIME")) {\r
- model.setEndTime(Double.parseDouble(expressionUnitsAndComments[0]));\r
- } else if(nameAndData[0].trim().equals("INITIAL TIME")) {\r
- model.setStartTime(Double.parseDouble(expressionUnitsAndComments[0]));\r
- } else if(nameAndData[0].trim().equals("TIME STEP")) {\r
- model.setTimeStep(Double.parseDouble(expressionUnitsAndComments[0]));\r
- } else if(nameAndData[0].trim().equals("SAVEPER")) {\r
- model.setSaveper(expressionUnitsAndComments[0]);\r
- model.setTimeUnit(expressionUnitsAndComments[1]);\r
- }\r
- }\r
- \r
- }\r
- \r
- private static Variable getVariable(Model model, String name) {\r
- Element e = model.getElement(name);\r
- Variable variable = null;\r
- if(e != null && e instanceof Variable)\r
- variable = (Variable)e;\r
- return variable;\r
- }\r
- \r
- private static String[] getNormalVariableNameDataAndRange(String element) {\r
- String[] nameAndData = element.split("=", 2);\r
- String[] nameAndRange = nameAndData[0].trim().split("[\\[|\\]]");\r
- if(nameAndData.length == 2)\r
- return new String[] {nameAndRange[0], nameAndData[1], nameAndRange.length == 2 ? nameAndRange[1] : null};\r
- return null;\r
- }\r
- \r
- private static String[] getSubscriptNameAndData(String element) {\r
- String[] nameAndData = element.split(":");\r
- if(nameAndData.length == 2)\r
- return nameAndData;\r
- return null;\r
- } \r
- \r
- private static String[] getEquivalenceSubscriptNameAndData(String element) {\r
- String[] nameAndData = element.split("\\<\\-\\>");\r
- if(nameAndData.length == 2)\r
- return nameAndData;\r
- return null;\r
- }\r
- \r
- private static String[] getTableNameDataAndRange(String element) {\r
- String[] parts = element.split("\\~"); \r
- if(!parts[0].contains("(") || !parts[0].contains(")"))\r
- return null;\r
- String name = element.substring(0, element.indexOf("("));\r
- String theRest = element.substring(element.indexOf("("));\r
- String[] nameAndData = {name, theRest};\r
- String[] nameAndRange = nameAndData[0].trim().split("[\\[|\\]]");\r
- if(nameAndData.length == 2)\r
- return new String[] {nameAndRange[0], nameAndData[1], nameAndRange.length == 2 ? nameAndRange[1] : null};\r
- return nameAndData;\r
- }\r
- \r
- private static String[] getDataVariableNameAndData(String element) {\r
- String[] nameAndData = {\r
- element.substring(0, element.indexOf("~")),\r
- " " + element.substring(element.indexOf("~"))};\r
- return nameAndData;\r
- }\r
- \r
- private static Variable createVariable(Model model, String elementString) {\r
-\r
- String[] elementExpressions = elementString.split("\\~\\~\\|");\r
- \r
- Variable variable = null;\r
- \r
- for(String s : elementExpressions) {\r
- // Skip these definitions at least for now\r
- if(elementExpressions.length > 1 && s.contains("A FUNCTION OF"))\r
- continue;\r
- \r
- Expression expression = new Expression();\r
-\r
- String[] nameAndData = null;\r
- String name;\r
- \r
- // Create the expression based on the expression string\r
- if((nameAndData = getNormalVariableNameDataAndRange(s)) != null) {\r
- \r
- name = nameAndData[0].replace("\"", "");\r
- variable = getVariable(model, name);\r
- if(variable == null) {\r
- variable = new Auxiliary();\r
- variable.setName(name);\r
- model.addElement(variable);\r
- }\r
- \r
- if(!nameAndData[1].trim().endsWith("|")) {\r
- // Multiple expressions\r
- expression.setExpression(nameAndData[1].trim());\r
- } else {\r
- String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]");\r
- expression.setExpression(expressionUnitsAndComments[0].trim());\r
- }\r
- \r
- } else if((nameAndData = getSubscriptNameAndData(s)) != null) {\r
- \r
- name = nameAndData[0].replace("\"", "");\r
- variable = getVariable(model, name);\r
- if(variable == null) {\r
- variable = new Subscript();\r
- variable.setName(name);\r
- model.addElement(variable);\r
- }\r
- \r
- // No support for multidimensional variables. Don't know what that would mean\r
- String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]");\r
- expression.setExpression(expressionUnitsAndComments[0].trim());\r
- variable.setUnits(expressionUnitsAndComments[1].trim());\r
- variable.setComments(expressionUnitsAndComments[2].trim());\r
- \r
- } else if((nameAndData = getEquivalenceSubscriptNameAndData(s)) != null) {\r
- \r
- name = nameAndData[0].replace("\"", "");\r
- variable = getVariable(model, name);\r
- if(variable == null) {\r
- variable = new EquivalenceSubscript();\r
- variable.setName(name);\r
- model.addElement(variable);\r
- }\r
- \r
- // No support for multidimensional variables. Don't know what that would mean\r
- String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]");\r
- expression.setExpression(expressionUnitsAndComments[0].trim());\r
- variable.setUnits(expressionUnitsAndComments[1].trim());\r
- variable.setComments(expressionUnitsAndComments[2].trim());\r
- \r
- } else if((nameAndData = getTableNameDataAndRange(s)) != null) {\r
- \r
- name =(nameAndData[0].replace("\"", ""));\r
- variable = getVariable(model, name);\r
- if(variable == null) {\r
- variable = new Function();\r
- variable.setName(name);\r
- model.addElement(variable);\r
- }\r
- \r
- String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]");\r
- // ([(0,0)-(2,5)],(0,5),(0.5,3),(1,0.5),(2,0.5) => ( ; (0,0)-(2,5) ; ,(0,5),(0.5,3),(1,0.5),(2,0.5)\r
- String table = expressionUnitsAndComments[0].trim().split("[\\[|\\]]")[2];\r
- // ,(0,5),(0.5,3),(1,0.5),(2,0.5) => (0,5),(0.5,3),(1,0.5),(2,0.5)\r
- table = table.substring(table.indexOf(",") + 1, table.lastIndexOf(")"));\r
- table = "{" + table + "}";\r
- table = table.replace("(", "{");\r
- table = table.replace(")", "}");\r
- expression.setExpression(table); \r
- \r
- \r
- } else if((nameAndData = getDataVariableNameAndData(s)) != null) {\r
- \r
- name = nameAndData[0].replace("\"", "");\r
- variable = getVariable(model, name);\r
- if(variable == null) {\r
- variable = new Auxiliary();\r
- variable.setName(name);\r
- model.addElement(variable);\r
- }\r
- \r
- expression.setExpression("");\r
- } \r
- \r
- if(nameAndData == null || variable == null)\r
- continue;\r
- \r
- // Set possible range for the expression\r
- if(nameAndData.length == 3)\r
- expression.setRange(nameAndData[2]);\r
- \r
- // Set units and comments for the variable \r
- if(nameAndData[1].trim().endsWith("|")) {\r
- String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]");\r
- String units = expressionUnitsAndComments[1].trim();\r
- if(units.contains("[") &&\r
- units.contains("]") &&\r
- units.lastIndexOf("]") == units.length() - 1) {\r
- // Range definitions are at the end\r
- String range = units.substring(\r
- units.lastIndexOf("[") + 1, \r
- units.length() - 1);\r
- String[] rangeParts = range.split(",");\r
- \r
- try {\r
- variable.setRangeStart(Double.parseDouble(rangeParts[0]));\r
- if(rangeParts.length >= 2)\r
- variable.setRangeEnd(Double.parseDouble(rangeParts[1]));\r
- if(rangeParts.length >= 3)\r
- variable.setRangeStep(Double.parseDouble(rangeParts[2]));\r
- } catch (NumberFormatException e) {\r
- // Not a double\r
- }\r
- expressionUnitsAndComments[1] = units.substring(0, units.lastIndexOf("["));\r
- }\r
- variable.setUnits(expressionUnitsAndComments[1].trim());\r
- variable.setComments(expressionUnitsAndComments[2].trim());\r
- }\r
- \r
- // Finally add the expression to element\r
- variable.getExpressions().add(expression);\r
- }\r
- return variable;\r
- }\r
- \r
- private static int SCALE = 4;\r
- private static void getSketchData(Model model, ArrayList<String> sketchData) {\r
-\r
- String line = null;\r
- View view = null;\r
- int i = 0;\r
- while(i < sketchData.size()) {\r
- line = sketchData.get(i);\r
- if(line.startsWith("*")) {\r
- view = new View();\r
- model.addView(view);\r
- \r
- view.setName(line.substring(1));\r
-\r
- // STARTED A NEW VIEW\r
-\r
- HashMap<String, Element> elementNumbers = new HashMap<String, Element>();\r
- ArrayList<String> ghostNumbers = new ArrayList<String>();\r
- ArrayList<String[]> connections = new ArrayList<String[]>();\r
- HashMap<String, String[]> emptyValves = new HashMap<String, String[]>(); // map for valves that don't have an element \r
- \r
- \r
- i++;\r
- line = sketchData.get(i);\r
- while(i < sketchData.size() && !sketchData.get(i).startsWith("*")) {\r
- line = sketchData.get(i);\r
- \r
- if(line.startsWith("$")) {\r
- view.setFontParameters(line);\r
- i++;\r
- continue;\r
- }\r
- \r
- String[] data = line.split(",");\r
- if(data[0].equals("1")) {\r
- // Connections are handled after all elements\r
- String[] connectionData = line.split(",");\r
- connections.add(connectionData);\r
- \r
- } else if(data[0].equals("11")){\r
- // Valve\r
- i = i + 1;\r
- String elementLine = sketchData.get(i);\r
- String[] elementData = elementLine.split(",");\r
- // FIXME: Assumes that element is always attached to the valve\r
- Element element = model.getElement(elementData[2].replace("\"", ""));\r
- Valve valve = new Valve();\r
- if(element != null && element instanceof Variable) {\r
- Variable v = (Variable) element;\r
- valve.setName(v.getName());\r
- valve.setExpressions(v.getExpressions());\r
- valve.setUnits(v.getUnits());\r
- valve.setComments(v.getComments());\r
- valve.setX(Integer.parseInt(data[3]) / SCALE);\r
- valve.setY(Integer.parseInt(data[4]) / SCALE);\r
- \r
- model.removeElement(element);\r
- model.addElement(view, valve);\r
- \r
- // Add valve to the element list with both valve and variable symbol numbers\r
- elementNumbers.put(elementData[1], valve);\r
- elementNumbers.put(data[1], valve);\r
- } else {\r
- i = i - 1;\r
- emptyValves.put(data[1], data);\r
- }\r
- } else if(data[0].equals("12")){\r
- // Cloud\r
- Cloud cloud = new Cloud();\r
- cloud.setX(Integer.parseInt(data[3]) / SCALE); \r
- cloud.setY(Integer.parseInt(data[4]) / SCALE); \r
- elementNumbers.put(data[1], cloud);\r
- model.addElement(view, cloud);\r
- } else if(data[0].equals("10") && data.length <= 15){\r
- // Some variable\r
- Element e = model.getElement(data[2].replace("\"", "").trim());\r
- if(e != null && e instanceof Variable) {\r
- Variable v = (Variable) e;\r
- if(v.getExpressions().get(0).getExpression().startsWith("INTEG (") && !(e instanceof Stock)) {\r
- // Stock\r
- Stock s = new Stock();\r
- s.setName(v.getName());\r
- s.setUnits(v.getUnits());\r
- s.setComments(v.getComments());\r
- s.setExpressions(v.getExpressions());\r
- model.removeElement(e);\r
- e = s;\r
- model.addElement(view, e);\r
- }\r
- }\r
-\r
- e.setX(Integer.parseInt(data[3]) / SCALE); \r
- e.setY(Integer.parseInt(data[4]) / SCALE); \r
- elementNumbers.put(data[1], e);\r
- model.relocateElement(view, e);\r
- } else if(data[0].equals("10") && data.length > 15){\r
- // TODO: Ghost\r
- // for now, direct back to the original element\r
- Element originalElement = model.getElement(data[2].replace("\"", ""));\r
- if(originalElement != null) {\r
- elementNumbers.put(data[1], originalElement);\r
- ghostNumbers.add(data[1]);\r
- }\r
- }\r
- \r
- i++;\r
- }\r
- i--;\r
- \r
- // Find the first variable that is connected to an empty valve\r
- for(String[] connectionData : connections) {\r
- if(!connectionData[9].equals("64"))\r
- continue; // not dependency\r
- String[] end = emptyValves.get(connectionData[3]);\r
- if(end != null && elementNumbers.get(connectionData[3]) == null) {\r
- // Use the connected element to create a valve and give it a name \r
- Element start = elementNumbers.get(connectionData[2]);\r
- if(start == null)\r
- continue;\r
- \r
- Valve valve = new Valve();\r
- valve.setName(start.getName() + " Rate");\r
- valve.setX(Integer.parseInt(end[3]) / SCALE); \r
- valve.setY(Integer.parseInt(end[4]) / SCALE);\r
- \r
- model.addElement(view, valve);\r
- elementNumbers.put(connectionData[3], valve);\r
- valve.setUnits("");\r
- valve.setComments("");\r
- }\r
- }\r
- \r
- \r
- \r
- for(String[] connectionData : connections) {\r
- \r
- Element start = elementNumbers.get(connectionData[2]);\r
- Element end = elementNumbers.get(connectionData[3]);\r
- // Discard connection if one of the ends is null\r
- if(start == null || end == null)\r
- continue;\r
- \r
- \r
- Connection connection; \r
- if(connectionData[9].equals("64")) {\r
- // Dependency\r
- Point2D startPoint = new Point2D.Double(start.getX(), start.getY());\r
- Point2D endPoint = new Point2D.Double(end.getX(), end.getY());\r
- String controlX = connectionData[13].substring(connectionData[13].indexOf("(") + 1);\r
- String controlY = connectionData[14].substring(0, connectionData[14].indexOf(")"));\r
- Point2D controlPoint = new Point2D.Double(Double.parseDouble(controlX) / SCALE, Double.parseDouble(controlY) / SCALE);\r
- \r
- if(ghostNumbers.contains(connectionData[2]) ||\r
- ghostNumbers.contains(connectionData[3])) {\r
- connection = new Dependency();\r
- } else {\r
- double angle = Dependency.angleOfArc(\r
- startPoint.getX(), startPoint.getY(),\r
- controlPoint.getX(), controlPoint.getY(),\r
- endPoint.getX(), endPoint.getY());\r
-\r
- connection = new Dependency(angle);\r
- }\r
- \r
- } else {\r
- // Flow\r
- connection = new Flow();\r
- if(connectionData[4].equals("100")) {\r
- // Flip the flow\r
- Element temp = start;\r
- start = end;\r
- end = temp;\r
- }\r
- }\r
- connection.setStart(start);\r
- connection.setEnd(end);\r
- model.addConnection(connection);\r
- }\r
- \r
- \r
- // Generate expressions for empty valves \r
- for(String key : emptyValves.keySet()) {\r
- Element e = elementNumbers.get(key);\r
- if(e instanceof Valve && ((Valve)e).getExpressions().isEmpty()) {\r
- Valve valve = (Valve)e;\r
- // Find the stock\r
- Stock stock = null;\r
- for(Connection connection : valve.getConnections()) {\r
- if(!(connection instanceof Flow))\r
- continue;\r
- if(connection.getStart().equals(valve) &&\r
- connection.getEnd() instanceof Stock) {\r
- stock = (Stock)connection.getEnd();\r
- break;\r
- }\r
- }\r
- \r
- // Create the expression. Use the expression of the stock, and undo the effect of other valves\r
- if(stock != null && stock instanceof Stock) {\r
- Expression expression = new Expression();\r
- \r
- StringBuilder sb = new StringBuilder();\r
- sb.append(((Stock)stock).getIntegralParts(stock.getExpressions().get(0))[0]);\r
- \r
- for(Connection c : stock.getConnections()) {\r
- if(c instanceof Flow) {\r
- if(c.getStart().equals(stock) && !c.getEnd().equals(valve)) {\r
- sb.append("+");\r
- sb.append(c.getEnd().getName());\r
- } else if(!c.getStart().equals(valve)){\r
- sb.append("-");\r
- sb.append(c.getStart().getName());\r
- }\r
- }\r
- }\r
- expression.setExpression(sb.toString());\r
- ArrayList<Expression> expressions = new ArrayList<Expression>();\r
- expressions.add(expression);\r
- valve.setExpressions(expressions);\r
- }\r
- }\r
- }\r
- }\r
- i++;\r
- }\r
-\r
- }\r
- \r
- private static void getOthertData(Model model, String otherData) {\r
- \r
- }\r
- \r
- private static void setAllSubscripts(Model model) {\r
- \r
- // Set subscripts for all elements\r
- ArrayList<Element> elements = new ArrayList<Element>();\r
- elements.addAll(model.getUnlocatedElements());\r
- for(View view : model.getViews()) {\r
- elements.addAll(view.getElements());\r
- }\r
- \r
- for(Element e : elements) { \r
- if(!(e instanceof Variable))\r
- continue;\r
- Variable v = (Variable)e;\r
- v.initializeSubscripts(model);\r
- }\r
- }\r
- \r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.mdlImport.ImportUtils;\r
-\r
-public class Auxiliary extends Variable {\r
-\r
- @Override\r
- public Resource getExpression(WriteGraph graph, Expression expression) throws DatabaseException {\r
- \r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource e = GraphUtils.create2(graph, \r
- sr.NormalExpression,\r
- sr.Expression_equation, ImportUtils.escapeExpression(expression.getExpression()).trim());\r
- return e;\r
- }\r
-\r
- @Override\r
- public void write(WriteGraph graph, Resource parent, double xOffset,\r
- double yOffset) {\r
- if(parent == null || graph == null)\r
- return;\r
- \r
- try {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(!graph.isInstanceOf(parent, sr.Configuration))\r
- return;\r
- createVariable(graph, parent, sr.Auxiliary, sr.AuxiliarySymbol, xOffset, yOffset);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.utils.OrderedSetUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.diagram.stubs.DiagramResource;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.sysdyn.SysdynResource;\r
-\r
-public class Cloud extends Element {\r
-\r
- @Override\r
- public void write(WriteGraph graph, Resource parent, double xOffset,\r
- double yOffset) {\r
- if(parent == null || graph == null)\r
- return;\r
- \r
- try {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph); \r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- DiagramResource dr = DiagramResource.getInstance(graph);\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
- \r
- if(!graph.isInstanceOf(parent, sr.Configuration))\r
- return;\r
- \r
- Resource diagram = graph.getSingleObject(parent, mr.CompositeToDiagram);\r
-\r
- if(diagram == null)\r
- return;\r
- \r
- Resource cloud = GraphUtils.create2(graph, \r
- sr.Cloud);\r
-\r
- graph.claim(parent, l0.ConsistsOf, cloud);\r
-\r
- \r
-\r
- Resource symbol = GraphUtils.create2(graph, \r
- sr.CloudSymbol,\r
- mr.ElementToComponent, cloud);\r
-\r
- double[] transform = {1.0, 0.0, 0.0, 1.0, getX() + xOffset, getY() + yOffset};\r
- graph.claimLiteral(symbol, dr.HasTransform, g2d.Transform, transform);\r
-\r
- OrderedSetUtils.add(graph, diagram, symbol);\r
-\r
- setResource(cloud);\r
-\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.utils.OrderedSetUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.diagram.stubs.DiagramResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.SysdynResource;\r
-\r
-public abstract class Connection implements IWriteableMDLObject {\r
- protected Element start, end;\r
- \r
- public Resource writeConnection(WriteGraph graph, Resource configuration, Resource connectionType, Resource connectionSymbol) throws DatabaseException {\r
- if(configuration == null || graph == null \r
- || start.getResource() == null || end.getResource() == null) {\r
- return null;\r
- }\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph); \r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- DiagramResource dr = DiagramResource.getInstance(graph);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
- \r
- Resource diagram = graph.getPossibleObject(configuration, mr.CompositeToDiagram);\r
- Resource startElement = graph.getPossibleObject(start.getResource(), mr.ComponentToElement);\r
- Resource endElement = graph.getPossibleObject(end.getResource(), mr.ComponentToElement);\r
- if(diagram == null || startElement == null || endElement == null)\r
- return null;\r
- \r
- \r
- if(connectionType == null)\r
- connectionType = sr.Dependency;\r
- \r
- if(connectionSymbol == null)\r
- connectionSymbol = sr.DependencyConnection;\r
- \r
- // Build the connection to configuration\r
- Resource connection = GraphUtils.create2(graph, \r
- connectionType,\r
- sr.Variable_HasHead, end.getResource(),\r
- sr.Variable_HasTail, start.getResource(),\r
- l0.PartOf, configuration);\r
- graph.claim(connection, mr.Mapped, connection);\r
- \r
- \r
- // Build diagram connectors and connection\r
- Resource tailConnector = GraphUtils.create2(graph, \r
- dr.Connector,\r
- sr.HasTailTerminal, startElement);\r
- \r
- Resource headConnector = GraphUtils.create2(graph,\r
- dr.Connector,\r
- sr.HasHeadTerminal, endElement,\r
- dr.AreConnected, tailConnector);\r
- \r
- Resource diagramConnection = GraphUtils.create2(graph, \r
- connectionSymbol,\r
- sr2.HasConnectionType, sr.SysdynConnectionType,\r
- mr.DiagramConnectionToConnection, connection,\r
- dr.HasArrowConnector, headConnector,\r
- dr.HasPlainConnector, tailConnector);\r
- \r
- OrderedSetUtils.add(graph, diagram, diagramConnection);\r
- \r
- return connection;\r
- }\r
-\r
- public Element getStart() {\r
- return start;\r
- }\r
-\r
- public void setStart(Element start) {\r
- this.start = start;\r
- }\r
-\r
- public Element getEnd() {\r
- return end;\r
- }\r
-\r
- public void setEnd(Element end) {\r
- this.end = end;\r
- }\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.sysdyn.SysdynResource;\r
-\r
-public class Dependency extends Connection {\r
- \r
- private double angle;\r
- \r
- public Dependency() {\r
- this(-0.1);\r
- }\r
- \r
- public Dependency(double angle) {\r
- this.angle = angle; \r
- }\r
-\r
- @Override\r
- public void write(WriteGraph graph, Resource parent) {\r
- if(parent == null || graph == null || start == null || end == null)\r
- return;\r
- try {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource connection = writeConnection(graph, parent, sr.Dependency, sr.DependencyConnection);\r
-\r
- if(connection != null) {\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- Resource diagramConnection = graph.getSingleObject(connection, mr.ConnectionToDiagramConnection);\r
- graph.claimLiteral(diagramConnection, sr.Dependency_angle, angle);\r
- }\r
-\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- }\r
-\r
- public double getAngle() {\r
- return angle;\r
- }\r
-\r
- public void setAngle(double angle) {\r
- this.angle = angle;\r
- }\r
- \r
- \r
- \r
- /**\r
- * Returns an angle in radians between straight line from (x0,y0) to (x2,y2)\r
- * and an arc from (x0,y0) to (x2,y2) thru (x1,y1). The angle\r
- * is measured at (x0,y0) and is between -PI and PI.\r
- */\r
- public static double angleOfArc(\r
- double x0, double y0, \r
- double x1, double y1,\r
- double x2, double y2) {\r
- double dx0 = x1-x0;\r
- double dy0 = y1-y0;\r
- double dx1 = x1-x2;\r
- double dy1 = y1-y2;\r
- double dx = x2-x0;\r
- double dy = y2-y0;\r
- // Length of cross product (p1-p0)x(p2-p0)\r
- double dd = dx0*dy - dy0*dx; \r
- \r
- if(Math.abs(dd) < 1e-6) // Points are (almost) collinear\r
- return 0.0;\r
- else { \r
- // (p1-p0)*(p1-p2) / dd\r
- double offset = (dx0*dx1 + dy0*dy1) / dd;\r
- double angle = Math.PI*0.5 - Math.atan(offset);\r
- if(dd > 0.0)\r
- angle = angle-Math.PI;\r
- return angle;\r
- \r
- }\r
- }\r
-\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import java.util.ArrayList;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-\r
-public abstract class Element implements IWriteableMDLElement {\r
- \r
- protected int x, y;\r
- protected Resource resource;\r
- protected String name;\r
- protected ArrayList<Connection> connections;\r
- \r
- protected Resource getExpression(WriteGraph graph, Expression expression)\r
- throws DatabaseException {\r
- return null;\r
- } \r
- \r
- public int getX() {\r
- return x;\r
- }\r
-\r
- public void setX(int x) {\r
- this.x = x;\r
- }\r
-\r
- public int getY() {\r
- return y;\r
- }\r
-\r
- public void setY(int y) {\r
- this.y = y;\r
- }\r
-\r
- public String getName() {\r
- if(name == null)\r
- return "Name";\r
- return name;\r
- }\r
-\r
- public void setName(String name) {\r
- this.name = name;\r
- }\r
-\r
- public Resource getResource() {\r
- return resource;\r
- }\r
-\r
- public void setResource(Resource resource) {\r
- this.resource = resource;\r
- }\r
- \r
- public ArrayList<Connection> getConnections() {\r
- if(connections == null)\r
- connections = new ArrayList<Connection>();\r
- return connections;\r
- }\r
-\r
- public void setConnections(ArrayList<Connection> connections) {\r
- this.connections = connections;\r
- }\r
- \r
- public void addConnection(Connection connection) {\r
- getConnections().add(connection);\r
- }\r
-}\r
-\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-\r
-public class EquivalenceSubscript extends Subscript {\r
- \r
- public String getEquivalentToName() {\r
- String name = "";\r
- if(expressions != null && expressions.get(0) != null) {\r
- name = expressions.get(0).getExpression().trim();\r
- }\r
- return name;\r
- }\r
-\r
- public void setEquivalentTo(Subscript equivalentTo) {\r
- setExpressions(equivalentTo.getExpressions());\r
- }\r
-\r
- @Override\r
- public void write(WriteGraph graph, Resource parent, double xOffset,\r
- double yOffset) {\r
- super.write(graph, parent, xOffset, yOffset);\r
- }\r
-\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-\r
-public class Expression {\r
- private String range, expression;\r
- \r
- @Override\r
- public String toString() {\r
- return (range != null ? "[" + range + "]: " : "") + expression; \r
- }\r
-\r
- public String getRange() {\r
- return range;\r
- }\r
-\r
- public void setRange(String range) {\r
- this.range = range;\r
- }\r
-\r
- public String getExpression() {\r
- if(expression == null)\r
- return "";\r
- return expression;\r
- }\r
-\r
- public void setExpression(String expression) {\r
- this.expression = expression;\r
- }\r
- \r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.mdlImport.ImportUtils;\r
-\r
-public class Function extends Variable {\r
-\r
- @Override\r
- public void write(WriteGraph graph, Resource parent, double xOffset,\r
- double yOffset) {\r
- if(parent == null || graph == null)\r
- return;\r
- \r
- try {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(!graph.isInstanceOf(parent, sr.SysdynModel))\r
- return;\r
- Layer0 l0 = Layer0.getInstance(graph); \r
- \r
- Resource function = GraphUtils.create2(graph, \r
- sr.SysdynModelicaFunction,\r
- l0.HasName, ImportUtils.escapeName(this.getName()));\r
- \r
- if(comments != null && comments.length() > 0)\r
- graph.claimLiteral(function, l0.HasDescription, comments);\r
- \r
- if(expressions != null && expressions.get(0) != null) {\r
- StringBuilder sb = new StringBuilder();\r
- sb.append(" input Real a;\n");\r
- sb.append(" output Real result;\n");\r
- sb.append("algorithm\n");\r
- sb.append(" result := interpolate(a, " + expressions.get(0).getExpression() + ");");\r
- graph.claimLiteral(function, sr.SysdynModelicaFunction_modelicaFunctionCode, sb.toString());\r
- }\r
-\r
- graph.claim(parent, l0.ConsistsOf, function);\r
- resource = function;\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- }\r
-\r
-\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-\r
-public interface IWriteableMDLElement {\r
-\r
- /**\r
- * Writes an element with coordinates (variable, cloud) to the given resource.\r
- * \r
- * Offsets determine where the parent view is located in the combined diagram\r
- * \r
- * @param graph WriteGraph\r
- * @param parent The resource where the object is located\r
- * @param xOffset xOffset of the view in the diagram\r
- * @param yOffset yOffset of the view in the diagram\r
- */\r
- public void write(WriteGraph graph, Resource parent, double xOffset, double yOffset);\r
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-\r
-public interface IWriteableMDLObject {\r
- \r
- /**\r
- * Writes an object with no coordinates (connection, model, view) to the given resource\r
- * \r
- * @param graph WriteGraph\r
- * @param parent The resource where the object is located\r
- */\r
- public void write(WriteGraph graph, Resource parent);\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import java.util.ArrayList;\r
-import java.util.HashMap;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.utils.ModelUtils;\r
-\r
-public class Model implements IWriteableMDLObject {\r
-\r
- private String name, timeUnit, saveper;\r
- private double startTime = 0, endTime = 10, timeStep = 1;\r
- \r
- private HashMap<String, Element> elementMap = new HashMap<String, Element>();\r
- private ArrayList<Subscript> subscripts = new ArrayList<Subscript>();\r
- private ArrayList<Function> functions = new ArrayList<Function>();\r
- private ArrayList<Connection> connections = new ArrayList<Connection>();\r
- private ArrayList<View> views = new ArrayList<View>();\r
- private ArrayList<Element> unlocatedElements = new ArrayList<Element>();\r
- \r
- public void addElement(Element element) {\r
- if(element instanceof Subscript)\r
- addSubscript((Subscript)element);\r
- else if(element instanceof Function)\r
- addFunction((Function)element);\r
- else\r
- unlocatedElements.add(element);\r
- if(element.getName() != null)\r
- elementMap.put(element.getName(), element);\r
- }\r
- \r
- public void addSubscript(Subscript subscript) {\r
- subscripts.add(subscript);\r
- }\r
- \r
- public void addFunction(Function function) {\r
- functions.add(function);\r
- }\r
- \r
- public void addElement(View view, Element element) {\r
- if(element instanceof Subscript)\r
- addSubscript((Subscript)element);\r
- else {\r
- if(unlocatedElements.contains(element))\r
- unlocatedElements.remove(element);\r
- view.addElement(element);\r
- }\r
- if(element.getName() != null)\r
- elementMap.put(element.getName(), element);\r
- }\r
- \r
- public void relocateElement(View view, Element element) {\r
- if(unlocatedElements.contains(element))\r
- unlocatedElements.remove(element);\r
- for(View v : views) {\r
- if(v.getElements().contains(element))\r
- v.getElements().remove(element);\r
- }\r
- view.addElement(element);\r
- }\r
- \r
- public void removeElement(Element element) {\r
- if(unlocatedElements.contains(element))\r
- unlocatedElements.remove(element);\r
- \r
- for(View view : views) {\r
- if(view.getElements().contains(element)) {\r
- view.getElements().remove(element);\r
- }\r
- }\r
- \r
- // just to be sure: loop the whole elementMap and don't trust the element's name\r
- String toBeRemoved = null;\r
- for(String key : elementMap.keySet()) {\r
- if(element.equals(elementMap.get(key))) {\r
- toBeRemoved = key;\r
- break;\r
- }\r
- }\r
- if(toBeRemoved != null)\r
- elementMap.remove(toBeRemoved);\r
- }\r
- \r
- public ArrayList<Element> getUnlocatedElements() {\r
- return unlocatedElements;\r
- }\r
- \r
- public Element getElement(String name) {\r
- return elementMap.get(name);\r
- }\r
- \r
- public void addConnection(Connection connection) {\r
- connections.add(connection);\r
- if(connection.getStart() != null &&\r
- !connection.getStart().getConnections().contains(connection)) {\r
- connection.getStart().addConnection(connection);\r
- }\r
- if(connection.getEnd() != null &&\r
- !connection.getEnd().getConnections().contains(connection)) {\r
- connection.getEnd().addConnection(connection);\r
- }\r
- }\r
- \r
- public ArrayList<Connection> getConnections() {\r
- return connections;\r
- }\r
- \r
- public ArrayList<Subscript> getSubscripts() {\r
- return subscripts;\r
- }\r
-\r
- public String getName() {\r
- if(name == null)\r
- return "ModelName";\r
- return name;\r
- }\r
-\r
- public void setName(String name) {\r
- this.name = name;\r
- }\r
-\r
- public String getTimeUnit() {\r
- return timeUnit;\r
- }\r
-\r
- public void setTimeUnit(String timeUnit) {\r
- this.timeUnit = timeUnit;\r
- }\r
-\r
- public String getSaveper() {\r
- return saveper;\r
- }\r
-\r
- public void setSaveper(String saveper) {\r
- this.saveper = saveper;\r
- }\r
-\r
- public double getStartTime() {\r
- return startTime;\r
- }\r
-\r
- public void setStartTime(double startTime) {\r
- this.startTime = startTime;\r
- }\r
-\r
- public double getEndTime() {\r
- return endTime;\r
- }\r
-\r
- public void setEndTime(double endTime) {\r
- this.endTime = endTime;\r
- }\r
-\r
- public double getTimeStep() {\r
- return timeStep;\r
- }\r
-\r
- public void setTimeStep(double timeStep) {\r
- this.timeStep = timeStep;\r
- }\r
-\r
- public HashMap<String, Element> getElementMap() {\r
- return elementMap;\r
- }\r
-\r
- public void setElementMap(HashMap<String, Element> elementMap) {\r
- this.elementMap = elementMap;\r
- }\r
-\r
- public void setSubscripts(ArrayList<Subscript> subscripts) {\r
- this.subscripts = subscripts;\r
- }\r
-\r
- public void setConnections(ArrayList<Connection> connections) {\r
- this.connections = connections;\r
- }\r
- \r
- public void addView(View view) {\r
- views.add(view);\r
- }\r
- \r
- public ArrayList<View> getViews() {\r
- return views;\r
- }\r
-\r
- /**\r
- * Write the model to a project\r
- * @param graph WriteGraph\r
- * @param parent Project resource\r
- */\r
- @Override\r
- public void write(WriteGraph graph, Resource parent) {\r
- if(parent == null || graph == null)\r
- return;\r
- \r
- try {\r
- \r
- \r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SimulationResource simu = SimulationResource.getInstance(graph);\r
-\r
- Resource model = ModelUtils.createModelAt(graph, parent);\r
- graph.claimLiteral(model, l0.HasLabel, getName());\r
- graph.claimLiteral(model, sr.SysdynModel_startTime, startTime);\r
- graph.claimLiteral(model, sr.SysdynModel_stopTime, endTime);\r
-
-\r
- Resource conf = graph.getSingleObject(model, simu.HasConfiguration);\r
- \r
- for(Subscript s : subscripts) {\r
- s.write(graph, conf, 0, 0);\r
- }\r
-\r
- // Create the grid n*n of views:\r
- \r
- double n = Math.sqrt(views.size());\r
- n = Math.ceil(n);\r
- \r
- int width = 0, height = 0;\r
- for(View v : views) {\r
- if(v.getWidth() > width)\r
- width = v.getWidth();\r
- if(v.getHeight() > height)\r
- height = v.getHeight();\r
- }\r
-\r
- for(int i = 0; i < n; i++) {\r
- for(int j = 0; j < n; j++) {\r
- int index = i * (int)n + j;\r
- if(index < views.size()) {\r
- View v = views.get(index);\r
- v.setxOffset(width * j);\r
- v.setyOffset(height * i);\r
- v.write(graph, conf);\r
- }\r
- }\r
- }\r
- \r
- for(Element e : unlocatedElements) {\r
- e.write(graph, conf, 0, 0);\r
- }\r
-\r
- for(Connection c : connections) {\r
- c.write(graph, conf);\r
- }\r
- \r
- for(Function f : functions) {\r
- f.write(graph, model, 0, 0);\r
- }\r
-\r
-\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- \r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-\r
-public class ModelControl extends Variable {\r
-\r
-\r
-\r
- @Override\r
- public Resource getExpression(WriteGraph graph, Expression expression)\r
- throws DatabaseException {\r
- return null;\r
- }\r
-\r
- @Override\r
- public void write(WriteGraph graph, Resource parent, double xOffset,\r
- double yOffset) {\r
- // TODO Auto-generated method stub\r
- \r
- }\r
-\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.mdlImport.ImportUtils;\r
-\r
-public class Stock extends Variable {\r
-\r
- @Override\r
- public Resource getExpression(WriteGraph graph, Expression expression) throws DatabaseException { \r
-\r
- String integralEquation = ImportUtils.escapeExpression(getIntegralParts(expression)[1]);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource e = GraphUtils.create2(graph, \r
- sr.StockExpression,\r
- sr.StockExpression_initialEquation, integralEquation);\r
- \r
- return e;\r
- }\r
- \r
- public String[] getIntegralParts(Expression expression) {\r
- // Does not work, if the integral has some other logic than +inflows -outflows!\r
- \r
- // Parsing the possible functions. Searching ',' that divides the INTEG -function\r
- int parenthesiscount = 0;\r
- int location = 0;\r
- char[] charArray = expression.getExpression().toCharArray();\r
- for(int i = 0; i < charArray.length; i++) {\r
- char c = charArray[i];\r
- if(c == '(')\r
- parenthesiscount++;\r
- else if(c == ')')\r
- parenthesiscount--;\r
- else if(c == ',' && parenthesiscount == 1) {\r
- location = i + 1;\r
- break;\r
- }\r
- }\r
- \r
- String exp = expression.getExpression();\r
- String initialEquation = exp.substring(location, exp.lastIndexOf(')')).trim();\r
- String integral = exp.substring(exp.indexOf("(") + 1, location - 1).trim();\r
- \r
- \r
- return new String[] {integral, initialEquation};\r
- }\r
-\r
- @Override\r
- public void write(WriteGraph graph, Resource parent, double xOffset,\r
- double yOffset) {\r
- if(parent == null || graph == null)\r
- return;\r
- \r
- try {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(!graph.isInstanceOf(parent, sr.Configuration))\r
- return;\r
- createVariable(graph, parent, sr.Stock, sr.StockSymbol, xOffset, yOffset);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- }\r
-\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import java.util.ArrayList;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-\r
-public class Subscript extends Variable {\r
-\r
- @Override\r
- public Resource getExpression(WriteGraph graph, Expression expression)\r
- throws DatabaseException {\r
- return null;\r
- }\r
-\r
- @Override\r
- public void write(WriteGraph graph, Resource parent, double xOffset,\r
- double yOffset) {\r
- if(parent == null || graph == null)\r
- return;\r
- \r
- try {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(!graph.isInstanceOf(parent, sr.Configuration))\r
- return;\r
- Layer0 l0 = Layer0.getInstance(graph); \r
- ArrayList<Resource> enumerationIndexes = new ArrayList<Resource>();\r
- if(expressions != null && expressions.get(0) != null) {\r
- String[] indexes = expressions.get(0).getExpression().split(",");\r
- for(String s : indexes) {\r
- Resource ei = GraphUtils.create2(graph, \r
- sr.EnumerationIndex,\r
- l0.HasName, s.trim());\r
- enumerationIndexes.add(ei);\r
- }\r
- }\r
-\r
- Resource enumeration = GraphUtils.create2(graph, \r
- sr.Enumeration,\r
- l0.HasName, this.getName(),\r
- sr.Enumeration_enumerationIndexList, ListUtils.create(graph, enumerationIndexes));\r
-\r
- graph.claim(parent, l0.ConsistsOf, enumeration);\r
-\r
- resource = enumeration;\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.mdlImport.ImportUtils;\r
-\r
-public class Valve extends Variable {\r
-\r
- @Override\r
- public Resource getExpression(WriteGraph graph, Expression expression) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- String expressionString = ImportUtils.escapeExpression(expression.getExpression());\r
- Resource e = GraphUtils.create2(graph, \r
- sr.NormalExpression,\r
- sr.Expression_equation, expressionString.trim());\r
- return e;\r
- }\r
-\r
- @Override\r
- public void write(WriteGraph graph, Resource parent, double xOffset,\r
- double yOffset) {\r
- try {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(!graph.isInstanceOf(parent, sr.Configuration))\r
- return;\r
- createVariable(graph, parent, sr.Valve, sr.ValveSymbol, xOffset, yOffset);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import java.util.ArrayList;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.OrderedSetUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.diagram.stubs.DiagramResource;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.mdlImport.ImportUtils;\r
-\r
-public abstract class Variable extends Element {\r
- protected String units;\r
- protected String comments;\r
- protected ArrayList<Expression> expressions;\r
- protected ArrayList<Subscript> subscripts;\r
-\r
- private Double rangeStart, rangeEnd, rangeStep;\r
- \r
- protected void createVariable(WriteGraph graph, Resource configuration, Resource variableType, Resource symbolType, double xOffset, double yOffset) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph); \r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- DiagramResource dr = DiagramResource.getInstance(graph);\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
- \r
- Resource diagram = graph.getSingleObject(configuration, mr.CompositeToDiagram);\r
- if(diagram == null)\r
- return;\r
- \r
- // Make sure at least one expression exist\r
- if(getExpressions().isEmpty()) {\r
- Expression e = new Expression();\r
- e.setExpression("");\r
- getExpressions().add(e);\r
- }\r
- \r
- Resource variable = GraphUtils.create2(graph, \r
- variableType,\r
- l0.HasName, ImportUtils.escapeName(name));\r
- graph.claim(variable, mr.Mapped, variable);\r
-\r
- ArrayList<Resource> expressions = new ArrayList<Resource>();\r
- for(Expression e : getExpressions()) {\r
-\r
- // Get expression from the variable. They have different types\r
- Resource expression = getExpression(graph, e);\r
-\r
- if(e.getRange() != null) {\r
- graph.claimLiteral(expression, sr.Expression_arrayRange, "[" + e.getRange().trim() + "]");\r
- }\r
- expressions.add(expression);\r
- graph.claim(variable, l0.ConsistsOf, expression);\r
- }\r
- graph.claim(variable, sr.Variable_expressionList, ListUtils.create(graph, expressions));\r
-\r
- if(subscripts != null) {\r
- ArrayList<Resource> arrayIndexes = new ArrayList<Resource>();\r
- for(Subscript sub : subscripts) {\r
- if(sub.getResource() != null)\r
- arrayIndexes.add(sub.getResource());\r
- }\r
- graph.claim(variable, sr.Variable_arrayIndexesList, ListUtils.create(graph, arrayIndexes));\r
- }\r
- \r
- if(units != null && units.length() > 0)\r
- graph.claimLiteral(variable, sr.Variable_unit, units);\r
- if(comments != null && comments.length() > 0)\r
- graph.claimLiteral(variable, l0.HasDescription, comments);\r
- if(rangeStart != null)\r
- graph.claimLiteral(variable, sr.HasRangeStart, rangeStart);\r
- if(rangeEnd != null)\r
- graph.claimLiteral(variable, sr.HasRangeEnd, rangeEnd);\r
- if(rangeStep != null)\r
- graph.claimLiteral(variable, sr.HasRangeStep, rangeStep);\r
- \r
- graph.claim(configuration, l0.ConsistsOf, variable);\r
- \r
- \r
- Resource symbol = GraphUtils.create2(graph, \r
- symbolType,\r
- mr.ElementToComponent, variable);\r
- \r
- double[] transform = {1.0, 0.0, 0.0, 1.0, x + xOffset, y + yOffset};\r
- graph.claimLiteral(symbol, dr.HasTransform, g2d.Transform, transform);\r
- \r
- OrderedSetUtils.add(graph, diagram, symbol);\r
- \r
- resource = variable;\r
- }\r
- \r
- \r
- public String getUnits() {\r
- return units;\r
- }\r
-\r
- public void setUnits(String units) {\r
- this.units = units;\r
- }\r
-\r
- public String getComments() {\r
- return comments;\r
- }\r
-\r
- public void setComments(String comments) {\r
- this.comments = comments;\r
- }\r
-\r
- public ArrayList<Expression> getExpressions() {\r
- if(expressions == null) {\r
- expressions = new ArrayList<Expression>();\r
- }\r
- return expressions;\r
- }\r
-\r
- public void setExpressions(ArrayList<Expression> expressions) {\r
- this.expressions = expressions;\r
- }\r
-\r
- public ArrayList<Subscript> getSubscripts() {\r
- if(subscripts == null)\r
- subscripts = new ArrayList<Subscript>();\r
- return subscripts;\r
- }\r
-\r
- public void setSubscripts(ArrayList<Subscript> subscripts) {\r
- this.subscripts = subscripts;\r
- }\r
- \r
-\r
- public Double getRangeStart() {\r
- return rangeStart;\r
- }\r
-\r
- public void setRangeStart(Double rangeStart) {\r
- this.rangeStart = rangeStart;\r
- }\r
-\r
- public Double getRangeEnd() {\r
- return rangeEnd;\r
- }\r
-\r
- public void setRangeEnd(Double rangeEnd) {\r
- this.rangeEnd = rangeEnd;\r
- }\r
-\r
- public Double getRangeStep() {\r
- return rangeStep;\r
- }\r
-\r
- public void setRangeStep(Double rangeStep) {\r
- this.rangeStep = rangeStep;\r
- }\r
- \r
- /**\r
- * Use this to set subscripts after all elements have been read\r
- * \r
- * @param model The model where the variable is located\r
- */\r
- public void initializeSubscripts(Model model) {\r
- for(Expression ex : getExpressions()) {\r
- if(ex.getRange() != null) {\r
- \r
- // Subscripts exist, check that subscripts -array is initialized\r
- getSubscripts();\r
- \r
- String[] elements = ex.getRange().split(",");\r
- // Search the corresponding subscript for each element, if it has not been searched already\r
- for(int i = 0; i < elements.length; i++) {\r
- // The subscript has been defined, move to next\r
- if(subscripts.size() > i)\r
- continue;\r
- \r
- String element = elements[i].trim();\r
- for(Subscript sub : model.getSubscripts()) {\r
- if(sub.getName().equals(element)) {\r
- subscripts.add(sub);\r
- break;\r
- }\r
- for(String index : sub.getExpressions().get(0).getExpression().split(",")) {\r
- if(index.trim().equals(element)) {\r
- subscripts.add(sub);\r
- break;\r
- }\r
- }\r
- // Subscript was defined for this index in previous for-loop\r
- if(subscripts.size() == i + 1)\r
- break;\r
- }\r
- }\r
- }\r
- }\r
- }\r
-}\r
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
-\r
-import java.util.ArrayList;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-\r
-public class View implements IWriteableMDLObject {\r
- \r
- private int minX = 0, maxX = 0, minY = 0, maxY = 0;\r
- private double xOffset = 0, yOffset = 0;\r
- private String name, fontParameters;\r
- \r
- private ArrayList<Element> elements = new ArrayList<Element>();\r
- \r
-\r
- @Override\r
- public void write(WriteGraph graph, Resource parent) {\r
- xOffset = xOffset - minX;\r
- yOffset = yOffset - minY;\r
- for(Element e : elements) {\r
- e.write(graph, parent, xOffset, yOffset);\r
- }\r
- }\r
- \r
- public void addElement(Element e) {\r
- if(e instanceof Subscript ||\r
- e instanceof Function)\r
- return;\r
- \r
- if(e.getX()<minX)\r
- minX = e.getX();\r
- if(e.getX()>maxX)\r
- maxX = e.getX();\r
- if(e.getY()<minY)\r
- minY = e.getY();\r
- if(e.getY()>maxY)\r
- maxY = e.getY();\r
- this.elements.add(e);\r
- }\r
- \r
- public ArrayList<Element> getElements() {\r
- return elements;\r
- }\r
-\r
- public void setElements(ArrayList<Element> elements) {\r
- this.elements = elements;\r
- }\r
- \r
- public String getName() {\r
- return name;\r
- }\r
-\r
- public void setName(String name) {\r
- this.name = name;\r
- }\r
-\r
-\r
- public String getFontParameters() {\r
- return fontParameters;\r
- }\r
-\r
-\r
- public void setFontParameters(String fontParameters) {\r
- this.fontParameters = fontParameters;\r
- }\r
-\r
-\r
- public int getMinX() {\r
- return minX;\r
- }\r
-\r
- public void setMinX(int minX) {\r
- this.minX = minX;\r
- }\r
-\r
- public int getMaxX() {\r
- return maxX;\r
- }\r
-\r
- public void setMaxX(int maxX) {\r
- this.maxX = maxX;\r
- }\r
-\r
- public int getMinY() {\r
- return minY;\r
- }\r
-\r
- public void setMinY(int minY) {\r
- this.minY = minY;\r
- }\r
-\r
- public int getMaxY() {\r
- return maxY;\r
- }\r
-\r
- public void setMaxY(int maxY) {\r
- this.maxY = maxY;\r
- }\r
-\r
- public double getxOffset() {\r
- return xOffset;\r
- }\r
-\r
- public void setxOffset(double xOffset) {\r
- this.xOffset = xOffset;\r
- }\r
-\r
- public double getyOffset() {\r
- return yOffset;\r
- }\r
-\r
- public void setyOffset(double yOffset) {\r
- this.yOffset = yOffset;\r
- }\r
- \r
- public int getWidth() {\r
- return maxX - minX;\r
- }\r
- \r
- public int getHeight() {\r
- return maxY - minY;\r
- }\r
-}\r
--- /dev/null
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ * VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.modelImport;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.InputStreamReader;\r
+\r
+import org.simantics.sysdyn.modelImport.mdl.Declaration;\r
+import org.simantics.sysdyn.modelImport.mdl.Lookup;\r
+import org.simantics.sysdyn.modelImport.mdl.MdlModel;\r
+import org.simantics.sysdyn.modelImport.mdl.Sketch;\r
+import org.simantics.sysdyn.modelImport.mdl.SketchComment;\r
+import org.simantics.sysdyn.modelImport.mdl.SketchConnection;\r
+import org.simantics.sysdyn.modelImport.mdl.SketchObject;\r
+import org.simantics.sysdyn.modelImport.mdl.SketchValve;\r
+import org.simantics.sysdyn.modelImport.mdl.SketchVariable;\r
+import org.simantics.sysdyn.modelImport.mdl.Subscript;\r
+import org.simantics.sysdyn.modelImport.mdl.SubscriptVariable;\r
+import org.simantics.sysdyn.modelImport.mdl.Variable;\r
+import org.simantics.sysdyn.modelImport.model.Model;\r
+import org.simantics.sysdyn.modelImport.model.element.Connection;\r
+import org.simantics.sysdyn.modelImport.model.element.ModelVariable;\r
+import org.simantics.sysdyn.modelImport.model.element.Symbol;\r
+import org.simantics.sysdyn.modelImport.model.element.Shadow;\r
+import org.simantics.sysdyn.modelImport.model.element.Valve;\r
+\r
+public class MdlParser {\r
+\r
+ public static Model parse(File file) {\r
+ // generate a mdl model based on the contents of the file\r
+ MdlModel mdl;\r
+ try {\r
+ mdl = parseFile(file);\r
+ }\r
+ catch (Exception e) {\r
+ e.printStackTrace();\r
+ return null;\r
+ }\r
+ \r
+ System.err.println("model parsed");\r
+ \r
+ // generate a sysdyn model from the mdl model\r
+ \r
+ Model model = new Model(mdl.getName());\r
+\r
+ double offset = 0;\r
+\r
+ for (Subscript subscript : mdl.getAllSubscripts()) {\r
+ if (!subscript.isEquivalent())\r
+ model.addEnumeration(subscript.getEnumeration(mdl));\r
+ }\r
+ \r
+ for (Lookup lookup : mdl.getAllLookups()) {\r
+ model.addFunction(lookup.getFunction());\r
+ }\r
+ \r
+ try {\r
+ // add sketch labels and independent elements\r
+ for (Sketch sketch : mdl.getSketches()) {\r
+ \r
+ sketch.setOffset(0, offset);\r
+\r
+ //model.addSymbol(new Comment(0, offset, -1, -1, sketch.getName()));\r
+ \r
+ for (SketchComment comment : sketch.getComments()) {\r
+ Symbol symbol = comment.getSymbol(mdl, sketch);\r
+ if (symbol != null) {\r
+ comment.setModelObject(symbol);\r
+ model.addSymbol(symbol);\r
+ }\r
+ }\r
+ \r
+ for (SketchValve valve : sketch.getValves()) {\r
+ Valve symbol = valve.getSymbol(mdl, sketch);\r
+ if (symbol != null) {\r
+ valve.setModelObject(symbol);\r
+ model.addSymbol(symbol);\r
+ }\r
+ }\r
+ \r
+ for (SketchVariable variable : sketch.getNonShadowVariables()) {\r
+ ModelVariable symbol = variable.getSymbol(mdl, sketch);\r
+ if (symbol != null) {\r
+ variable.setModelObject(symbol);\r
+ model.addSymbol(symbol);\r
+ }\r
+ }\r
+ \r
+ offset += 200;\r
+ }\r
+ \r
+ }\r
+ catch (NullPointerException e) {\r
+ e.printStackTrace();\r
+ }\r
+ \r
+ // add dependent elements\r
+ for (Sketch sketch : mdl.getSketches()) {\r
+ for (SketchVariable variable : sketch.getShadowVariables()) {\r
+ ModelVariable original = model.getVariable(variable.getName());\r
+ if (original == null)\r
+ System.err.println("original variable not found for "+variable.getName());\r
+ Symbol symbol = original != null ? new Shadow(variable.getDimensions(sketch), original) : variable.getSymbol(mdl, sketch);\r
+ if (symbol != null) {\r
+ variable.setModelObject(symbol);\r
+ model.addSymbol(symbol);\r
+ }\r
+ }\r
+\r
+ for (SketchConnection connection : sketch.getConnections()) {\r
+ Connection conn = connection.getConnection(sketch);\r
+ if (conn != null) {\r
+ connection.setModelObject(conn);\r
+ model.addConnection(conn);\r
+ }\r
+ }\r
+ }\r
+ \r
+ // Set simulation parameters\r
+ \r
+ System.err.println("DONE");\r
+\r
+ return model;\r
+ }\r
+ \r
+ private static final String UTF_8 = "{UTF-8}";\r
+ private static final String SKETCH_VERSION = "V300";\r
+ private static final String SKETCH_START = "\\\\\\---///";\r
+ private static final String SKETCH_END = "///---\\\\\\";\r
+ \r
+ private static MdlModel parseFile(File file) \r
+ throws Exception {\r
+ \r
+ // strip the file suffix from file name\r
+ String name = file.getName();\r
+ if (file.getName().contains(".")) {\r
+ name = name.substring(0, name.indexOf('.'));\r
+ }\r
+ \r
+ MdlModel mdl = new MdlModel(name);\r
+ \r
+ // peek at the first line to see if we need to use UTF-8\r
+ BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));\r
+ String line = reader.readLine();\r
+\r
+ if (line == null) {\r
+ // file is empty, nothing to do here\r
+ reader.close();\r
+ return null;\r
+ }\r
+\r
+ if (line.startsWith(UTF_8)) {\r
+ reader.close();\r
+ reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));\r
+ // skip the first line\r
+ reader.readLine();\r
+ line = reader.readLine();\r
+ }\r
+\r
+ // START READING VARIABLE DATA\r
+\r
+ // keep track of the current category\r
+ String category = null;\r
+\r
+ do {\r
+ // skip empty lines\r
+ if (line.isEmpty()) \r
+ continue;\r
+\r
+ // combine the (possible) variable declaration into one line \r
+ StringBuilder buffer = new StringBuilder();\r
+ do {\r
+ // strip trailing '\' if present\r
+ buffer.append(line.endsWith("\\") ? line.substring(0, line.length()-1) : line);\r
+ // each variable declaration ends with '|'\r
+ if (line.endsWith("|"))\r
+ break;\r
+ } while ((line = reader.readLine()) != null);\r
+ String str = buffer.toString();\r
+\r
+ String cat;\r
+ Variable var;\r
+ Lookup lookup;\r
+ Subscript subscript;\r
+ \r
+ // parse the (possible) variable declaration\r
+ if ((cat = Declaration.parseCategory(str)) != null) {\r
+ category = cat;\r
+ }\r
+ else if ((var = Variable.getPossible(str)) != null) {\r
+ mdl.addVariable(var, category);\r
+ }\r
+ else if ((var = SubscriptVariable.getPossible(str)) != null) {\r
+ mdl.addSubscriptVariable((SubscriptVariable)var, category);\r
+ }\r
+ else if ((lookup = Lookup.getPossible(str)) != null) {\r
+ mdl.addLookup(lookup);\r
+ }\r
+ else if ((subscript = Subscript.getPossible(str)) != null) {\r
+ mdl.addSubscript(subscript);\r
+ }\r
+ else {\r
+ // if we got this far, the variable could not be parsed\r
+ throw new Exception("unrecognized variable "+str);\r
+ }\r
+\r
+ } while ((line = reader.readLine()) != null && !line.startsWith(SKETCH_START));\r
+\r
+ // END READING VARIABLE DATA\r
+\r
+ if (line == null) {\r
+ throw new Exception("unexpected end of file");\r
+ }\r
+\r
+ // START READING SKETCH DATA\r
+\r
+ // keep track of the current sketch\r
+ Sketch sketch = null;\r
+\r
+ do {\r
+ // skip empty lines\r
+ if (line.isEmpty())\r
+ continue;\r
+ \r
+ SketchObject so;\r
+\r
+ if (line.startsWith(SKETCH_START)) {\r
+ sketch = new Sketch();\r
+ mdl.addSketch(sketch);\r
+ }\r
+ else if (line.startsWith(SKETCH_VERSION)) {\r
+ // version declaration, nothing to do here\r
+ }\r
+ else if (line.startsWith("*")) {\r
+ sketch.setName(line.substring(1));\r
+ }\r
+ else if (line.startsWith("$")) {\r
+ // font declaration, nothing to do here\r
+ }\r
+ else if ((so = SketchConnection.getPossible(line)) != null) {\r
+ sketch.addConnection((SketchConnection)so);\r
+ }\r
+ else if ((so = SketchVariable.getPossible(line)) != null) {\r
+ sketch.addVariable((SketchVariable)so);\r
+ }\r
+ else if ((so = SketchValve.getPossible(line)) != null) {\r
+ SketchValve valve = (SketchValve)so;\r
+ // the next row after a valve should always the variable associated with the valve\r
+ SketchVariable attached = SketchVariable.getPossible(reader.readLine());\r
+ if (attached == null || !attached.isAttached()) {\r
+ throw new Exception("attached variable not found for valve");\r
+ }\r
+ valve.setAttached(attached);\r
+ sketch.addValve(valve);\r
+ }\r
+ else if ((so = SketchComment.getPossible(line)) != null) {\r
+ SketchComment comment = (SketchComment)so;\r
+ if (comment.hasTextLine()) {\r
+ comment.setText(reader.readLine());\r
+ }\r
+ sketch.addComment(comment);\r
+ }\r
+ else {\r
+ // if we got this far, the element could not be parsed\r
+ throw new Exception("unrecognized element "+line);\r
+ }\r
+\r
+ } while ((line = reader.readLine()) != null && !line.startsWith(SKETCH_END));\r
+\r
+ // END READING SKETCH DATA\r
+\r
+ if (line == null) {\r
+ throw new Exception("unexpected end of file");\r
+ }\r
+\r
+ // START READING OTHER DATA\r
+\r
+ do {\r
+ // TODO: is there anything relevant here?\r
+ } while ((line = reader.readLine()) != null);\r
+\r
+ // END READING OTHER DATA\r
+\r
+ reader.close();\r
+ return mdl;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.mdl.Lookup;\r
+import org.simantics.sysdyn.modelImport.mdl.MdlModel;\r
+\r
+public class MdlUtil {\r
+ \r
+ // most of this is based on the documentation of the .mdl file format \r
+ // available in http://www.vensim.com/documentation/24305.htm\r
+ \r
+ // some regular expressions that are used commonly in the parser\r
+ public static final String DBL = "-?\\d+(?:\\.\\d+)?";\r
+ public static final String DBL_G = "("+DBL+")";\r
+ public static final String INT = "-?\\d+";\r
+ public static final String INT_G = "("+INT+")";\r
+ \r
+ // matches a basic vensim name (starts with a letter, may contain any word \r
+ // characters and white space)\r
+ public static final String BASIC_NAME =\r
+ "[A-Za-z]\\w*(?:\\s+\\w+)*";\r
+ // matches a special vensim name (starts and ends with a quotation mark, \r
+ // may contain escaped special characters)\r
+ public static final String SPECIAL_NAME =\r
+ "\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"";\r
+ \r
+ // matches a vensim variable (either basic name or special name)\r
+ public static final String VARIABLE =\r
+ "("+BASIC_NAME+"|"+SPECIAL_NAME+")";\r
+ // matches a vensim variable inside an expression (basic name not followed \r
+ // by an open parenthesis or a special name)\r
+ public static final String VARIABLE_EXPRESSION =\r
+ "([A-Za-z](?![\\s\\w]*\\()\\w*(?:\\s+\\w+)*|"+SPECIAL_NAME+")";\r
+ // matches a vensim subscript variable (basic name with a list of indices)\r
+ public static final String SUBSCRIPT =\r
+ "("+BASIC_NAME+")\\[("+BASIC_NAME+"\\!?(?:,"+BASIC_NAME+"\\!?)*)\\]";\r
+ // matches a vensim function (basic name followed by an open parenthesis)\r
+ public static final String FUNCTION =\r
+ "("+BASIC_NAME+")\\s*\\(";\r
+ \r
+ public static String normalize(String str) {\r
+ // start by removing all tabs from the string, not really necessary \r
+ // but does make the equation cleaner\r
+ str = str.replaceAll("\t", "");\r
+\r
+ // normalize functions\r
+ str = normalizeFunctions(str);\r
+ // normalize variables\r
+ str = normalizeVariables(str);\r
+ \r
+ // replace inline operations\r
+ str = str.replaceAll(":AND:", " and ");\r
+ str = str.replaceAll(":OR:", " or ");\r
+\r
+ return str;\r
+ }\r
+ \r
+ private static String normalizeVariables(String expression) {\r
+ StringBuilder result = new StringBuilder();\r
+ int offset = 0;\r
+\r
+ Matcher matcher = Pattern.compile(VARIABLE_EXPRESSION).matcher(expression);\r
+ while (matcher.find()) {\r
+ result.append(expression.substring(offset, matcher.start()));\r
+\r
+ String variable = matcher.group(1);\r
+ \r
+ if (variable.equalsIgnoreCase("time")) {\r
+ result.append("time");\r
+ }\r
+ else if (variable.startsWith("\"") && variable.endsWith("\"")) {\r
+ result.append('\'');\r
+ result.append(variable.substring(1, variable.length() - 1));\r
+ result.append('\'');\r
+ }\r
+ else if (variable.contains("-")) {\r
+ result.append('\'');\r
+ result.append(variable);\r
+ result.append('\'');\r
+ }\r
+ else {\r
+ String[] parts = variable.split("\\s+");\r
+ for (int i = 0; i < parts.length; i++) {\r
+ if (i > 0)\r
+ result.append(' ');\r
+ result.append(parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1));\r
+ }\r
+ }\r
+ \r
+ offset = matcher.end();\r
+ }\r
+ if (offset < expression.length()) {\r
+ result.append(expression.substring(offset));\r
+ }\r
+ \r
+ return result.toString();\r
+ }\r
+ \r
+ private static String normalizeFunctions(String expression) {\r
+ StringBuilder result = new StringBuilder();\r
+ int offset = 0;\r
+\r
+ Matcher matcher = Pattern.compile(FUNCTION).matcher(expression);\r
+ while (matcher.find()) {\r
+ result.append(expression.substring(offset, matcher.start()));\r
+\r
+ String function = matcher.group(1);\r
+ \r
+ if (function.equalsIgnoreCase("sum")) {\r
+ // vensim "sum" is similar to modelica "sum" if operations \r
+ // are replaced with dot-operations (e.g. * with .*) inside\r
+ // the parameters\r
+ result.append("sum(");\r
+ int closing = expression.indexOf(')', matcher.end());\r
+ String parameters = expression.substring(matcher.end(), closing);\r
+ parameters = parameters.replaceAll("\\*", ".*");\r
+ result.append(parameters);\r
+ offset = closing;\r
+ }\r
+ else if (function.equalsIgnoreCase("if then else")) {\r
+ result.append("IFTHENELSE(");\r
+ offset = matcher.end();\r
+ }\r
+ else {\r
+ // this will also capitalize lookups, is this ok?\r
+ result.append(function.toUpperCase()+"(");\r
+ offset = matcher.end();\r
+ }\r
+ }\r
+ if (offset < expression.length()) {\r
+ result.append(expression.substring(offset));\r
+ }\r
+ \r
+ return result.toString();\r
+ }\r
+ \r
+ public static String finalize(String expression, MdlModel mdl) {\r
+ expression = expandIterations(expression, mdl);\r
+ expression = renameLookups(expression, mdl);\r
+ \r
+ return expression;\r
+ }\r
+ \r
+ private static String expandIterations(String expression, MdlModel mdl) {\r
+ StringBuilder result = new StringBuilder();\r
+ int offset = 0;\r
+\r
+ Matcher matcher = Pattern.compile(SUBSCRIPT).matcher(expression);\r
+ while (matcher.find()) {\r
+ result.append(expression.substring(offset, matcher.start()));\r
+ \r
+ String name = matcher.group(1);\r
+ String[] indices = matcher.group(2).split(",");\r
+ \r
+ result.append(name);\r
+ \r
+ result.append('[');\r
+ for (int i = 0; i < indices.length; i++) {\r
+ if (i > 0)\r
+ result.append(',');\r
+ \r
+ if (indices[i].endsWith("!")) {\r
+ String subscript = indices[i].substring(0, indices[i].length() - 1);\r
+ List<String> values = mdl.getSubscript(subscript).getValues(mdl);\r
+ result.append('{');\r
+ for (int j = 0; j < values.size(); j++) {\r
+ if (j > 0)\r
+ result.append(',');\r
+ result.append(values.get(j));\r
+ }\r
+ result.append('}');\r
+ }\r
+ else {\r
+ result.append(indices[i]);\r
+ }\r
+ }\r
+ result.append(']');\r
+ \r
+ offset = matcher.end();\r
+ }\r
+ if (offset < expression.length()) {\r
+ result.append(expression.substring(offset));\r
+ }\r
+ \r
+ return result.toString();\r
+ }\r
+ \r
+ private static String renameLookups(String expression, MdlModel mdl) {\r
+ StringBuilder result = new StringBuilder();\r
+ int offset = 0;\r
+\r
+ Matcher matcher = Pattern.compile(FUNCTION).matcher(expression);\r
+ while (matcher.find()) {\r
+ result.append(expression.substring(offset, matcher.start()));\r
+\r
+ String name = matcher.group(1);\r
+ \r
+ Lookup potential = mdl.getLookup(name);\r
+ \r
+ if (potential != null) {\r
+ System.err.println("found lookup "+name);\r
+ name = name.replaceAll("\\s+", "");\r
+ }\r
+ \r
+ result.append(name+"(");\r
+ offset = matcher.end();\r
+ }\r
+ if (offset < expression.length()) {\r
+ result.append(expression.substring(offset));\r
+ }\r
+ \r
+ return result.toString();\r
+ }\r
+ \r
+ public static String replaceSubscripts(String expression, String subscript, String replacement) {\r
+ StringBuilder result = new StringBuilder();\r
+ int offset = 0;\r
+ \r
+ Matcher matcher = Pattern.compile(SUBSCRIPT).matcher(expression);\r
+ while (matcher.find()) {\r
+ result.append(expression.substring(offset, matcher.start()));\r
+ \r
+ String name = matcher.group(1);\r
+ String[] indices = matcher.group(2).split(",");\r
+ \r
+ result.append(name);\r
+ \r
+ result.append('[');\r
+ for (int i = 0; i < indices.length; i++) {\r
+ if (i > 0)\r
+ result.append(',');\r
+ \r
+ if (indices[i].equals(subscript)) {\r
+ result.append(replacement);\r
+ }\r
+ else {\r
+ result.append(indices[i]);\r
+ }\r
+ }\r
+ result.append(']');\r
+ \r
+ offset = matcher.end();\r
+ }\r
+ if (offset < expression.length()) {\r
+ result.append(expression.substring(offset));\r
+ }\r
+ \r
+ return result.toString();\r
+ }\r
+ \r
+ public static String[] splitFunctionParameters(String str) {\r
+ ArrayList<String> list = new ArrayList<String>();\r
+\r
+ int i;\r
+ int last = 0;\r
+ int level = 0;\r
+ boolean comment = false;\r
+ boolean brackets = false;\r
+ \r
+ for (i = 0; i < str.length(); i++) {\r
+ char current = str.charAt(i);\r
+ if (current == '"')\r
+ // note that this does not currently support escaped quotation marks inside quoted variable names\r
+ comment = !comment;\r
+ else if (current == '[' && !comment)\r
+ brackets = true;\r
+ else if (current == ']' && !comment)\r
+ brackets = false;\r
+ else if (current == '(' && !comment && !brackets)\r
+ level++;\r
+ else if (current == ')' && !comment && !brackets)\r
+ level--;\r
+ else if (current == ',' && !comment && !brackets && level == 0) {\r
+ list.add(str.substring(last, i).trim());\r
+ last = i + 1;\r
+ }\r
+ }\r
+ if (last < i) {\r
+ list.add(str.substring(last, i).trim());\r
+ }\r
+ \r
+ return list.toArray(new String[list.size()]);\r
+ }\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+public abstract class Declaration {\r
+\r
+ private static final String CATEGORY = "\\*{56}\\s*\\.(\\S+)\\s*\\*{56}.*";\r
+ \r
+ protected static final String DECL_DELIM = "\\s*~\\s*";\r
+ protected static final String DECL_END = "\\s*\\|";\r
+ protected static final String DECL_UNIT = "([^~]*?)";\r
+ protected static final String DECL_DESC = "([^\\|]*?)";\r
+\r
+ protected static final String DECL_SUFFIX = \r
+ DECL_DELIM + DECL_UNIT + DECL_DELIM + DECL_DESC + DECL_END;\r
+ protected static final int declarationUnit = 1;\r
+ protected static final int declarationDescription = 2;\r
+ \r
+ private String name;\r
+ private String unit;\r
+ private String description;\r
+ \r
+ protected Declaration(String name) {\r
+ this.name = name;\r
+ }\r
+ \r
+ protected void parseSuffix(String suffix) \r
+ throws Exception {\r
+ Matcher matcher = Pattern.compile(DECL_SUFFIX).matcher(suffix);\r
+ if (!matcher.matches()) {\r
+ // this should not happen unless subclasses fail to construct their\r
+ // regular expressions properly\r
+ throw new Exception("could not parse declaration suffix "+suffix);\r
+ }\r
+ \r
+ unit = matcher.group(declarationUnit);\r
+ description = matcher.group(declarationDescription);\r
+ }\r
+ \r
+ public String getName() {\r
+ return name;\r
+ }\r
+ \r
+ public String getUnit() {\r
+ return unit;\r
+ }\r
+ \r
+ public String getDescription() {\r
+ return description;\r
+ }\r
+\r
+ public static String parseCategory(String line) {\r
+ Matcher matcher = Pattern.compile(CATEGORY).matcher(line);\r
+ return matcher.matches() ? matcher.group(1) : null;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+public interface IMdlObject {\r
+ \r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.expression.LookupExpression;\r
+import org.simantics.sysdyn.modelImport.model.support.Function;\r
+\r
+public class Lookup extends Declaration {\r
+ \r
+ private static final String LOOKUP_RANGE =\r
+ "\\[\\("+MdlUtil.DBL_G+","+MdlUtil.DBL_G+"\\)-\\("+MdlUtil.DBL_G+","+MdlUtil.DBL_G+"\\)\\]";\r
+ private static final String LOOKUP_POINTS =\r
+ "(\\("+MdlUtil.DBL+","+MdlUtil.DBL+"\\)(?:,\\("+MdlUtil.DBL+","+MdlUtil.DBL+"\\))*)";\r
+ private static final String LOOKUP =\r
+ "("+MdlUtil.BASIC_NAME+")\\s*\\(\\s*"+LOOKUP_RANGE+","+LOOKUP_POINTS+"\\s*\\)";\r
+ \r
+ private static final String LOOKUP_DECL = \r
+ LOOKUP+"("+DECL_SUFFIX+")"; \r
+ private static final int lookupName = 1;\r
+ private static final int lookupRangeXMin = 2;\r
+ private static final int lookupRangeYMin = 3;\r
+ private static final int lookupRangeXMax = 4;\r
+ private static final int lookupRangeYMax = 5;\r
+ private static final int lookupPoints = 6;\r
+ private static final int lookupSuffix = 7;\r
+ \r
+ private double xMin;\r
+ private double yMin;\r
+ private double xMax;\r
+ private double yMax;\r
+ private double[] points;\r
+ \r
+ private Function function;\r
+ \r
+ // TODO: generate functions from lookup variables\r
+\r
+ protected Lookup(String name, double xMin, double yMin, double xMax, double yMax, double[] points) {\r
+ super(name);\r
+ this.xMin = xMin;\r
+ this.yMin = yMin;\r
+ this.xMax = xMax;\r
+ this.yMax = yMax;\r
+ this.points = points;\r
+ }\r
+ \r
+ public static Lookup getPossible(String line) \r
+ throws Exception {\r
+ Matcher matcher = Pattern.compile(LOOKUP_DECL).matcher(line);\r
+ if (!matcher.matches()) {\r
+ return null;\r
+ }\r
+ \r
+ String name = matcher.group(lookupName).toUpperCase();\r
+ double xMin = Double.parseDouble(matcher.group(lookupRangeXMin));\r
+ double yMin = Double.parseDouble(matcher.group(lookupRangeYMin));\r
+ double xMax = Double.parseDouble(matcher.group(lookupRangeXMax));\r
+ double yMax = Double.parseDouble(matcher.group(lookupRangeYMax));\r
+ double[] points = parsePoints(matcher.group(lookupPoints));\r
+ \r
+ Lookup lookup = new Lookup(name, xMin, yMin, xMax, yMax, points);\r
+ lookup.parseSuffix(matcher.group(lookupSuffix));\r
+ return lookup;\r
+ }\r
+ \r
+ private static double[] parsePoints(String str) {\r
+ // a hack to remove the leading empty string otherwise produced by split()\r
+ str = str.replaceFirst("[(),]+", "");\r
+ String[] parts = str.split("[(),]+");\r
+ double[] points = new double[parts.length];\r
+ for (int i = 0; i < parts.length; i++) {\r
+ points[i] = Double.parseDouble(parts[i]);\r
+ }\r
+ return points;\r
+ }\r
+\r
+ public double getxMin() {\r
+ return xMin;\r
+ }\r
+\r
+ public double getyMin() {\r
+ return yMin;\r
+ }\r
+\r
+ public double getxMax() {\r
+ return xMax;\r
+ }\r
+\r
+ public double getyMax() {\r
+ return yMax;\r
+ }\r
+ \r
+ public double[] getPoints() {\r
+ return points;\r
+ }\r
+ \r
+ public Function getFunction() {\r
+ if (function != null) {\r
+ return function;\r
+ }\r
+ \r
+ StringBuilder body = new StringBuilder();\r
+ \r
+ // one input, one output\r
+ body.append("input Real i;\n");\r
+ body.append("output Real o;\n");\r
+ \r
+ // interpolate over the set of points\r
+ body.append("algorithm\n");\r
+ \r
+ body.append("o := interpolate(i, {");\r
+ for (int i = 0; i < points.length/2; i++) {\r
+ if (i > 0) {\r
+ body.append(',');\r
+ }\r
+ body.append('{').append(points[2*i]).append(',').append(points[2*i+1]).append('}');\r
+ }\r
+ body.append("});\n");\r
+ \r
+ function = new Function(getName().replaceAll("\\s+", ""), body.toString());\r
+ \r
+ return function;\r
+ }\r
+ \r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Set;\r
+\r
+public class MdlModel {\r
+ \r
+ private String name;\r
+ \r
+ private Map<String, Variable> variables;\r
+ private Map<String, ArrayList<Variable>> groups;\r
+ private Map<String, Lookup> lookups;\r
+ private Map<String, Subscript> subscripts;\r
+ private List<Sketch> sketches;\r
+ \r
+ public MdlModel(String name) {\r
+ this.name = name;\r
+ \r
+ this.variables = new HashMap<String, Variable>();\r
+ this.groups = new HashMap<String, ArrayList<Variable>>();\r
+ this.lookups = new HashMap<String, Lookup>();\r
+ this.subscripts = new HashMap<String, Subscript>();\r
+ this.sketches = new ArrayList<Sketch>();\r
+ }\r
+ \r
+ public String getName() {\r
+ return name;\r
+ }\r
+ \r
+ public void addVariable(Variable variable, String group) \r
+ throws Exception {\r
+ if (variables.get(variable.getName()) != null) {\r
+ throw new Exception("duplicate variable "+variable.getName());\r
+ }\r
+ \r
+ variables.put(variable.getName(), variable);\r
+ addGroup(variable, group);\r
+ }\r
+ \r
+ public void addSubscriptVariable(SubscriptVariable variable, String group) \r
+ throws Exception {\r
+ Variable original = variables.get(variable.getName());\r
+ if (original != null) {\r
+ if (!(original instanceof SubscriptVariable)) {\r
+ throw new Exception("incompatible type for variable "+variable.getName());\r
+ }\r
+ ((SubscriptVariable)original).addSubscriptVariable(variable);\r
+ }\r
+ else {\r
+ variables.put(variable.getName(), variable);\r
+ addGroup(variable, group);\r
+ }\r
+ }\r
+ \r
+ private void addGroup(Variable variable, String group) {\r
+ if (group != null) {\r
+ if (groups.get(group) == null) {\r
+ groups.put(group, new ArrayList<Variable>());\r
+ }\r
+ groups.get(group).add(variable);\r
+ }\r
+ }\r
+ \r
+ public Variable getVariable(String name) {\r
+ return variables.get(name);\r
+ }\r
+ \r
+ public Set<Variable> getAllVariables() {\r
+ return new HashSet<Variable>(variables.values());\r
+ }\r
+ \r
+ public void addLookup(Lookup lookup) \r
+ throws Exception {\r
+ if (lookups.get(lookup.getName()) != null) {\r
+ throw new Exception("duplicate lookup "+lookup.getName());\r
+ }\r
+ \r
+ lookups.put(lookup.getName(), lookup);\r
+ }\r
+ \r
+ public Lookup getLookup(String name) {\r
+ return lookups.get(name);\r
+ }\r
+ \r
+ public Set<Lookup> getAllLookups() {\r
+ return new HashSet<Lookup>(lookups.values());\r
+ }\r
+ \r
+ public void addSubscript(Subscript subscript) \r
+ throws Exception {\r
+ if (subscripts.get(subscript.getName()) != null) {\r
+ throw new Exception("duplicate subscript "+subscript.getName());\r
+ }\r
+ \r
+ // TODO: check if a subscript with the same values already exists\r
+ \r
+ subscripts.put(subscript.getName(), subscript);\r
+ }\r
+ \r
+ public Subscript getSubscript(String key) {\r
+ return subscripts.get(key);\r
+ }\r
+ \r
+ public Set<Subscript> getAllSubscripts() {\r
+ return new HashSet<Subscript>(subscripts.values());\r
+ }\r
+ \r
+ public Subscript resolveSubscript(List<String> values) {\r
+ return resolveSubscript(new HashSet<String>(values));\r
+ }\r
+ \r
+ public Subscript resolveSubscript(Set<String> values) {\r
+ // if one value is actually a subscript, expand it to its values\r
+ Set<String> all = new HashSet<String>();\r
+ for (String value : values) {\r
+ Subscript potential = subscripts.get(value);\r
+ if (potential != null) {\r
+ all.addAll(potential.getValues(this));\r
+ }\r
+ else {\r
+ all.add(value);\r
+ }\r
+ }\r
+ \r
+ // find the subscript that contains exactly the given set of values.\r
+ // only consider original subscripts (ignore equivalent subscripts)\r
+ for (Subscript subscript : getAllSubscripts()) {\r
+ if (!subscript.isEquivalent() && subscript.getValues(this).containsAll(all) && all.containsAll(subscript.getValues(this))) {\r
+ return subscript;\r
+ }\r
+ }\r
+ \r
+ // if an exact match could not be found, return null\r
+ return null;\r
+ }\r
+ \r
+ public void addSketch(Sketch sketch) {\r
+ sketches.add(sketch);\r
+ }\r
+ \r
+ public List<Sketch> getSketches() {\r
+ return sketches;\r
+ }\r
+ \r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+\r
+import org.simantics.sysdyn.modelImport.model.element.Symbol;\r
+\r
+public class Sketch {\r
+ \r
+ private String name;\r
+ \r
+ private boolean edgesOutOfDate;\r
+ public double topEdge = 0;\r
+ public double bottomEdge = 0;\r
+ public double leftEdge = 0;\r
+ public double rightEdge = 0;\r
+\r
+ private List<SketchComment> comments;\r
+ private List<SketchConnection> connections;\r
+ private List<SketchValve> valves;\r
+ private List<SketchVariable> variables;\r
+ \r
+ private HashMap<Integer, SketchObject> objects;\r
+ \r
+ public Sketch() {\r
+ edgesOutOfDate = true;\r
+ \r
+ comments = new ArrayList<SketchComment>();\r
+ connections = new ArrayList<SketchConnection>();\r
+ valves = new ArrayList<SketchValve>();\r
+ variables = new ArrayList<SketchVariable>();\r
+ \r
+ objects = new HashMap<Integer, SketchObject>();\r
+ }\r
+ \r
+ public String getName() {\r
+ return name;\r
+ }\r
+\r
+ public void setName(String name) {\r
+ this.name = name;\r
+ }\r
+ \r
+ private void updateEdges() {\r
+// if (edgesOutOfDate) {\r
+// boolean first = true;\r
+// for (SketchElement e : getAllElements()) {\r
+// topEdge = first ? e.getSysdynTopEdge() : Math.min(topEdge, e.getSysdynTopEdge());\r
+// bottomEdge = first ? e.getSysdynBottomEdge() : Math.max(bottomEdge, e.getSysdynBottomEdge());\r
+// leftEdge = first ? e.getSysdynLeftEdge() : Math.min(leftEdge, e.getSysdynLeftEdge());\r
+// rightEdge = first ? e.getSysdynRightEdge() : Math.max(rightEdge, e.getSysdynRightEdge());\r
+// first = false;\r
+// }\r
+// edgesOutOfDate = false;\r
+// }\r
+ }\r
+ \r
+ public double getTopEdge() {\r
+ updateEdges();\r
+ return topEdge;\r
+ }\r
+ \r
+ public double getBottomEdge() {\r
+ updateEdges();\r
+ return bottomEdge;\r
+ }\r
+ \r
+ public double getLeftEdge() {\r
+ updateEdges();\r
+ return leftEdge;\r
+ }\r
+ \r
+ public double getRightEdge() {\r
+ updateEdges();\r
+ return rightEdge;\r
+ }\r
+ \r
+ public double getWidth() {\r
+ updateEdges();\r
+ return rightEdge - leftEdge;\r
+ }\r
+ \r
+ public double getHeight() {\r
+ updateEdges();\r
+ return bottomEdge - topEdge;\r
+ }\r
+ \r
+ public void setOffset(double horizontal, double vertical) {\r
+ hOffset = horizontal;\r
+ vOffset = vertical;\r
+ }\r
+ \r
+ private double hOffset, vOffset;\r
+ \r
+ public double getHorizontalOffset() {\r
+ return hOffset;\r
+ }\r
+ \r
+ public double getVerticalOffset() {\r
+ return vOffset;\r
+ }\r
+ \r
+ public void addComment(SketchComment comment) {\r
+ comments.add(comment);\r
+ objects.put(comment.getId(), comment);\r
+ }\r
+ \r
+ public List<SketchComment> getComments() {\r
+ return comments;\r
+ }\r
+ \r
+ public void addConnection(SketchConnection connection) {\r
+ connections.add(connection);\r
+ objects.put(connection.getId(), connection);\r
+ }\r
+ \r
+ public List<SketchConnection> getConnections() {\r
+ return connections;\r
+ }\r
+ \r
+ public void addValve(SketchValve valve) {\r
+ valves.add(valve);\r
+ objects.put(valve.getId(), valve);\r
+ // replace the attached variable with the valve in order to redirect \r
+ // possible connections to the variable to the valve\r
+ objects.put(valve.getAttached().getId(), valve);\r
+ }\r
+ \r
+ public List<SketchValve> getValves() {\r
+ return valves;\r
+ }\r
+ \r
+ public void addVariable(SketchVariable variable) {\r
+ variables.add(variable);\r
+ objects.put(variable.getId(), variable);\r
+ }\r
+ \r
+ public List<SketchVariable> getVariables() {\r
+ return variables;\r
+ }\r
+ \r
+ public SketchObject getObject(int id) {\r
+ return objects.get(id);\r
+ }\r
+ \r
+ public List<SketchElement> getAllElements() {\r
+ ArrayList<SketchElement> list = new ArrayList<SketchElement>();\r
+ list.addAll(getComments());\r
+ list.addAll(getValves());\r
+ list.addAll(getVariables());\r
+ return list;\r
+ }\r
+ \r
+ public List<SketchVariable> getShadowVariables() {\r
+ List<SketchVariable> variables = new ArrayList<SketchVariable>();\r
+ for (SketchVariable var : getVariables()) {\r
+ if (!var.allowsIn()) {\r
+ variables.add(var);\r
+ }\r
+ }\r
+ return variables;\r
+ }\r
+ \r
+ public List<SketchVariable> getNonShadowVariables() {\r
+ List<SketchVariable> variables = new ArrayList<SketchVariable>();\r
+ variables.addAll(getVariables());\r
+ variables.removeAll(getShadowVariables());\r
+ return variables;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.model.element.Cloud;\r
+import org.simantics.sysdyn.modelImport.model.element.Comment;\r
+import org.simantics.sysdyn.modelImport.model.element.Symbol;\r
+\r
+public class SketchComment extends SketchElement {\r
+ \r
+ private static final String SKETCH_COMMENT =\r
+ "12,"+KEEP_I+KEEP_I+"("+ELEMENT_SUFFIX+")";\r
+ private static final int commentId = 1;\r
+ private static final int commentIcon = 2;\r
+ private static final int commentSuffix = 3;\r
+ \r
+ public enum CommentIcon {\r
+ CLOUD, OTHER\r
+ }\r
+ \r
+ private String text;\r
+ private CommentIcon icon;\r
+\r
+ protected SketchComment(int id, CommentIcon icon) {\r
+ super(id);\r
+ this.icon = icon;\r
+ }\r
+ \r
+ public static SketchComment getPossible(String line) \r
+ throws Exception {\r
+ Matcher matcher = Pattern.compile(SKETCH_COMMENT).matcher(line);\r
+ if (!matcher.matches()) {\r
+ return null;\r
+ }\r
+ \r
+ int id = Integer.parseInt(matcher.group(commentId));\r
+ \r
+ CommentIcon icon;\r
+ switch (Integer.parseInt(matcher.group(commentIcon))) {\r
+ case 48: icon = CommentIcon.CLOUD; break;\r
+ default: icon = CommentIcon.OTHER; break;\r
+ }\r
+ \r
+ SketchComment element = new SketchComment(id, icon);\r
+ element.parseSuffix(matcher.group(commentSuffix));\r
+ return element;\r
+ }\r
+\r
+ public String getText() {\r
+ return text;\r
+ }\r
+ \r
+ public void setText(String text) {\r
+ this.text = text;\r
+ }\r
+ \r
+ public CommentIcon getIcon() {\r
+ return icon;\r
+ }\r
+ \r
+ @Override\r
+ public Symbol getSymbol(MdlModel mdl, Sketch sketch) {\r
+ if (isInputOutput())\r
+ return new Comment(getDimensions(), "I/O objects are not supported");\r
+ \r
+ switch(icon) {\r
+ case CLOUD: return new Cloud(getDimensions(sketch));\r
+ case OTHER: return new Comment(getDimensions(sketch), text);\r
+ default: return null;\r
+ }\r
+ }\r
+ \r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.element.Connection;\r
+import org.simantics.sysdyn.modelImport.model.element.Dependency;\r
+import org.simantics.sysdyn.modelImport.model.element.Symbol;\r
+import org.simantics.sysdyn.modelImport.model.element.Flow;\r
+\r
+public class SketchConnection extends SketchObject {\r
+ \r
+ public enum ConnectionType {\r
+ ARROW, LINE_ARROW, LINE_SEGMENT, OTHER\r
+ }\r
+ \r
+ // some shorthands\r
+ private static final String KEEP_I = MdlUtil.INT_G+",";\r
+ private static final String SKIP_I = MdlUtil.INT+",";\r
+ private static final String SKIP_ANY = "[^,]*,";\r
+ \r
+ private static final String POINTS = "(\\d+\\|(?:\\(-?\\d+,-?\\d+\\)\\|)+)";\r
+ \r
+ // each sketch connection is declared with a string:\r
+ // 1,id,from,to,shape,hid,pol,thick,hasf,dtype,res,color,font,np|plist\r
+ \r
+ // the following regular expression matches a connection declaration and \r
+ // extracts the useful information from it\r
+ private static final String SKETCH_CONNECTION = \r
+ "1,"+KEEP_I+KEEP_I+KEEP_I+KEEP_I+SKIP_I+SKIP_I+SKIP_I+SKIP_I+SKIP_I+SKIP_I+SKIP_ANY+SKIP_ANY+POINTS;\r
+ // corresponding group indices\r
+ private static final int connectionId = 1;\r
+ private static final int connectionFrom = 2;\r
+ private static final int connectionTo = 3;\r
+ private static final int connectionShape = 4;\r
+ private static final int connectionPoints = 5;\r
+ \r
+ private static final String SAVE = "(-?\\d+),";\r
+ private static final String SKIP = "-?\\d+,";\r
+ \r
+ public static final String sketchConnection =\r
+ // 1, id, from,to, shape,hid, pol, thick,hasf,dtype,res, color,font,np|plist\r
+ "1,"+SAVE+SAVE+SAVE+SAVE+ SKIP+SKIP+SKIP+ SKIP+SKIP+ SKIP+"[^,]*,[^,]*,"+POINTS;\r
+\r
+ private int from;\r
+ private int to;\r
+ private ConnectionType type;\r
+ int[] points;\r
+\r
+ protected SketchConnection(int id, int from, int to, ConnectionType type, int[] points) {\r
+ super(id);\r
+ this.from = from;\r
+ this.to = to;\r
+ this.type = type;\r
+ this.points = points;\r
+ }\r
+ \r
+ public static SketchConnection getPossible(String line) \r
+ throws Exception {\r
+ Matcher matcher = Pattern.compile(SKETCH_CONNECTION).matcher(line);\r
+ if (!matcher.matches()) {\r
+ return null;\r
+ }\r
+ \r
+ int id = Integer.parseInt(matcher.group(connectionId));\r
+ int from = Integer.parseInt(matcher.group(connectionFrom));\r
+ int to = Integer.parseInt(matcher.group(connectionTo));\r
+ int connType = Integer.parseInt(matcher.group(connectionShape));\r
+ \r
+ ConnectionType type;\r
+ switch (Integer.parseInt(matcher.group(connectionShape))) {\r
+ case 0: \r
+ case 1: type = ConnectionType.ARROW; break;\r
+ case 4: type = ConnectionType.LINE_ARROW; break;\r
+ case 100: type = ConnectionType.LINE_SEGMENT; break;\r
+ default: \r
+ System.err.println("connection type "+connType+" not recognized"); \r
+ type = ConnectionType.OTHER; break;\r
+ }\r
+ \r
+ int[] points = parsePoints(matcher.group(connectionPoints));\r
+ \r
+ return new SketchConnection(id, from, to, type, points);\r
+ }\r
+ \r
+ private static int[] parsePoints(String str) {\r
+ int sep = str.indexOf('|');\r
+ int count = Integer.parseInt(str.substring(0, sep));\r
+ int[] points = new int[count*2];\r
+ for (int i = 0; i < count; i++) {\r
+ int start = sep + 1;\r
+ sep = str.indexOf('|', start);\r
+ String[] pair = str.substring(start+1, sep-1).split(",");\r
+ points[i*2] = Integer.parseInt(pair[0]);\r
+ points[i*2+1] = Integer.parseInt(pair[1]);\r
+ }\r
+ return points;\r
+ }\r
+\r
+ public int getFrom() {\r
+ return from;\r
+ }\r
+\r
+ public int getTo() {\r
+ return to;\r
+ }\r
+\r
+ public ConnectionType getType() {\r
+ return type;\r
+ }\r
+ \r
+ public int[] getPoints() {\r
+ return points;\r
+ }\r
+\r
+ public Connection getConnection(Sketch sketch) {\r
+ Symbol tail = (Symbol)sketch.getObject(from).getModelObject();\r
+ if (tail == null) {\r
+ return null;\r
+ }\r
+ Symbol head = (Symbol)sketch.getObject(to).getModelObject();\r
+ if (head == null) {\r
+ return null;\r
+ }\r
+ \r
+ switch (type) {\r
+ case ARROW: return new Dependency(tail, head, true, false, getAngle(sketch));\r
+ case LINE_ARROW: return new Flow(tail, head);\r
+ case LINE_SEGMENT: return new Flow(head, tail);\r
+ default: return null;\r
+ }\r
+ }\r
+\r
+ public double getAngle(Sketch sketch) {\r
+ if (points == null || points.length < 2) {\r
+ return 0;\r
+ }\r
+ \r
+ SketchElement tail = (SketchElement)sketch.getObject(from);\r
+ SketchElement head = (SketchElement)sketch.getObject(to);\r
+ \r
+ // 'from' element is in (x0, y0) and 'to' element is in (x2, y2)\r
+ double x0 = tail.getX();\r
+ double y0 = tail.getY();\r
+ double x2 = head.getX();\r
+ double y2 = head.getY();\r
+ \r
+ // treat the first points in points as the control point (x1, y1)\r
+ double x1 = (double)points[0];\r
+ double y1 = (double)points[1];\r
+ \r
+ //System.err.println("("+x0+","+y0+") -> ("+x1+","+y1+") -> ("+x2+","+y2+")");\r
+\r
+ double dx0 = x1 - x0;\r
+ double dy0 = y1 - y0;\r
+ double dx1 = x1 - x2;\r
+ double dy1 = y1 - y2;\r
+ double dx = x2 - x0;\r
+ double dy = y2 - y0;\r
+\r
+ // length of (p1-p0) x (p2-p0)\r
+ double dd = dx0*dy - dy0*dx; \r
+\r
+ if (Math.abs(dd) < 0.01) {\r
+ // Points are (almost) collinear\r
+ return 0;\r
+ }\r
+ else {\r
+ // (p1-p0) * (p1-p2) / dd\r
+ double offset = (dx0*dx1 + dy0*dy1) / dd;\r
+ double angle = Math.PI/2 - Math.atan(offset);\r
+ if (dd > 0)\r
+ angle = angle - Math.PI;\r
+ return angle;\r
+ }\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.element.Symbol;\r
+import org.simantics.sysdyn.modelImport.model.element.Valve.TextPosition;\r
+\r
+public abstract class SketchElement extends SketchObject {\r
+ \r
+ // some shorthands\r
+ protected static final String KEEP_I = MdlUtil.INT_G+",";\r
+ protected static final String SKIP_I = MdlUtil.INT+",";\r
+ \r
+ // each sketch element is declared with a string:\r
+ // n,id,name,x,y,w,h,sh,bits,hid,hasf,tpos,bw,nav1,nav2(,box,fill,font)\r
+ \r
+ // n, id and name depend on the type of the sketch element, and some\r
+ // of the fields in the suffix do not contain useful information\r
+ \r
+ // the following regular expression matches the suffix of an element\r
+ // declaration and extracts the useful information from it\r
+ protected static final String ELEMENT_SUFFIX =\r
+ KEEP_I+KEEP_I+KEEP_I+KEEP_I+KEEP_I+KEEP_I+SKIP_I+SKIP_I+KEEP_I+".*";\r
+ // corresponding group indices\r
+ protected static final int elementX = 1;\r
+ protected static final int elementY = 2;\r
+ protected static final int elementWidth = 3;\r
+ protected static final int elementHeight = 4;\r
+ protected static final int elementShape = 5;\r
+ protected static final int elementBits = 6;\r
+ protected static final int elementTextPos = 7;\r
+\r
+ private int x;\r
+ private int y;\r
+ private int width;\r
+ private int height;\r
+ private boolean attached;\r
+ private boolean allowsIn;\r
+ private boolean allowsOut;\r
+ private boolean inputOutput;\r
+ private boolean textLine;\r
+ private TextPosition textPosition;\r
+\r
+ protected SketchElement(int id) {\r
+ super(id);\r
+ }\r
+ \r
+ protected void parseSuffix(String suffix) \r
+ throws Exception {\r
+ Matcher matcher = Pattern.compile(ELEMENT_SUFFIX).matcher(suffix);\r
+ if (!matcher.matches()) {\r
+ // this should not happen unless subclasses fail to construct their\r
+ // regular expressions properly\r
+ throw new Exception("could not parse element suffix "+suffix);\r
+ }\r
+ \r
+ x = Integer.parseInt(matcher.group(elementX));\r
+ y = Integer.parseInt(matcher.group(elementY));\r
+ width = Integer.parseInt(matcher.group(elementWidth));\r
+ height = Integer.parseInt(matcher.group(elementHeight));\r
+ attached = (Integer.parseInt(matcher.group(elementShape)) & 1<<5) != 0;\r
+ allowsIn = (Integer.parseInt(matcher.group(elementBits)) & 1) != 0;\r
+ allowsOut = (Integer.parseInt(matcher.group(elementBits)) & 1<<1) != 0;\r
+ inputOutput = (Integer.parseInt(matcher.group(elementBits)) & 1<<3) != 0;\r
+ textLine = (Integer.parseInt(matcher.group(elementBits)) & 1<<2) != 0;\r
+ \r
+ switch (Integer.parseInt(matcher.group(elementTextPos))) {\r
+ case 0: textPosition = TextPosition.INSIDE; break;\r
+ case 1: textPosition = TextPosition.BELOW; break;\r
+ case 2: textPosition = TextPosition.LEFT; break;\r
+ case 3: textPosition = TextPosition.ABOVE; break;\r
+ case 4: textPosition = TextPosition.RIGHT; break;\r
+ default: textPosition = TextPosition.UNSET; break;\r
+ }\r
+ \r
+ }\r
+\r
+ public int getX() {\r
+ return x;\r
+ }\r
+ \r
+ public int getY() {\r
+ return y;\r
+ }\r
+ \r
+ public int getWidth() {\r
+ return width;\r
+ }\r
+\r
+ public int getHeight() {\r
+ return height;\r
+ }\r
+ \r
+ public boolean isAttached() {\r
+ return attached;\r
+ }\r
+\r
+ public boolean allowsIn() {\r
+ return allowsIn;\r
+ }\r
+\r
+ public boolean allowsOut() {\r
+ return allowsOut;\r
+ }\r
+\r
+ public boolean isInputOutput() {\r
+ return inputOutput;\r
+ }\r
+\r
+ public boolean hasTextLine() {\r
+ return textLine;\r
+ }\r
+ \r
+ public TextPosition getTextPosition() {\r
+ return textPosition;\r
+ }\r
+\r
+ public abstract Symbol getSymbol(MdlModel mdl, Sketch sketch);\r
+ \r
+ private static final double SCALE_MULTIPLIER = 0.4;\r
+ \r
+ public double[] getDimensions(Sketch sketch) {\r
+ double[] dimensions = getDimensions();\r
+ dimensions[0] = dimensions[0] + sketch.getHorizontalOffset();\r
+ dimensions[1] = dimensions[1] + sketch.getVerticalOffset();\r
+ return dimensions;\r
+ }\r
+ \r
+ // get element dimensions, [x, y, width, height]\r
+ public double[] getDimensions() {\r
+ double[] dimensions = new double[4];\r
+ dimensions[0] = (getX() - getWidth()) * SCALE_MULTIPLIER;\r
+ dimensions[1] = (getY() - getHeight()) * SCALE_MULTIPLIER;\r
+ dimensions[2] = getWidth() * 2 * SCALE_MULTIPLIER;\r
+ dimensions[3] = getHeight() * 2 * SCALE_MULTIPLIER;\r
+ return dimensions;\r
+ }\r
+ \r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+\r
+public abstract class SketchObject {\r
+\r
+ private int id;\r
+ private IWriteableObject modelObject;\r
+ \r
+ protected SketchObject(int id) {\r
+ this.id = id;\r
+ }\r
+ \r
+ public int getId() {\r
+ return id;\r
+ }\r
+ \r
+ public void setModelObject(IWriteableObject modelObject) {\r
+ this.modelObject = modelObject;\r
+ }\r
+ \r
+ public IWriteableObject getModelObject() {\r
+ return modelObject;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.model.element.Valve;\r
+import org.simantics.sysdyn.modelImport.model.element.Valve.Orientation;\r
+\r
+public class SketchValve extends SketchElement {\r
+ \r
+ private static final String SKETCH_VALVE =\r
+ "11,"+KEEP_I+SKIP_I+"("+ELEMENT_SUFFIX+")";\r
+ private static final int valveId = 1;\r
+ private static final int valveSuffix = 2;\r
+ \r
+ private SketchVariable attached;\r
+ \r
+ protected SketchValve(int id) {\r
+ super(id);\r
+ }\r
+ \r
+ public static SketchValve getPossible(String line) \r
+ throws Exception {\r
+ Matcher matcher = Pattern.compile(SKETCH_VALVE).matcher(line);\r
+ if (!matcher.matches()) {\r
+ return null;\r
+ }\r
+ \r
+ int id = Integer.parseInt(matcher.group(valveId));\r
+ \r
+ SketchValve element = new SketchValve(id);\r
+ element.parseSuffix(matcher.group(valveSuffix));\r
+ return element;\r
+ }\r
+\r
+ public SketchVariable getAttached() {\r
+ return attached;\r
+ }\r
+\r
+ public void setAttached(SketchVariable attached) {\r
+ this.attached = attached;\r
+ }\r
+ \r
+ @Override\r
+ public Valve getSymbol(MdlModel mdl, Sketch sketch) {\r
+ Variable variable = mdl.getVariable(attached.getName());\r
+ if (variable == null) {\r
+ return null;\r
+ }\r
+ \r
+ Valve valve = new Valve(Orientation.HORIZONTAL, getTextPosition());\r
+ \r
+ return variable.setUpModelVariable(valve, getDimensions(sketch), mdl);\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.element.Auxiliary;\r
+import org.simantics.sysdyn.modelImport.model.element.ModelVariable;\r
+import org.simantics.sysdyn.modelImport.model.element.Symbol;\r
+import org.simantics.sysdyn.modelImport.model.element.Stock;\r
+import org.simantics.sysdyn.modelImport.model.expression.IntegralExpression;\r
+\r
+public class SketchVariable extends SketchElement {\r
+ \r
+ private static final String SKETCH_VARIABLE =\r
+ "10,"+KEEP_I+MdlUtil.VARIABLE+",("+ELEMENT_SUFFIX+")";\r
+ private static final int variableId = 1;\r
+ private static final int variableName = 2;\r
+ private static final int variableSuffix = 3;\r
+ \r
+ private String name;\r
+\r
+ protected SketchVariable(int id, String name) {\r
+ super(id);\r
+ this.name = name;\r
+ }\r
+ \r
+ public static SketchVariable getPossible(String line) \r
+ throws Exception {\r
+ Matcher matcher = Pattern.compile(SKETCH_VARIABLE).matcher(line);\r
+ if (!matcher.matches()) {\r
+ return null;\r
+ }\r
+ \r
+ int id = Integer.parseInt(matcher.group(variableId));\r
+ String name = MdlUtil.normalize(matcher.group(variableName));\r
+ \r
+ SketchVariable element = new SketchVariable(id, name);\r
+ element.parseSuffix(matcher.group(variableSuffix));\r
+ return element;\r
+ }\r
+ \r
+ public String getName() {\r
+ return name;\r
+ }\r
+ \r
+ @Override\r
+ public ModelVariable getSymbol(MdlModel mdl, Sketch sketch) {\r
+ Variable variable = mdl.getVariable(name);\r
+ if (variable == null) {\r
+ return null;\r
+ }\r
+ \r
+ ModelVariable var;\r
+ \r
+ if (variable.getExpressionString() != null && variable.getExpressionString().startsWith("INTEG"))\r
+ var = new Stock();\r
+ else\r
+ var = new Auxiliary();\r
+ \r
+ return variable.setUpModelVariable(var, getDimensions(sketch), mdl);\r
+ }\r
+ \r
+}
\ No newline at end of file
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.Arrays;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Set;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.support.Enumeration;\r
+\r
+public class Subscript extends Declaration {\r
+ \r
+ private static final String SUBSCRIPT_DECL = \r
+ "("+MdlUtil.BASIC_NAME+")\\s*(:|<->)\\s*([^~]*?)("+DECL_SUFFIX+")";\r
+ private static final int subscriptName = 1;\r
+ private static final int subscriptType = 2;\r
+ private static final int subscriptExpression = 3;\r
+ private static final int subscriptSuffix = 4;\r
+ \r
+ private String original;\r
+ private List<String> values;\r
+ \r
+ private Enumeration enumeration;\r
+ \r
+ protected Subscript(String name, List<String> values) {\r
+ super(name);\r
+ this.original = null;\r
+ this.values = values;\r
+ }\r
+ \r
+ protected Subscript(String name, String original) {\r
+ super(name);\r
+ this.original = original;\r
+ this.values = null;\r
+ }\r
+ \r
+ public static Subscript getPossible(String line) \r
+ throws Exception {\r
+ Matcher matcher = Pattern.compile(SUBSCRIPT_DECL).matcher(line); \r
+ if (!matcher.matches())\r
+ return null;\r
+ \r
+ String name = MdlUtil.normalize(matcher.group(subscriptName));\r
+ boolean equivalent = matcher.group(subscriptType).equals("<->");\r
+ String expression = MdlUtil.normalize(matcher.group(subscriptExpression));\r
+ \r
+ Subscript subscript;\r
+ if (equivalent)\r
+ subscript = new Subscript(name, expression);\r
+ else\r
+ subscript = new Subscript(name, Arrays.asList(expression.split(",")));\r
+ subscript.parseSuffix(matcher.group(subscriptSuffix));\r
+ return subscript;\r
+ }\r
+ \r
+ public String getOriginal() {\r
+ return original;\r
+ }\r
+ \r
+ public List<String> getValues(MdlModel mdl) {\r
+ if (values != null)\r
+ return values;\r
+ else\r
+ return mdl.getSubscript(original).getValues(mdl);\r
+ }\r
+ \r
+ public boolean isEquivalent() {\r
+ return original != null;\r
+ }\r
+ \r
+ public Enumeration getEnumeration(MdlModel mdl) {\r
+ if (enumeration == null) {\r
+ enumeration = new Enumeration(getName(), getValues(mdl));\r
+ }\r
+ \r
+ return enumeration;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.ArrayDeque;\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.Deque;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Set;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.expression.EnumerationExpression;\r
+import org.simantics.sysdyn.modelImport.model.expression.NormalExpression;\r
+import org.simantics.sysdyn.modelImport.model.support.Enumeration;\r
+\r
+public class SubscriptVariable extends Variable {\r
+ \r
+ // a subscript variable is a variable that has a different equation\r
+ // depending on the value of the subscript it references\r
+ private static final String SUBSCRIPT_VARIABLE_DECL = \r
+ MdlUtil.SUBSCRIPT+EXPRESSION+"("+DECL_SUFFIX+")";;\r
+ private static final int subscriptVariableName = 1;\r
+ private static final int subscriptVariableIndices = 2;\r
+ private static final int subscriptVariableExpression = 3;\r
+ private static final int subscriptVariableSuffix = 4;\r
+\r
+ private String[] indices;\r
+ private SubscriptVariable next;\r
+ \r
+ protected SubscriptVariable(String name, String expression, String[] indices) {\r
+ super(name, expression);\r
+ this.indices = indices;\r
+ this.next = null;\r
+ }\r
+ \r
+ public static SubscriptVariable getPossible(String line) \r
+ throws Exception {\r
+ Matcher matcher = Pattern.compile(SUBSCRIPT_VARIABLE_DECL).matcher(line);\r
+ if (!matcher.matches()) {\r
+ return null;\r
+ }\r
+ \r
+ String name = MdlUtil.normalize(matcher.group(subscriptVariableName));\r
+ String[] indices = MdlUtil.normalize(matcher.group(subscriptVariableIndices)).split(",");\r
+ String expression = matcher.group(subscriptVariableExpression);\r
+ if (expression != null)\r
+ expression = MdlUtil.normalize(expression);\r
+ \r
+ SubscriptVariable subVar = new SubscriptVariable(name, expression, indices);\r
+ subVar.parseSuffix(matcher.group(subscriptVariableSuffix));\r
+ return subVar;\r
+ }\r
+ \r
+ public String[] getIndices() {\r
+ return indices;\r
+ }\r
+ \r
+ private SubscriptVariable getNext() {\r
+ return next;\r
+ }\r
+ \r
+ private void setNext(SubscriptVariable next) {\r
+ this.next = next;\r
+ }\r
+ \r
+ public void addSubscriptVariable(SubscriptVariable variable) {\r
+ // find the last variable in the list and add the new variable after it\r
+ SubscriptVariable last = this;\r
+ while (last.getNext() != null)\r
+ last = last.getNext();\r
+ last.setNext(variable);\r
+ }\r
+ \r
+ @Override\r
+ public EnumerationExpression getExpression(MdlModel mdl) {\r
+ SubscriptVariable var;\r
+ \r
+ // find out what subscripts the combined expression uses by collecting\r
+ // all subscript indices from individual expressions into a list of\r
+ // sets (one set for each "position" in the indices)\r
+ \r
+ List<Set<String>> subscripts = new ArrayList<Set<String>>();\r
+ for (int i = 0; i < indices.length; i++) {\r
+ subscripts.add(new HashSet<String>());\r
+ }\r
+ \r
+ var = this;\r
+ while (var != null) {\r
+ for (int i = 0; i < var.getIndices().length; i++) {\r
+ subscripts.get(i).add(var.getIndices()[i]);\r
+ }\r
+ \r
+ var = var.getNext();\r
+ }\r
+ \r
+ // turn the aforementioned list of sets into a list of enumeration\r
+ // by finding the enumerations that correspond to the sets of subscript\r
+ // indices\r
+ \r
+ List<Enumeration> enumerations = new ArrayList<Enumeration>();\r
+ for (Set<String> values : subscripts) {\r
+ Subscript potential = mdl.resolveSubscript(values);\r
+ if (potential == null) {\r
+ System.err.println("subscript indices could not be resolved ");\r
+ for (String value : values) {\r
+ System.err.println(" "+value);\r
+ }\r
+ System.err.println();\r
+ }\r
+ enumerations.add(potential.getEnumeration(mdl));\r
+ }\r
+ \r
+ EnumerationExpression expr = new EnumerationExpression(enumerations);\r
+ \r
+ // populate the created expression (TODO: comment)\r
+ \r
+ // TODO: is this check correct, also does not work correctly yet\r
+ if (next == null && enumerations.size() == 2) {\r
+ // option a:\r
+// StringBuilder buffer = new StringBuilder();\r
+// buffer.append('{');\r
+// for (int i = 0; i < values.length; i++) {\r
+// if (i > 0) {\r
+// buffer.append(',');\r
+// }\r
+// buffer.append('{');\r
+// for (int j = 0; j < values[i].length; j++) {\r
+// if (j > 0) {\r
+// buffer.append(',');\r
+// }\r
+// buffer.append(values[i][j]);\r
+// }\r
+// buffer.append('}');\r
+// }\r
+// buffer.append('}');\r
+//\r
+// String[] exprindices = new String[enumerations.size()];\r
+// for (int i = 0; i < exprindices.length; i++) {\r
+// exprindices[i] = enumerations.get(i).getName();\r
+// }\r
+//\r
+// expr.addExpression(new NormalExpression(buffer.toString()), exprindices);\r
+// return expr;\r
+ \r
+ // option b: (probably more sensible)\r
+ double[][] values = getPossibleValueArray(getExpressionString());\r
+ if (values != null) {\r
+ for (int i = 0; i < values.length; i++) {\r
+ for (int j = 0; j < values[i].length; j++) {\r
+ expr.addExpression(\r
+ new NormalExpression(Double.toString(values[i][j])),\r
+ enumerations.get(0).getValues().get(i),\r
+ enumerations.get(1).getValues().get(j));\r
+ }\r
+ }\r
+ return expr;\r
+ }\r
+ }\r
+ \r
+ var = this;\r
+ while (var != null) {\r
+ \r
+ Deque<WorkExpression> workqueue = new ArrayDeque<WorkExpression>();\r
+ workqueue.add(new WorkExpression(var.getIndices(), var.getExpressionString()));\r
+ \r
+ for (int i = 0; i < var.getIndices().length; i++) {\r
+ int limit = workqueue.size();\r
+ for (int j = 0; j < limit; j++) {\r
+ WorkExpression current = workqueue.pollFirst();\r
+ Subscript potential = mdl.getSubscript(current.indices[i]);\r
+ if (potential != null) {\r
+ for (String value : potential.getValues(mdl)) {\r
+ String[] newindices = Arrays.copyOf(current.indices, current.indices.length);\r
+ newindices[i] = value;\r
+ String newexpression = current.expression;\r
+ newexpression = MdlUtil.replaceSubscripts(newexpression, potential.getName(), value);\r
+ workqueue.addLast(new WorkExpression(newindices, newexpression));\r
+ }\r
+ }\r
+ else {\r
+ workqueue.addLast(current);\r
+ }\r
+ }\r
+ }\r
+ \r
+ for (WorkExpression we : workqueue) {\r
+ // TODO: is this check correct\r
+ String expression = MdlUtil.finalize(we.expression, mdl);\r
+ if (next == null) {\r
+ expression = removeComparisons(expression, indices, we.indices);\r
+ }\r
+ expr.addExpression(parseExpression(expression), we.indices);\r
+ }\r
+ \r
+ var = var.getNext();\r
+ }\r
+ \r
+ return expr;\r
+ }\r
+ \r
+ private class WorkExpression {\r
+ String[] indices;\r
+ String expression;\r
+ \r
+ private WorkExpression(String[] indices, String expression) {\r
+ this.indices = indices;\r
+ this.expression = expression;\r
+ }\r
+ }\r
+ \r
+ private static double[][] getPossibleValueArray(String expression) {\r
+ // (number(,number)*;)*\r
+ Matcher matcher = Pattern.compile(\r
+ "("+MdlUtil.DBL+"(,"+MdlUtil.DBL+")*;)*"\r
+ ).matcher(expression);\r
+ \r
+ if (!matcher.matches()) {\r
+ return null;\r
+ }\r
+ \r
+ String[] rows = expression.split(";");\r
+ double[][] result = new double[rows.length][];\r
+ for (int i = 0; i < rows.length; i++) {\r
+ String[] columns = rows[i].split(",");\r
+ result[i] = new double[columns.length];\r
+ for (int j = 0; j < columns.length; j++) {\r
+ result[i][j] = Double.parseDouble(columns[j]);\r
+ } \r
+ }\r
+ \r
+ return result;\r
+ }\r
+ \r
+ private static String removeComparisons(String expression, String[] subscripts, String[] values) {\r
+ \r
+ if (!expression.contains("=")) {\r
+ return expression;\r
+ }\r
+ \r
+ for (int i = 0; i < subscripts.length; i++) {\r
+ for (int j = 0; j < subscripts.length; j++) {\r
+ StringBuilder result = new StringBuilder();\r
+ int offset = 0;\r
+ \r
+ Matcher matcher = Pattern.compile(subscripts[i]+"\\s*=\\s*"+subscripts[j]).matcher(expression);\r
+ while (matcher.find()) {\r
+ result.append(expression.substring(offset, matcher.start()));\r
+ \r
+ if (values[i].equals(values[j])) {\r
+ result.append("true");\r
+ }\r
+ else {\r
+ result.append("false");\r
+ }\r
+ \r
+ offset = matcher.end();\r
+ }\r
+ if (offset < expression.length()) {\r
+ result.append(expression.substring(offset));\r
+ }\r
+ \r
+ expression = result.toString();\r
+ }\r
+ }\r
+ \r
+ return expression;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.ArrayList;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.element.ModelVariable;\r
+import org.simantics.sysdyn.modelImport.model.expression.DelayExpression;\r
+import org.simantics.sysdyn.modelImport.model.expression.Expression;\r
+import org.simantics.sysdyn.modelImport.model.expression.IntegralExpression;\r
+import org.simantics.sysdyn.modelImport.model.expression.NormalExpression;\r
+import org.simantics.sysdyn.modelImport.model.support.Range;\r
+\r
+public class Variable extends Declaration {\r
+ \r
+ protected static final String EXPRESSION =\r
+ "(?:\\s*=\\s*([^~]*?(?:"+MdlUtil.SPECIAL_NAME+"[^~]*?)*))?";\r
+ \r
+ private static final String VARIABLE_DECL =\r
+ MdlUtil.VARIABLE+EXPRESSION+"("+DECL_SUFFIX+")";\r
+ private static final int variableName = 1;\r
+ private static final int variableExpression = 2;\r
+ private static final int variableSuffix = 3;\r
+ \r
+ private String expression;\r
+ \r
+ protected Variable(String name, String expression) {\r
+ super(name);\r
+ this.expression = expression;\r
+ }\r
+ \r
+ public static Variable getPossible(String line) \r
+ throws Exception {\r
+ Matcher matcher = Pattern.compile(VARIABLE_DECL).matcher(line);\r
+ if (!matcher.matches()) {\r
+ return null;\r
+ }\r
+ \r
+ String name = MdlUtil.normalize(matcher.group(variableName));\r
+ String expression = matcher.group(variableExpression);\r
+ if (expression != null)\r
+ expression = MdlUtil.normalize(expression);\r
+ \r
+ Variable var = new Variable(name, expression);\r
+ var.parseSuffix(matcher.group(variableSuffix));\r
+ return var;\r
+ }\r
+ \r
+ public String getExpressionString() {\r
+ return expression;\r
+ }\r
+ \r
+ public <T extends ModelVariable> T setUpModelVariable(T variable, \r
+ double[] dimensions, MdlModel mdl) {\r
+ variable.setName(getName());\r
+ if (expression != null)\r
+ variable.setExpression(getExpression(mdl));\r
+ \r
+ String unit = getUnit();\r
+ Range range = parseRange(unit);\r
+ if (range != null)\r
+ unit = unit.substring(0, unit.indexOf('[')).trim();\r
+ \r
+ variable.setUnit(unit);\r
+ if (range != null)\r
+ variable.setRange(range);\r
+ variable.setDescription(getDescription());\r
+ \r
+ variable.setDimensions(dimensions);\r
+ \r
+ return variable;\r
+ }\r
+ \r
+ public Expression getExpression(MdlModel mdl) {\r
+ return parseExpression(MdlUtil.finalize(expression, mdl));\r
+ }\r
+ \r
+ protected static Expression parseExpression(String expression) {\r
+ Matcher matcher = Pattern.compile(\r
+ MdlUtil.FUNCTION+"(.*)\\)"\r
+ ).matcher(expression);\r
+ if (!matcher.matches()) {\r
+ // the expression is not one of the special function calls\r
+ return new NormalExpression(expression);\r
+ }\r
+ \r
+ String function = matcher.group(1);\r
+ String[] parameters = MdlUtil.splitFunctionParameters(matcher.group(2));\r
+ \r
+ if (function.startsWith("INTEG")) {\r
+ // an integral expression\r
+ if (parameters.length != 2) {\r
+ System.err.println("malformed integral expression: "+expression);\r
+ return null;\r
+ }\r
+ return new IntegralExpression(parameters[0], parameters[1]);\r
+ }\r
+ else if (function.startsWith("DELAY N")) {\r
+ // a delay expression\r
+ if (parameters.length != 4) {\r
+ System.err.println("malformed delay expression: "+expression);\r
+ return null;\r
+ }\r
+ return new DelayExpression(parameters[0], parameters[1], parameters[2], Integer.parseInt(parameters[3]));\r
+ }\r
+ else if (function.startsWith("SMOOTHI")) {\r
+ if (parameters.length != 3) {\r
+ System.err.println("malformed smoothi expression: "+expression);\r
+ }\r
+ // what is the correct degree for smooth?\r
+ return new DelayExpression(parameters[0], parameters[1], parameters[2], 1);\r
+ }\r
+ else if (function.startsWith("SMOOTH")) {\r
+ if (parameters.length != 2) {\r
+ System.err.println("malformed smooth expression: "+expression);\r
+ }\r
+ // what is the correct degree and initial value for smooth?\r
+ return new DelayExpression(parameters[0], parameters[1], parameters[0], 1);\r
+ }\r
+ else if (function.startsWith("GAME")) {\r
+ // a game expression, currently treated as a normal expression\r
+ if (parameters.length != 1) {\r
+ System.err.println("malformed game expression: "+expression);\r
+ return null;\r
+ }\r
+ return new NormalExpression(parameters[0]);\r
+ }\r
+ else {\r
+ return new NormalExpression(expression);\r
+ }\r
+ }\r
+ \r
+ private static Range parseRange(String unit) {\r
+ Matcher matcher = Pattern.compile(\r
+ "\\["+MdlUtil.DBL_G+",(\\?|"+MdlUtil.DBL_G+"|"+MdlUtil.DBL_G+","+MdlUtil.DBL_G+")\\]"\r
+ ).matcher(unit);\r
+ if (matcher.find()) {\r
+ Double start, end, step;\r
+ start = Double.parseDouble(matcher.group(1));\r
+ if (matcher.group(2).equals("?")) {\r
+ end = null;\r
+ step = null;\r
+ }\r
+ else if (matcher.group(2).contains(",")){\r
+ end = Double.parseDouble(matcher.group(4));\r
+ step = Double.parseDouble(matcher.group(5));\r
+ }\r
+ else {\r
+ end = Double.parseDouble(matcher.group(3));\r
+ step = null; \r
+ }\r
+ return new Range(start, end, step);\r
+ }\r
+ else {\r
+ return null;\r
+ }\r
+ }\r
+}\r
* Contributors:\r
* VTT Technical Research Centre of Finland - initial API and implementation\r
*******************************************************************************/\r
-package org.simantics.sysdyn.mdlImport.mdlElements;\r
+package org.simantics.sysdyn.modelImport.model;\r
\r
import org.simantics.db.Resource;\r
import org.simantics.db.WriteGraph;\r
import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.sysdyn.SysdynResource;\r
-\r
-public class Flow extends Connection {\r
-\r
- @Override\r
- public void write(WriteGraph graph, Resource parent) {\r
- if(parent == null || graph == null)\r
- return;\r
- try {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- writeConnection(graph, parent, sr.Flow, sr.FlowConnection);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
\r
+public interface IWriteableObject {\r
+ \r
+ /**\r
+ * Write this object to the graph and return the corresponding resource.\r
+ * \r
+ * @param graph \r
+ * @param parent \r
+ * @param context\r
+ * @return Resource\r
+ * @throws DatabaseException \r
+ */\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException;\r
+ \r
+ /**\r
+ * Return the resource corresponding to this object or null if this object has not been written yet.\r
+ * \r
+ * @return Resource\r
+ */\r
+ public Resource getResource();\r
}\r
--- /dev/null
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ * VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.modelImport.model.element.Connection;\r
+import org.simantics.sysdyn.modelImport.model.element.Symbol;\r
+import org.simantics.sysdyn.modelImport.model.element.ModelVariable;\r
+import org.simantics.sysdyn.modelImport.model.element.Shadow;\r
+import org.simantics.sysdyn.modelImport.model.support.Enumeration;\r
+import org.simantics.sysdyn.modelImport.model.support.Function;\r
+import org.simantics.sysdyn.utils.ModelUtils;\r
+\r
+public class Model implements IWriteableObject {\r
+ \r
+ private String name;\r
+ // necessary simulation parameters\r
+ private double start, stop, step;\r
+ \r
+ // the structure of the model\r
+ private HashMap<String, ModelVariable> variables;\r
+ private HashMap<String, Enumeration> enumerations;\r
+ private HashMap<String, Function> functions;\r
+ \r
+ private ArrayList<Symbol> symbols;\r
+ private ArrayList<Shadow> shadows;\r
+ private ArrayList<Connection> connections;\r
+ \r
+ private Resource model;\r
+ \r
+ public Model(String name) {\r
+ this.name = name;\r
+ \r
+ variables = new HashMap<String, ModelVariable>();\r
+ enumerations = new HashMap<String, Enumeration>();\r
+ functions = new HashMap<String, Function>();\r
+ \r
+ symbols = new ArrayList<Symbol>();\r
+ shadows = new ArrayList<Shadow>();\r
+ connections = new ArrayList<Connection>();\r
+ }\r
+\r
+ public double getStart() {\r
+ return start;\r
+ }\r
+\r
+ public void setStart(double start) {\r
+ this.start = start;\r
+ }\r
+\r
+ public double getStop() {\r
+ return stop;\r
+ }\r
+\r
+ public void setStop(double stop) {\r
+ this.stop = stop;\r
+ }\r
+\r
+ public double getStep() {\r
+ return step;\r
+ }\r
+\r
+ public void setStep(double step) {\r
+ this.step = step;\r
+ }\r
+ \r
+ public void addSymbol(ModelVariable variable) {\r
+ if (variables.get(variable.getName()) != null) {\r
+ System.err.println("variable "+variable.getName()+" already defined");\r
+ }\r
+ \r
+ variables.put(variable.getName(), variable);\r
+ \r
+ symbols.add(variable);\r
+ }\r
+ \r
+ public ModelVariable getVariable(String name) {\r
+ return variables.get(name);\r
+ }\r
+ \r
+ public Collection<ModelVariable> getVariables() {\r
+ return variables.values();\r
+ }\r
+ \r
+ public void addSymbol(Shadow shadow) {\r
+ shadows.add(shadow);\r
+ }\r
+ \r
+ public void addSymbol(Symbol element) {\r
+ symbols.add(element);\r
+ }\r
+ \r
+ public void addConnection(Connection connection) {\r
+ // TODO: make sure connection head and tail exist\r
+ connections.add(connection);\r
+ }\r
+ \r
+ public void addEnumeration(Enumeration enumeration) {\r
+ if (enumerations.get(enumeration.getName()) != null) {\r
+ System.err.println("enumeration "+enumeration.getName()+" already defined");\r
+ }\r
+ enumerations.put(enumeration.getName(), enumeration);\r
+ }\r
+ \r
+ public Enumeration getEnumeration(String name) {\r
+ return enumerations.get(name);\r
+ }\r
+ \r
+ public Collection<Enumeration> getEnumerations() {\r
+ return enumerations.values();\r
+ }\r
+ \r
+ public void addFunction(Function function) {\r
+ if (functions.get(function.getName()) != null) {\r
+ System.err.println("function "+function.getName()+" already defined");\r
+ }\r
+ functions.put(function.getName(), function);\r
+ }\r
+ \r
+ public Function getEFunction(String name) {\r
+ return functions.get(name);\r
+ }\r
+ \r
+ public Collection<Function> getFunctions() {\r
+ return functions.values();\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ DiagramResource dr = DiagramResource.getInstance(graph);\r
+ Layer0 l0 = Layer0.getInstance(graph);\r
+ ModelingResources mr = ModelingResources.getInstance(graph);\r
+ SimulationResource sim = SimulationResource.getInstance(graph);\r
+ \r
+ model = ModelUtils.createModel(graph);\r
+ graph.claimLiteral(model, l0.HasLabel, name, Bindings.STRING);\r
+ \r
+ // TODO: set simulation parameters\r
+ \r
+ Resource configuration = graph.getSingleObject(model, sim.HasConfiguration);\r
+ \r
+ for (Enumeration e : getEnumerations()) {\r
+ e.write(graph, configuration, context);\r
+ }\r
+ \r
+ for (Function f : getFunctions()) {\r
+ f.write(graph, model, context);\r
+ }\r
+ \r
+ for (Symbol e : symbols) {\r
+ e.write(graph, configuration, context);\r
+ }\r
+ \r
+ for (Shadow s : shadows) {\r
+ s.write(graph, configuration, context);\r
+ }\r
+ \r
+ for (Connection c : connections) {\r
+ c.write(graph, configuration, context);\r
+ }\r
+ \r
+ Resource diagram = graph.getSingleObject(configuration, mr.CompositeToDiagram);\r
+ graph.claimLiteral(diagram, dr.HasModCount, context.getObjectCount(), Bindings.LONG);\r
+ \r
+ return model;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getResource() {\r
+ return model;\r
+ }\r
+ \r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import java.util.Arrays;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.Set;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.modelImport.model.support.Enumeration;\r
+\r
+public class WriteContext {\r
+ \r
+ private long objectCount;\r
+ \r
+ private long cloudCount;\r
+ private long shadowCount;\r
+ private long dependencyCount;\r
+ private long flowCount;\r
+ \r
+ private HashMap<String, Enumeration> enumerations;\r
+ private HashMap<String, Set<Enumeration>> enumerationValues;\r
+ \r
+ public WriteContext() {\r
+ objectCount = 0;\r
+ \r
+ cloudCount = 0;\r
+ shadowCount = 0;\r
+ dependencyCount = 0;\r
+ flowCount = 0;\r
+ \r
+ enumerations = new HashMap<String, Enumeration>();\r
+ enumerationValues = new HashMap<String, Set<Enumeration>>();\r
+ }\r
+ \r
+ public String getNextObject() {\r
+ return Long.toString(objectCount++);\r
+ }\r
+ \r
+ public long getObjectCount() {\r
+ return objectCount;\r
+ }\r
+ \r
+ public String getNextCloud() {\r
+ return "Cloud" + cloudCount++;\r
+ }\r
+ \r
+ public String getNextShadow() {\r
+ return "Shadow" + shadowCount++;\r
+ }\r
+ \r
+ public String getNextDependency() {\r
+ return "Dependency" + dependencyCount++;\r
+ }\r
+ \r
+ public String getNextFlow() {\r
+ return "Flow" + flowCount++;\r
+ }\r
+ \r
+ public void registerEnumeration(Enumeration enumeration, boolean copy) {\r
+ enumerations.put(enumeration.getName(), enumeration);\r
+ if (enumerationValues.get(enumeration.getName()) == null) {\r
+ enumerationValues.put(enumeration.getName(), new HashSet<Enumeration>());\r
+ }\r
+ enumerationValues.get(enumeration.getName()).add(enumeration);\r
+ if (!copy) {\r
+ for (String value : enumeration.getValues()) {\r
+ if (enumerationValues.get(value) == null) {\r
+ enumerationValues.put(value, new HashSet<Enumeration>());\r
+ }\r
+ enumerationValues.get(value).add(enumeration);\r
+ }\r
+ }\r
+ }\r
+ \r
+ public Enumeration getEnumeration(Set<String> indices) {\r
+ System.err.println("size is "+indices.size());\r
+ if (indices.size() == 1) {\r
+ Enumeration enumeration = enumerations.get(indices.iterator().next());\r
+ if (enumeration != null) {\r
+ return enumeration;\r
+ }\r
+ }\r
+ \r
+ // the set of potential matches is the intersection of all sets of\r
+ // enumerations that contain any of the given indices as elements\r
+ Set<Enumeration> potential = new HashSet<Enumeration>(enumerations.values());\r
+ for (String index : indices) {\r
+ potential.retainAll(enumerationValues.get(index));\r
+ }\r
+ \r
+ // if there is more than one potential match, the enumerations are not\r
+ // well defined (there are multiple enumerations with similar indices)\r
+ if (potential.size() == 1) {\r
+ return potential.iterator().next();\r
+ }\r
+ else {\r
+ System.err.println("enumeration could not be resolved "+potential.size());\r
+ for (String index : indices)\r
+ System.err.println(" "+index);\r
+ return null;\r
+ }\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.element;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.expression.Expression;\r
+import org.simantics.sysdyn.modelImport.model.support.Range;\r
+\r
+public class Auxiliary extends ModelVariable {\r
+ \r
+ public Auxiliary() {\r
+ \r
+ }\r
+ \r
+ public Auxiliary(double[] dim, String name, Expression expression, Range range, String unit, String description) {\r
+ super(dim, name, expression, range, unit, description);\r
+ }\r
+ \r
+ @Override\r
+ public Resource getVariableType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).Auxiliary;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getSymbolType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).AuxiliarySymbol;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.element;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class Cloud extends Symbol {\r
+ \r
+ private Resource cloud;\r
+ \r
+ public Cloud() {\r
+ \r
+ }\r
+ \r
+ public Cloud(double[] dim) {\r
+ super(dim);\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ Layer0 l0 = Layer0.getInstance(graph);\r
+ ModelingResources mr = ModelingResources.getInstance(graph);\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ cloud = GraphUtils.create2(graph, sr.Cloud,\r
+ l0.HasName, context.getNextCloud(),\r
+ l0.PartOf, parent);\r
+ \r
+ Resource symbol = super.write(graph, parent, context);\r
+ graph.claim(symbol, mr.ElementToComponent, cloud);\r
+ \r
+ return cloud;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getSymbolType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).CloudSymbol;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getResource() {\r
+ return cloud;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.element;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class Comment extends Symbol {\r
+ \r
+ private String text;\r
+ \r
+ public Comment() {\r
+ \r
+ }\r
+ \r
+ public Comment(String text) {\r
+ this.text = text;\r
+ }\r
+ \r
+ public Comment(double[] dim, String text) {\r
+ super(dim);\r
+ this.text = text;\r
+ }\r
+\r
+ public String getText() {\r
+ return text;\r
+ }\r
+\r
+ public void setText(String text) {\r
+ this.text = text;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ DiagramResource dr = DiagramResource.getInstance(graph);\r
+ \r
+ Resource symbol = super.write(graph, parent, context);\r
+ \r
+ graph.claimLiteral(symbol, dr.HasText, text, Bindings.STRING);\r
+ \r
+ return symbol;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getSymbolType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).AdditionalSymbols_MultilineText;\r
+ }\r
+\r
+ @Override\r
+ public Resource getResource() {\r
+ // comments only have diagram resources\r
+ return getDiagramResource();\r
+ }\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.element;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.OrderedSetUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public abstract class Connection implements IWriteableObject {\r
+\r
+ private Symbol head;\r
+ private Symbol tail;\r
+ \r
+ private Resource connection;\r
+ private Resource diagramConnection;\r
+ \r
+ public Connection() {\r
+ \r
+ }\r
+\r
+ public Connection(Symbol tail, Symbol head) {\r
+ this.tail = tail;\r
+ this.head = head;\r
+ }\r
+ \r
+ public Symbol getHead() {\r
+ return head;\r
+ }\r
+\r
+ public void setHead(Symbol head) {\r
+ this.head = head;\r
+ }\r
+\r
+ public Symbol getTail() {\r
+ return tail;\r
+ }\r
+\r
+ public void setTail(Symbol tail) {\r
+ this.tail = tail;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ DiagramResource dr = DiagramResource.getInstance(graph);\r
+ Layer0 l0 = Layer0.getInstance(graph);\r
+ ModelingResources mr = ModelingResources.getInstance(graph);\r
+ StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ connection = GraphUtils.create2(graph, getConnectionType(graph),\r
+ sr.Variable_HasHead, head.getResource(),\r
+ sr.Variable_HasTail, tail.getResource(),\r
+ l0.PartOf, parent);\r
+ graph.claim(connection, mr.Mapped, connection);\r
+ \r
+ Resource diagram = graph.getSingleObject(parent, mr.CompositeToDiagram);\r
+ \r
+ Resource tailConnector = GraphUtils.create2(graph, dr.Connector,\r
+ sr.HasTailTerminal, tail.getDiagramResource());\r
+\r
+ Resource headConnector = GraphUtils.create2(graph, dr.Connector,\r
+ sr.HasHeadTerminal, head.getDiagramResource(),\r
+ dr.AreConnected, tailConnector);\r
+\r
+ diagramConnection = GraphUtils.create2(graph, getDiagramConnectionType(graph),\r
+ l0.HasName, context.getNextObject(),\r
+ l0.PartOf, diagram,\r
+ sr2.HasConnectionType, sr.SysdynConnectionType,\r
+ mr.DiagramConnectionToConnection, connection,\r
+ dr.HasArrowConnector, headConnector,\r
+ dr.HasPlainConnector, tailConnector);\r
+\r
+ OrderedSetUtils.add(graph, diagram, diagramConnection);\r
+ \r
+ return connection;\r
+ }\r
+ \r
+ public abstract Resource getConnectionType(ReadGraph graph);\r
+ public abstract Resource getDiagramConnectionType(ReadGraph graph);\r
+ \r
+ @Override\r
+ public Resource getResource() {\r
+ return connection;\r
+ }\r
+ \r
+ public Resource getDiagramResource() {\r
+ return diagramConnection;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.element;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class Dependency extends Connection {\r
+ \r
+ private boolean showArrow;\r
+ private boolean showDelay;\r
+ private double angle;\r
+ \r
+ public Dependency() {\r
+ \r
+ }\r
+ \r
+ public Dependency(boolean showArrow, boolean showDelay, double angle) {\r
+ this.showArrow = showArrow;\r
+ this.showDelay = showDelay;\r
+ this.angle = angle;\r
+ }\r
+ \r
+ public Dependency(Symbol tail, Symbol head, boolean showArrow, boolean showDelay, double angle) {\r
+ super(tail, head);\r
+ this.showArrow = showArrow;\r
+ this.showDelay = showDelay;\r
+ this.angle = angle;\r
+ }\r
+\r
+ public boolean isShowArrow() {\r
+ return showArrow;\r
+ }\r
+\r
+ public void setShowArrow(boolean showArrow) {\r
+ this.showArrow = showArrow;\r
+ }\r
+\r
+ public boolean isShowDelay() {\r
+ return showDelay;\r
+ }\r
+\r
+ public void setShowDelay(boolean showDelay) {\r
+ this.showDelay = showDelay;\r
+ }\r
+\r
+ public double getAngle() {\r
+ return angle;\r
+ }\r
+\r
+ public void setAngle(double angle) {\r
+ this.angle = angle;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ if (getHead() == null || getTail() == null) {\r
+ System.err.println("dependency missing head or tail");\r
+ return null;\r
+ }\r
+ \r
+ Layer0 l0 = Layer0.getInstance(graph);\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ Resource dependency = super.write(graph, parent, context);\r
+ graph.claimLiteral(dependency, l0.HasName, context.getNextDependency(), Bindings.STRING);\r
+ \r
+ graph.claimLiteral(getDiagramResource(), sr.Dependency_angle, angle, Bindings.DOUBLE);\r
+ \r
+ return dependency;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getConnectionType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).Dependency;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getDiagramConnectionType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).DependencyConnection;\r
+ }\r
+ \r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.element;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class Flow extends Connection {\r
+ \r
+ public Flow() {\r
+ \r
+ }\r
+ \r
+ public Flow(Symbol tail, Symbol head) {\r
+ super(tail, head);\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ if (getHead() == null || getTail() == null) {\r
+ System.err.println("flow missing head or tail");\r
+ return null;\r
+ }\r
+ \r
+ Layer0 l0 = Layer0.getInstance(graph);\r
+ \r
+ Resource flow = super.write(graph, parent, context);\r
+ graph.claimLiteral(flow, l0.HasName, context.getNextFlow(), Bindings.STRING);\r
+ \r
+ return flow;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getConnectionType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).Flow;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getDiagramConnectionType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).FlowConnection;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.element;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+import org.simantics.sysdyn.modelImport.model.expression.Expression;\r
+import org.simantics.sysdyn.modelImport.model.support.Range;\r
+\r
+public abstract class ModelVariable extends Symbol {\r
+\r
+ private String name;\r
+ private Expression expression;\r
+ private Range range;\r
+ private String unit;\r
+ private String description;\r
+ \r
+ private Resource variable;\r
+ \r
+ public ModelVariable() {\r
+ \r
+ }\r
+ \r
+ public ModelVariable(String name, Expression expression, Range range, String unit, String description) {\r
+ this.name = name;\r
+ this.expression = expression;\r
+ this.range = range;\r
+ this.unit = unit;\r
+ this.description = description;\r
+ }\r
+\r
+ public ModelVariable(double[] dim, String name, Expression expression, Range range, String unit, String description) {\r
+ super(dim);\r
+ this.name = name;\r
+ this.expression = expression;\r
+ this.range = range;\r
+ this.unit = unit;\r
+ this.description = description;\r
+ }\r
+\r
+ public String getName() {\r
+ return name;\r
+ }\r
+\r
+ public void setName(String name) {\r
+ this.name = name;\r
+ }\r
+\r
+ public Expression getExpression() {\r
+ return expression;\r
+ }\r
+\r
+ public void setExpression(Expression expression) {\r
+ this.expression = expression;\r
+ }\r
+\r
+ public Range getRange() {\r
+ return range;\r
+ }\r
+\r
+ public void setRange(Range range) {\r
+ this.range = range;\r
+ }\r
+\r
+ public String getUnit() {\r
+ return unit;\r
+ }\r
+\r
+ public void setUnit(String unit) {\r
+ this.unit = unit;\r
+ }\r
+\r
+ public String getDescription() {\r
+ return description;\r
+ }\r
+\r
+ public void setDescription(String description) {\r
+ this.description = description;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ Layer0 l0 = Layer0.getInstance(graph);\r
+ ModelingResources mr = ModelingResources.getInstance(graph);\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+ variable = GraphUtils.create2(graph, getVariableType(graph), \r
+ l0.HasName, name,\r
+ l0.PartOf, parent);\r
+ graph.claim(variable, mr.Mapped, variable);\r
+ \r
+ // TODO: write references to enumerations here?\r
+ \r
+ if (expression != null) {\r
+ expression.write(graph, variable, context);\r
+ }\r
+ if (range != null) {\r
+ range.write(graph, variable, context);\r
+ }\r
+ if (unit != null && !unit.isEmpty()) {\r
+ graph.claimLiteral(variable, sr.Variable_unit, unit, Bindings.STRING);\r
+ }\r
+ if (description != null && !description.isEmpty()) {\r
+ graph.claimLiteral(variable, l0.HasDescription, description, Bindings.STRING);\r
+ }\r
+ \r
+ Resource symbol = super.write(graph, parent, context);\r
+ graph.claim(symbol, mr.ElementToComponent, variable);\r
+\r
+ return variable;\r
+ }\r
+ \r
+ public abstract Resource getVariableType(ReadGraph graph);\r
+ \r
+ @Override\r
+ public Resource getResource() {\r
+ return variable;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.element;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class Shadow extends Symbol {\r
+\r
+ private ModelVariable original;\r
+ \r
+ private Resource shadow;\r
+ \r
+ public Shadow() {\r
+ \r
+ }\r
+ \r
+ public Shadow(ModelVariable original) {\r
+ this.original = original;\r
+ }\r
+ \r
+ public Shadow(double[] dim, ModelVariable original) {\r
+ super(dim);\r
+ this.original = original;\r
+ }\r
+\r
+ public ModelVariable getOriginal() {\r
+ return original;\r
+ }\r
+\r
+ public void setOriginal(ModelVariable original) {\r
+ this.original = original;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ Layer0 l0 = Layer0.getInstance(graph);\r
+ ModelingResources mr = ModelingResources.getInstance(graph);\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ shadow = GraphUtils.create2(graph, sr.Shadow,\r
+ l0.HasName, context.getNextShadow(),\r
+ l0.PartOf, parent);\r
+ \r
+ graph.claim(shadow, sr.Shadow_original, original.getResource());\r
+ \r
+ Resource symbol = super.write(graph, parent, context);\r
+ graph.claim(symbol, mr.ElementToComponent, shadow);\r
+ \r
+ return shadow;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getSymbolType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).ShadowSymbol;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getResource() {\r
+ return shadow;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.element;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.expression.IntegralExpression;\r
+import org.simantics.sysdyn.modelImport.model.support.Range;\r
+\r
+public class Stock extends ModelVariable {\r
+ \r
+ public Stock() {\r
+ \r
+ }\r
+ \r
+ public Stock(double[] dim, String name, IntegralExpression expression, Range range, String unit, String description) {\r
+ super(dim, name, expression, range, unit, description);\r
+ }\r
+ \r
+ @Override\r
+ public Resource getVariableType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).Stock;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getSymbolType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).StockSymbol;\r
+ }\r
+ \r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.element;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.OrderedSetUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public abstract class Symbol implements IWriteableObject {\r
+ \r
+ private double x;\r
+ private double y;\r
+ private double width;\r
+ private double height;\r
+\r
+ private Resource symbol;\r
+ \r
+ public Symbol() {\r
+ \r
+ }\r
+\r
+ public Symbol(double[] dim) {\r
+ x = dim[0];\r
+ y = dim[1];\r
+ width = dim[2];\r
+ height = dim[3];\r
+ }\r
+ \r
+ public void setDimensions(double[] dim) {\r
+ x = dim[0];\r
+ y = dim[1];\r
+ width = dim[2];\r
+ height = dim[3];\r
+ }\r
+\r
+ public double getX() {\r
+ return x;\r
+ }\r
+\r
+ public void setX(double x) {\r
+ this.x = x;\r
+ }\r
+\r
+ public double getY() {\r
+ return y;\r
+ }\r
+\r
+ public void setY(double y) {\r
+ this.y = y;\r
+ }\r
+\r
+ public double getWidth() {\r
+ return width;\r
+ }\r
+\r
+ public void setWidth(double width) {\r
+ this.width = width;\r
+ }\r
+\r
+ public double getHeight() {\r
+ return height;\r
+ }\r
+\r
+ public void setHeight(double height) {\r
+ this.height = height;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ DiagramResource dr = DiagramResource.getInstance(graph);\r
+ G2DResource g2d = G2DResource.getInstance(graph);\r
+ Layer0 l0 = Layer0.getInstance(graph);\r
+ ModelingResources mr = ModelingResources.getInstance(graph);\r
+\r
+ Resource diagram = graph.getSingleObject(parent, mr.CompositeToDiagram);\r
+ \r
+ symbol = GraphUtils.create2(graph, getSymbolType(graph),\r
+ l0.HasName, context.getNextObject(),\r
+ l0.PartOf, diagram);\r
+\r
+ double[] transform = { 1.0, 0.0, 0.0, 1.0, x, y };\r
+ graph.claimLiteral(symbol, dr.HasTransform, g2d.Transform, transform, Bindings.DOUBLE_ARRAY);\r
+\r
+ OrderedSetUtils.add(graph, diagram, symbol);\r
+ \r
+ return symbol;\r
+ }\r
+ \r
+ public abstract Resource getSymbolType(ReadGraph graph);\r
+ \r
+ public Resource getDiagramResource() {\r
+ return symbol;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.element;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+import org.simantics.sysdyn.modelImport.model.expression.Expression;\r
+import org.simantics.sysdyn.modelImport.model.support.Range;\r
+\r
+public class Valve extends ModelVariable {\r
+ \r
+ public enum Orientation {\r
+ HORIZONTAL, VERTICAL\r
+ }\r
+ \r
+ public enum TextPosition {\r
+ INSIDE, BELOW, LEFT, ABOVE, RIGHT, UNSET\r
+ }\r
+ \r
+ private Orientation orientation;\r
+ private TextPosition position;\r
+ \r
+ public Valve() {\r
+ \r
+ }\r
+ \r
+ public Valve(Orientation orientation, TextPosition position) {\r
+ this.orientation = orientation;\r
+ this.position = position;\r
+ }\r
+ \r
+ public Valve(double[] dim, String name, Expression expression, Range range, String unit, String description, \r
+ Orientation orientation, TextPosition position) {\r
+ super(dim, name, expression, range, unit, description);\r
+ this.orientation = orientation;\r
+ this.position = position;\r
+ }\r
+\r
+ public Orientation getOrientation() {\r
+ return orientation;\r
+ }\r
+\r
+ public void setOrientation(Orientation orientation) {\r
+ this.orientation = orientation;\r
+ }\r
+\r
+ public TextPosition getPosition() {\r
+ return position;\r
+ }\r
+\r
+ public void setPosition(TextPosition position) {\r
+ this.position = position;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+ Resource location = null;\r
+ switch (position) {\r
+ case BELOW: location = sr.Bottom; break;\r
+ case LEFT: location = sr.Left; break;\r
+ case ABOVE: location = sr.Top; break;\r
+ case RIGHT: location = sr.Right; break;\r
+ case UNSET:\r
+ default: System.err.println("valve text location not set"); location = sr.Bottom; break;\r
+ }\r
+ \r
+ Resource valve = super.write(graph, parent, context);\r
+ \r
+ graph.claim(getDiagramResource(), sr.ValveSymbol_textLocation, location);\r
+ \r
+ return valve;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getVariableType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).Valve;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getSymbolType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).ValveSymbol;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class DelayExpression extends Expression {\r
+ \r
+ private String expression;\r
+ private String time;\r
+ private String initial;\r
+ private int order;\r
+ \r
+ public DelayExpression(String expression, String time, String initial, int order) {\r
+ this.expression = expression;\r
+ this.time = time;\r
+ this.initial = initial;\r
+ this.order = order;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ Resource expr = super.write(graph, parent, context);\r
+ \r
+ graph.claimLiteral(expr, sr.DelayExpression_expression, expression, Bindings.STRING);\r
+ graph.claimLiteral(expr, sr.DelayExpression_delayTime, time, Bindings.STRING);\r
+ graph.claimLiteral(expr, sr.DelayExpression_initialValue, initial, Bindings.STRING);\r
+ graph.claimLiteral(expr, sr.DelayExpression_order, order, Bindings.INTEGER);\r
+ \r
+ return expr;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getExpressionType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).DelayExpression;\r
+ }\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+import org.simantics.sysdyn.modelImport.model.support.Enumeration;\r
+\r
+public class EnumerationExpression extends Expression {\r
+ \r
+ private List<Enumeration> enumerations;\r
+ private List<EnumerationSubExpression> subExpressions;\r
+ \r
+ public EnumerationExpression(List<Enumeration> enumerations) {\r
+ this.enumerations = enumerations;\r
+ this.subExpressions = new ArrayList<EnumerationSubExpression>();\r
+ }\r
+ \r
+ public void addExpression(Expression expression, String...indices) {\r
+// for (int i = 0; i < indices.length; i++) {\r
+// if (!enumerations.get(i).getValues().contains(indices)) {\r
+// System.err.println("tried adding an enumeration expression with incorrect indices");\r
+// return;\r
+// }\r
+// }\r
+ subExpressions.add(new EnumerationSubExpression(expression, indices));\r
+ }\r
+ \r
+ public List<EnumerationSubExpression> getExpressions() {\r
+ return subExpressions;\r
+ }\r
+ \r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ for (EnumerationSubExpression subexpr : subExpressions) {\r
+ StringBuilder range = new StringBuilder();\r
+ range.append('[');\r
+ for (int i = 0; i < subexpr.indices.length; i++) {\r
+ if (i > 0)\r
+ range.append(',');\r
+ range.append(subexpr.indices[i]);\r
+ }\r
+ range.append(']');\r
+ \r
+ Resource res = subexpr.expression.write(graph, parent, context);\r
+ \r
+ graph.claimLiteral(res, sr.Expression_arrayRange, range.toString(), Bindings.STRING);\r
+ }\r
+ \r
+ ArrayList<Resource> indexlist = new ArrayList<Resource>();\r
+ for (Enumeration enumeration : enumerations) {\r
+ indexlist.add(enumeration.getResource());\r
+ }\r
+ \r
+ // write array index list\r
+ graph.claim(parent, sr.Variable_arrayIndexesList, ListUtils.create(graph, indexlist));\r
+ \r
+ // set active expression?\r
+ \r
+ return getResource();\r
+ }\r
+ \r
+ private class EnumerationSubExpression {\r
+ \r
+ Expression expression;\r
+ String[] indices;\r
+ \r
+ public EnumerationSubExpression(Expression expression, String...indices) {\r
+ this.expression = expression;\r
+ this.indices = indices;\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public Resource getExpressionType(ReadGraph graph) {\r
+ return subExpressions.get(0).expression.getExpressionType(graph);\r
+ }\r
+ \r
+ @Override\r
+ public Resource getResource() {\r
+ return subExpressions.get(0).expression.getResource();\r
+ }\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import java.util.Arrays;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public abstract class Expression implements IWriteableObject {\r
+\r
+ private Resource expr;\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ Layer0 l0 = Layer0.getInstance(graph);\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ expr = GraphUtils.create2(graph, getExpressionType(graph),\r
+ l0.PartOf, parent);\r
+\r
+ // insert the expression into the expression list of the variable \r
+ // (necessary because of enumeration expressions)\r
+ Resource list = graph.getPossibleObject(parent, sr.Variable_expressionList);\r
+ if (list != null) {\r
+ ListUtils.insertBack(graph, list, Arrays.asList(expr));\r
+ }\r
+ else {\r
+ graph.claim(parent, sr.Variable_expressionList, ListUtils.create(graph, Arrays.asList(expr)));\r
+ }\r
+ \r
+ return expr;\r
+ }\r
+ \r
+ public abstract Resource getExpressionType(ReadGraph graph);\r
+\r
+ @Override\r
+ public Resource getResource() {\r
+ return expr;\r
+ }\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class IntegralExpression extends Expression {\r
+ \r
+ private String integral;\r
+ private String initial;\r
+ \r
+ public IntegralExpression(String integral, String initial) {\r
+ this.integral = integral;\r
+ this.initial = initial;\r
+ }\r
+ \r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ Resource expr = super.write(graph, parent, context);\r
+ \r
+ graph.claimLiteral(expr, sr.StockExpression_integralEquation, integral, Bindings.STRING);\r
+ graph.claimLiteral(expr, sr.StockExpression_initialEquation, initial, Bindings.STRING);\r
+ graph.claim(expr, sr.StockExpression_useCustomIntegral, expr);\r
+ \r
+ return expr;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getExpressionType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).StockExpression;\r
+ }\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class LookupExpression extends Expression {\r
+ \r
+ private String expression;\r
+ private double xMin;\r
+ private double yMin;\r
+ private double xMax;\r
+ private double yMax;\r
+ private double[] points;\r
+ \r
+ public LookupExpression(String expression, double xMin, double yMin, double xMax, double yMax, double[] points) {\r
+ this.expression = expression;\r
+ this.xMin = xMin;\r
+ this.yMin = yMin;\r
+ this.xMax = xMax;\r
+ this.yMax = yMax;\r
+ this.points = points;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ StringBuilder lookup = new StringBuilder();\r
+ lookup.append('{');\r
+ for (int i = 0; i < points.length / 2; i++) {\r
+ if (i > 0) {\r
+ lookup.append(',');\r
+ }\r
+ lookup.append('{').append(points[2*i]).append(',').append(points[2*i+1]).append('}');\r
+ }\r
+ lookup.append('}');\r
+ \r
+ Resource expr = super.write(graph, parent, context);\r
+ \r
+ // TODO: fix this\r
+ graph.claimLiteral(expr, sr.WithLookupExpression_expression, expression, Bindings.STRING);\r
+ graph.claimLiteral(expr, sr.WithLookupExpression_lookup, lookup.toString(), Bindings.STRING);\r
+ graph.claimLiteral(expr, sr.WithLookupExpression_minX, xMin, Bindings.DOUBLE);\r
+ graph.claimLiteral(expr, sr.WithLookupExpression_minY, yMin, Bindings.DOUBLE);\r
+ graph.claimLiteral(expr, sr.WithLookupExpression_maxX, xMax, Bindings.DOUBLE);\r
+ graph.claimLiteral(expr, sr.WithLookupExpression_maxY, yMax, Bindings.DOUBLE);\r
+ \r
+ return expr;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getExpressionType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).WithLookupExpression;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class NormalExpression extends Expression {\r
+\r
+ private String expression;\r
+ \r
+ public NormalExpression(String expression) {\r
+ this.expression = expression;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ Resource expr = super.write(graph, parent, context);\r
+ \r
+ graph.claimLiteral(expr, sr.Expression_equation, expression, Bindings.STRING);\r
+ \r
+ return expr;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getExpressionType(ReadGraph graph) {\r
+ return SysdynResource.getInstance(graph).NormalExpression;\r
+ }\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.support;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class Enumeration implements IWriteableObject {\r
+ \r
+ private String name;\r
+ private List<String> values;\r
+ \r
+ private Resource enumeration;\r
+ \r
+ public Enumeration(String name, List<String> values) {\r
+ this.name = name;\r
+ this.values = values;\r
+ }\r
+ \r
+ public String getName() {\r
+ return name;\r
+ }\r
+ \r
+ public List<String> getValues() {\r
+ return values;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context)\r
+ throws DatabaseException {\r
+ Layer0 l0 = Layer0.getInstance(graph);\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ enumeration = GraphUtils.create2(graph, sr.Enumeration,\r
+ l0.HasName, name,\r
+ l0.PartOf, parent);\r
+ \r
+ List<Resource> indices = new ArrayList<Resource>();\r
+ for (String index : values) {\r
+ indices.add(GraphUtils.create2(graph, sr.EnumerationIndex,\r
+ l0.HasName, index));\r
+ }\r
+ \r
+ graph.claim(enumeration, sr.Enumeration_enumerationIndexList, ListUtils.create(graph, indices));\r
+ \r
+ return enumeration;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getResource() {\r
+ return enumeration;\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.support;\r
+\r
+import java.util.List;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class Function implements IWriteableObject {\r
+\r
+ private String name;\r
+ private String body;\r
+ private String description;\r
+ \r
+ private Resource function;\r
+ \r
+ public Function(String name, String body) {\r
+ this(name, body, null);\r
+ }\r
+ \r
+ public Function(String name, String body, String description) {\r
+ this.name = name;\r
+ this.body = body;\r
+ this.description = description;\r
+ }\r
+ \r
+ public String getName() {\r
+ return name;\r
+ }\r
+ \r
+ public String getBody() {\r
+ return body;\r
+ }\r
+ \r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource parent, WriteContext context) \r
+ throws DatabaseException {\r
+ System.err.println("write function");\r
+ \r
+ Layer0 l0 = Layer0.getInstance(graph);\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ \r
+ function = GraphUtils.create2(graph, sr.SysdynModelicaFunction, \r
+ l0.HasName, name,\r
+ l0.PartOf, parent);\r
+ \r
+ graph.claimLiteral(function, sr.SysdynModelicaFunction_modelicaFunctionCode, body, Bindings.STRING);\r
+ \r
+ if (description != null) {\r
+ graph.claimLiteral(function, l0.HasDescription, body, Bindings.STRING);\r
+ }\r
+ \r
+ return function;\r
+ }\r
+\r
+ @Override\r
+ public Resource getResource() {\r
+ return function;\r
+ }\r
+ \r
+}\r
--- /dev/null
+package org.simantics.sysdyn.modelImport.model.support;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class Range implements IWriteableObject {\r
+ \r
+ private Double start;\r
+ private Double end;\r
+ private Double step;\r
+ \r
+ private Resource resource;\r
+ \r
+ public Range(Double start, Double end, Double step) {\r
+ this.start = start;\r
+ this.end = end;\r
+ this.step = step;\r
+ }\r
+ \r
+ public Double getStart() {\r
+ return start;\r
+ }\r
+\r
+ public Double getEnd() {\r
+ return end;\r
+ }\r
+\r
+ public Double getStep() {\r
+ return step;\r
+ }\r
+\r
+ @Override\r
+ public Resource write(WriteGraph graph, Resource variable, WriteContext context) throws DatabaseException {\r
+ return null;\r
+ }\r
+ \r
+ @Override\r
+ public Resource getResource() {\r
+ return resource;\r
+ }\r
+\r
+}\r
import org.simantics.sysdyn.representation.Sheet;\r
import org.simantics.sysdyn.representation.Stock;\r
import org.simantics.sysdyn.representation.Variable;\r
+import org.simantics.sysdyn.representation.expressions.DelayExpression;\r
+import org.simantics.sysdyn.representation.expressions.IExpression;\r
\r
/**\r
* ModelicaWriter writes Sysdyn model representations (objmap) into Modelica code.\r
*/\r
public class ModelicaWriter {\r
\r
- /**\r
- * Write a collection of configurations into a single Modelica code\r
- * @param isGame \r
- * \r
- * @param Configurations Configurations, one main configuration and possible modules\r
- * @return Complete Modelica code of a model\r
- */\r
- public static String write(Collection<Configuration> _configurations, boolean isGame, String omVersion) {\r
- \r
- ArrayList<Configuration> configurations = new ArrayList<Configuration>(_configurations);\r
- Collections.sort(configurations, new Comparator<Configuration>() {\r
-\r
- boolean uses(Configuration o1, Configuration o2) {\r
- ModuleType type = o2.getModuleType();\r
- if(type == null) return false;\r
- for(IElement e : o1.getElements()) {\r
- if(e instanceof Module) {\r
- Module m = (Module)e;\r
- if(m.getType().equals(type)) {\r
- return true;\r
- }\r
- }\r
- }\r
- return false;\r
- }\r
- \r
+ /**\r
+ * Write a collection of configurations into a single Modelica code\r
+ * @param isGame \r
+ * \r
+ * @param Configurations Configurations, one main configuration and possible modules\r
+ * @return Complete Modelica code of a model\r
+ */\r
+ public static String write(Collection<Configuration> _configurations, boolean isGame, String omVersion) {\r
+\r
+ ArrayList<Configuration> configurations = new ArrayList<Configuration>(_configurations);\r
+ Collections.sort(configurations, new Comparator<Configuration>() {\r
+\r
+ boolean uses(Configuration o1, Configuration o2) {\r
+ ModuleType type = o2.getModuleType();\r
+ if(type == null) return false;\r
+ for(IElement e : o1.getElements()) {\r
+ if(e instanceof Module) {\r
+ Module m = (Module)e;\r
+ if(m.getType().equals(type)) {\r
+ return true;\r
+ }\r
+ }\r
+ }\r
+ return false;\r
+ }\r
+\r
@Override\r
public int compare(Configuration o1, Configuration o2) {\r
- if(uses(o1, o2)) return 1;\r
- else if(uses(o2, o1)) return -1;\r
- else return 0;\r
+ if(uses(o1, o2)) return 1;\r
+ else if(uses(o2, o1)) return -1;\r
+ else return 0;\r
}\r
- \r
+\r
});\r
- \r
- Configuration modelConf = null;\r
- for(Configuration conf : configurations) {\r
- if(conf.getModel() != null) {\r
- modelConf = conf;\r
- }\r
- }\r
- StringBuilder b = new StringBuilder();\r
- \r
- int spreadsheetlocation = b.length();\r
-\r
- String modelName = modelConf.getLabel().replace(" ", "");\r
- b.append("model " + modelName + "\n");\r
-\r
- // Super class for enumerations\r
- b.append("partial class Enumeration_class\n");\r
- b.append(" parameter Integer size;\n");\r
- b.append(" parameter Integer elements[:];\n");\r
- b.append("end Enumeration_class;\n\n");\r
- \r
- \r
- HashSet<String> sheetNames = new HashSet<String>();\r
- for(Sheet sheet : getSpreadSheets(configurations))\r
- sheetNames.add(sheet.getModelicaName());\r
- \r
- // Write all module configurations to the declarations part (first)\r
- for(Configuration conf : configurations) {\r
- conf.setIsGameConfiguration(isGame);\r
- if(!conf.equals(modelConf))\r
- writeConfiguration(conf, sheetNames, b);\r
- }\r
- \r
- // Write model configuration last, so that equations-part does not contain module definitions\r
- modelConf.setIsGameConfiguration(isGame);\r
- writeConfiguration(modelConf, sheetNames, b);\r
- \r
- b.append("end " + modelName + ";\n\n");\r
- \r
- // Insert spreadsheets\r
- if(omVersion != null && omVersion.startsWith("1.9")) {\r
- b.insert(spreadsheetlocation, getGlobalSpreadSheets(configurations));\r
- } else {\r
- b.append(getGlobalSpreadSheets(configurations));\r
- }\r
-\r
- \r
- return b.toString();\r
- }\r
- \r
- /**\r
- * Get all spreadsheets that are found in the model\r
- * @param configurations\r
- * @return\r
- */\r
- private static List<Sheet> getSpreadSheets(Collection<Configuration> configurations) {\r
- for(Configuration conf : configurations) {\r
- if(conf.getModel() != null) {\r
- for(IElement e : conf.getElements()) {\r
- if(e instanceof Book) {\r
- return ((Book)e).getSheets();\r
- }\r
- }\r
- }\r
- }\r
- return Collections.emptyList();\r
- }\r
- \r
- /**\r
- * \r
- */\r
- private static String getGlobalSpreadSheets(Collection<Configuration> configurations) {\r
- StringBuilder sheets = new StringBuilder();\r
- for(Configuration conf : configurations) {\r
- if(conf.getModel() != null) {\r
- for(IElement e : conf.getElements()) {\r
- if(e instanceof Book) {\r
- return ((Book)e).getBook();\r
- }\r
- }\r
- }\r
- }\r
- \r
- return sheets.toString();\r
- }\r
-\r
- /**\r
- * Write a single configuration to a given string builder\r
- * \r
- * @param configuration Model or module configuration\r
- * @param b String builder\r
- */\r
- private static void writeConfiguration(Configuration configuration, HashSet<String> sheetNames, StringBuilder b) {\r
- boolean defTime = true;\r
- String app;\r
- \r
- // Lists for storing different configuration elements\r
- ArrayList<IndependentVariable> variables = new ArrayList<IndependentVariable>();\r
- ArrayList<Input> inputs = new ArrayList<Input>();\r
- ArrayList<Module> modules = new ArrayList<Module>();\r
- ArrayList<Stock> stocks = new ArrayList<Stock>();\r
- ArrayList<Enumeration> enumerations = new ArrayList<Enumeration>();\r
- ArrayList<Dependency> inputDependencies = new ArrayList<Dependency>();\r
- ArrayList<Dependency> outputDependencies = new ArrayList<Dependency>();\r
- HashMap<String, ArrayList<Input>> moduleInputs = new HashMap<String, ArrayList<Input>>();\r
-\r
- // Initialize lists\r
- for(IElement element : configuration.getElements()) {\r
- if(element instanceof IndependentVariable) {\r
- // Normal variable\r
- variables.add((IndependentVariable)element);\r
- if(element instanceof Stock)\r
- // Stock\r
- stocks.add((Stock)element);\r
- } else if (element instanceof Module) {\r
- // Module\r
- Module m = (Module)element; \r
- modules.add(m);\r
- moduleInputs.put(m.getName(), new ArrayList<Input>());\r
- for(IElement e : m.getType().getConfiguration().getElements())\r
- // Inputs inside the module\r
- if(e instanceof Input && !((Input)e).isHeadOfDependency()) {\r
- moduleInputs.get(m.getName()).add((Input)e);\r
- }\r
- } else if (element instanceof Input) {\r
- // Input variables\r
- inputs.add((Input)element);\r
- } else if (element instanceof Enumeration) {\r
- // Enumerations\r
- enumerations.add((Enumeration)element);\r
- } else if (element instanceof Dependency) {\r
- Dependency dependency = (Dependency)element;\r
- if(dependency.getHead() instanceof Module) {\r
- // References given to child modules\r
- outputDependencies.add(dependency);\r
- } else if(dependency.getTail() instanceof Module){\r
- // References from child modules\r
- inputDependencies.add(dependency);\r
- }\r
- }\r
- }\r
- \r
- // Setup input references. (Input, String reference to another variable)\r
- HashMap<Input, String> inputReferences = new HashMap<Input, String>();\r
- setupInputReferences(inputReferences, inputDependencies);\r
- \r
-\r
- // If the configuration is model configuration, use model name. Otherwise, use configuration name.\r
- ModuleType mt = configuration.getModuleType();\r
- \r
- // className == null, if this is a model configuration. model configuration start and end are written in ModelicaWriter.write\r
- String className = mt != null ? (mt.getName().replace(" ", "")) : null;\r
- \r
- if(className != null)\r
- b.append("\nclass ").append(className);\r
- \r
- // Add spreadsheets to all modules and model. Model is "inner" and modules "outer"\r
- String globalStatus = mt != null ? "outer" : "inner";\r
- for(String sheetName : sheetNames)\r
- b.append("\n " + globalStatus + " " + sheetName + "_class" + " "+ sheetName + ";");\r
- \r
- b.append("\n");\r
-\r
-\r
- if(!enumerations.isEmpty()) {\r
- b.append("// Enumeration definitions\n");\r
- for(Enumeration e : enumerations) {\r
- b.append(e.getDeclaration());\r
- }\r
- }\r
-\r
- b.append("// Variable definitions\n");\r
- for(IndependentVariable variable : variables) {\r
- app = variable.getDeclaration();\r
- if (app != null) b.append(app);\r
- }\r
- \r
- if(defTime) {\r
- // Time variable for FMU (game) simulations\r
- if(configuration.isGameConfiguration()) {\r
- if(configuration.getModel() != null)\r
- // Parameter for model root. Values changed in FMU simulator\r
- b.append(" parameter Real time = 0;\n");\r
- else\r
- // Continuous variable for module instances\r
- b.append(" Real time;\n");\r
-\r
- }\r
- }\r
-\r
- if(!modules.isEmpty()) {\r
- b.append("// Module definitions\n");\r
- for(Module m : modules) {\r
- b.append(m.getDeclaration());\r
- }\r
- }\r
-\r
-\r
- // Input definitions\r
- inputDefinitions(b, configuration, inputs, inputReferences);\r
-\r
- boolean initialEquations = false;\r
- for(Stock stock : stocks) {\r
- app = stock.getInitialEquation();\r
- if (app != null) {\r
- if(initialEquations == false) {\r
- initialEquations = true;\r
- b.append("// Initial Equations\n");\r
- b.append("initial equation\n");\r
- }\r
- b.append(app);\r
- }\r
- }\r
-\r
- boolean equation = false;\r
- b.append("// Equations\n");\r
- for(IndependentVariable variable : variables) {\r
- app = variable.getEquation();\r
- if (app != null) {\r
- if(!equation) {\r
- b.append("equation\n");\r
- equation = true;\r
- }\r
- \r
- b.append(app);\r
- }\r
- }\r
- \r
- // If "equation" has not been added but there are still equations to be defined, add "equation"\r
- if(!equation && (!inputReferences.isEmpty() || !outputDependencies.isEmpty() ||\r
- !moduleInputs.isEmpty() || !modules.isEmpty()))\r
- b.append("equation\n");\r
-\r
- // Continous input references\r
- continuousInputReferences(b, inputReferences);\r
- \r
- b.append("// Outputs\n");\r
- for(Dependency dependency : outputDependencies) {\r
- Variable variable = (Variable)dependency.getTail();\r
- Module module = (Module)dependency.getHead();\r
- Input reference = (Input)dependency.refersTo();\r
- if(reference != null && reference.getName() != null && (reference.getVariability() == null || reference.getVariability().isEmpty())) {\r
- b.append(" " + module.getName() + "." + reference.getModelicaName() + " = " + variable.getModelicaName() + ";\n");\r
- moduleInputs.get(module.getName()).remove(reference);\r
- }\r
- }\r
-\r
- b.append("// Default values for inputs in modules\n");\r
- for(String moduleLabel : moduleInputs.keySet()) {\r
- for(Input input : moduleInputs.get(moduleLabel)) {\r
- if(input.getVariability() == null || input.getVariability().isEmpty())\r
- b.append(" " + moduleLabel + "." + input.getModelicaName() + " = " + input.getDefaultInputValue(moduleLabel) + ";\n");\r
- }\r
- }\r
- \r
- if(defTime) {\r
- if(configuration.isGameConfiguration() && !modules.isEmpty()) {\r
- b.append("// Time values for module\n");\r
- for(Module m : modules) {\r
- b.append(" " + m.getName() + ".time = time;\n");\r
- }\r
- }\r
- }\r
-\r
- if(className != null)\r
- b.append("end ").append(className).append(";\n\n");\r
-\r
- }\r
- \r
+\r
+ Configuration modelConf = null;\r
+ for(Configuration conf : configurations) {\r
+ if(conf.getModel() != null) {\r
+ modelConf = conf;\r
+ }\r
+ }\r
+ StringBuilder b = new StringBuilder();\r
+\r
+ int spreadsheetlocation = b.length();\r
+\r
+ String modelName = modelConf.getLabel().replace(" ", "");\r
+ b.append("model " + modelName + "\n");\r
+\r
+ // Super class for enumerations\r
+ b.append("partial class Enumeration_class\n");\r
+ b.append(" parameter Integer size;\n");\r
+ b.append(" parameter Integer elements[:];\n");\r
+ b.append("end Enumeration_class;\n\n");\r
+\r
+ // find out which delays are used in the model and create the\r
+ // necessary classes\r
+ HashSet<Integer> delays = new HashSet<Integer>();\r
+ for (Configuration configuration : configurations) {\r
+ for (IElement element : configuration.getElements()) {\r
+ if (element instanceof IndependentVariable) {\r
+ for (IExpression expression : ((IndependentVariable)element).getExpressions()) {\r
+ if (expression instanceof DelayExpression) {\r
+ delays.add(((DelayExpression)expression).getOrder());\r
+ }\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ for (Integer i : delays) {\r
+ b.append(getDelayClass(i));\r
+ b.append("\n");\r
+ }\r
+\r
+ HashSet<String> sheetNames = new HashSet<String>();\r
+ for(Sheet sheet : getSpreadSheets(configurations))\r
+ sheetNames.add(sheet.getModelicaName());\r
+\r
+ // Write all module configurations to the declarations part (first)\r
+ for(Configuration conf : configurations) {\r
+ conf.setIsGameConfiguration(isGame);\r
+ if(!conf.equals(modelConf))\r
+ writeConfiguration(conf, sheetNames, b);\r
+ }\r
+\r
+ // Write model configuration last, so that equations-part does not contain module definitions\r
+ modelConf.setIsGameConfiguration(isGame);\r
+ writeConfiguration(modelConf, sheetNames, b);\r
+\r
+ b.append("end " + modelName + ";\n\n");\r
+\r
+ // Insert spreadsheets\r
+ if(omVersion != null && omVersion.startsWith("1.9")) {\r
+ b.insert(spreadsheetlocation, getGlobalSpreadSheets(configurations));\r
+ } else {\r
+ b.append(getGlobalSpreadSheets(configurations));\r
+ }\r
+\r
+ return b.toString();\r
+ }\r
+\r
+ /**\r
+ * Get all spreadsheets that are found in the model\r
+ * @param configurations\r
+ * @return\r
+ */\r
+ private static List<Sheet> getSpreadSheets(Collection<Configuration> configurations) {\r
+ for(Configuration conf : configurations) {\r
+ if(conf.getModel() != null) {\r
+ for(IElement e : conf.getElements()) {\r
+ if(e instanceof Book) {\r
+ return ((Book)e).getSheets();\r
+ }\r
+ }\r
+ }\r
+ }\r
+ return Collections.emptyList();\r
+ }\r
+\r
+ /**\r
+ * \r
+ */\r
+ private static String getGlobalSpreadSheets(Collection<Configuration> configurations) {\r
+ StringBuilder sheets = new StringBuilder();\r
+ for(Configuration conf : configurations) {\r
+ if(conf.getModel() != null) {\r
+ for(IElement e : conf.getElements()) {\r
+ if(e instanceof Book) {\r
+ return ((Book)e).getBook();\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ return sheets.toString();\r
+ }\r
+\r
/**\r
- * Define continuous input references\r
- * @param b String builder\r
- * @param inputReferences Input references\r
- */\r
- private static void continuousInputReferences(StringBuilder b, HashMap<Input, String> inputReferences) {\r
- b.append("// Inputs\n");\r
- for(Input i : inputReferences.keySet()) {\r
- if(i.getVariability() == null || i.getVariability().isEmpty()) {\r
- // Define only continuous variables here\r
- b.append(" " + i.getModelicaName() + " = " + inputReferences.get(i));\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Setup input references for all inputs that are defined in child modules\r
- * \r
- * @param inputReferences Map containing the references\r
- * @param inputDependencies List of input dependencies\r
- */\r
- private static void setupInputReferences(HashMap<Input, String> inputReferences, ArrayList<Dependency> inputDependencies) {\r
- for(Dependency dependency : inputDependencies) {\r
- Input input = (Input)dependency.getHead();\r
- Module module = (Module)dependency.getTail();\r
- Variable reference = (Variable)dependency.refersTo();\r
- String expression;\r
- // If reference exists, use reference name. Otherwise, use default value.\r
- if(reference != null && reference.getName() != null)\r
- expression = module.getName() + "." + reference.getModelicaName() + ";\n";\r
-\r
- else\r
- expression = input.getDefaultInputValue() + ";\n";\r
- \r
- inputReferences.put(input, expression);\r
- }\r
- }\r
-\r
- /**\r
- * Build input definitions\r
- * \r
- * @param b String builder\r
- * @param configuration Module configuration\r
- * @param inputs All inputs of this module\r
- * @param inputReferences \r
- */\r
- private static void inputDefinitions(StringBuilder b, Configuration configuration, ArrayList<Input> inputs, HashMap<Input, String> inputReferences) {\r
- if(inputs.isEmpty())\r
- return;\r
- \r
- b.append("// Input definitions\n");\r
- for(Input i : inputs) {\r
- if(i.getVariability() != null && !i.getVariability().isEmpty()) {\r
- // Input is NOT continuous\r
- if(inputReferences.containsKey(i)) {\r
- // Input is defined in a child module\r
- String declaration = i.getDeclaration();\r
- declaration = declaration.substring(0, declaration.length() - 2); // remove ";\n" from the end\r
- b.append(declaration + " = " + inputReferences.get(i));\r
- } else {\r
- // Input is not defined in a child module, use default value\r
- b.append(i.getDeclarationWithValue());\r
- }\r
- } else if(configuration.getModel() != null && !i.isHeadOfDependency()) {\r
- /*\r
- * Input is in the top of the hierarchy, \r
- * and it does not get value from anywhere else.\r
- * => Declare it wit its default value \r
- */\r
- b.append(i.getDeclarationWithValue());\r
- } else {\r
- // Continuous => Parent module takes care of declaring a value for the input\r
- b.append(i.getDeclaration());\r
- }\r
- }\r
- }\r
-\r
- public String escape(String name) {\r
- return name.replace(' ', '_');\r
- }\r
+ * Write a single configuration to a given string builder\r
+ * \r
+ * @param configuration Model or module configuration\r
+ * @param b String builder\r
+ */\r
+ private static void writeConfiguration(Configuration configuration, HashSet<String> sheetNames, StringBuilder b) {\r
+ boolean defTime = true;\r
+ String app;\r
+\r
+ // Lists for storing different configuration elements\r
+ ArrayList<IndependentVariable> variables = new ArrayList<IndependentVariable>();\r
+ ArrayList<Input> inputs = new ArrayList<Input>();\r
+ ArrayList<Module> modules = new ArrayList<Module>();\r
+ ArrayList<Stock> stocks = new ArrayList<Stock>();\r
+ ArrayList<Enumeration> enumerations = new ArrayList<Enumeration>();\r
+ ArrayList<Dependency> inputDependencies = new ArrayList<Dependency>();\r
+ ArrayList<Dependency> outputDependencies = new ArrayList<Dependency>();\r
+ HashMap<String, ArrayList<Input>> moduleInputs = new HashMap<String, ArrayList<Input>>();\r
+\r
+ // Initialize lists\r
+ for(IElement element : configuration.getElements()) {\r
+ if(element instanceof IndependentVariable) {\r
+ // Normal variable\r
+ variables.add((IndependentVariable)element);\r
+ if(element instanceof Stock)\r
+ // Stock\r
+ stocks.add((Stock)element);\r
+ } else if (element instanceof Module) {\r
+ // Module\r
+ Module m = (Module)element; \r
+ modules.add(m);\r
+ moduleInputs.put(m.getName(), new ArrayList<Input>());\r
+ for(IElement e : m.getType().getConfiguration().getElements())\r
+ // Inputs inside the module\r
+ if(e instanceof Input && !((Input)e).isHeadOfDependency()) {\r
+ moduleInputs.get(m.getName()).add((Input)e);\r
+ }\r
+ } else if (element instanceof Input) {\r
+ // Input variables\r
+ inputs.add((Input)element);\r
+ } else if (element instanceof Enumeration) {\r
+ // Enumerations\r
+ enumerations.add((Enumeration)element);\r
+ } else if (element instanceof Dependency) {\r
+ Dependency dependency = (Dependency)element;\r
+ if(dependency.getHead() instanceof Module) {\r
+ // References given to child modules\r
+ outputDependencies.add(dependency);\r
+ } else if(dependency.getTail() instanceof Module){\r
+ // References from child modules\r
+ inputDependencies.add(dependency);\r
+ }\r
+ }\r
+ }\r
+\r
+ // Setup input references. (Input, String reference to another variable)\r
+ HashMap<Input, String> inputReferences = new HashMap<Input, String>();\r
+ setupInputReferences(inputReferences, inputDependencies);\r
+\r
+\r
+ // If the configuration is model configuration, use model name. Otherwise, use configuration name.\r
+ ModuleType mt = configuration.getModuleType();\r
+\r
+ // className == null, if this is a model configuration. model configuration start and end are written in ModelicaWriter.write\r
+ String className = mt != null ? (mt.getName().replace(" ", "")) : null;\r
+\r
+ if(className != null)\r
+ b.append("class "+className+"\n").append(className);\r
+\r
+ // Add spreadsheets to all modules and model. Model is "inner" and modules "outer"\r
+ String globalStatus = mt != null ? "outer" : "inner";\r
+ for(String sheetName : sheetNames)\r
+ b.append(" " + globalStatus + " " + sheetName + "_class" + " "+ sheetName + ";\n");\r
+\r
+ if(!enumerations.isEmpty()) {\r
+ b.append("// Enumeration definitions\n");\r
+ for(Enumeration e : enumerations) {\r
+ b.append(e.getDeclaration());\r
+ }\r
+ }\r
+\r
+ b.append("// Variable definitions\n");\r
+ for(IndependentVariable variable : variables) {\r
+ app = variable.getDeclaration();\r
+ if (app != null) b.append(app);\r
+ }\r
+\r
+ if(defTime) {\r
+ // Time variable for FMU (game) simulations\r
+ if(configuration.isGameConfiguration()) {\r
+ if(configuration.getModel() != null)\r
+ // Parameter for model root. Values changed in FMU simulator\r
+ b.append(" parameter Real time = 0;\n");\r
+ else\r
+ // Continuous variable for module instances\r
+ b.append(" Real time;\n");\r
+\r
+ }\r
+ }\r
+\r
+ if(!modules.isEmpty()) {\r
+ b.append("// Module definitions\n");\r
+ for(Module m : modules) {\r
+ b.append(m.getDeclaration());\r
+ }\r
+ }\r
+\r
+\r
+ // Input definitions\r
+ inputDefinitions(b, configuration, inputs, inputReferences);\r
+\r
+ boolean initialEquations = false;\r
+ for(Stock stock : stocks) {\r
+ app = stock.getInitialEquation();\r
+ if (app != null) {\r
+ if(initialEquations == false) {\r
+ initialEquations = true;\r
+ b.append("// Initial Equations\n");\r
+ b.append("initial equation\n");\r
+ }\r
+ b.append(app);\r
+ }\r
+ }\r
+\r
+ boolean equation = false;\r
+ b.append("// Equations\n");\r
+ for(IndependentVariable variable : variables) {\r
+ app = variable.getEquation();\r
+ if (app != null) {\r
+ if(!equation) {\r
+ b.append("equation\n");\r
+ equation = true;\r
+ }\r
+\r
+ b.append(app);\r
+ }\r
+ }\r
+\r
+ // If "equation" has not been added but there are still equations to be defined, add "equation"\r
+ if(!equation && (!inputReferences.isEmpty() || !outputDependencies.isEmpty() ||\r
+ !moduleInputs.isEmpty() || !modules.isEmpty()))\r
+ b.append("equation\n");\r
+\r
+ // Continuous input references\r
+ continuousInputReferences(b, inputReferences);\r
+\r
+ b.append("// Outputs\n");\r
+ for(Dependency dependency : outputDependencies) {\r
+ Variable variable = (Variable)dependency.getTail();\r
+ Module module = (Module)dependency.getHead();\r
+ Input reference = (Input)dependency.refersTo();\r
+ if(reference != null && reference.getName() != null && (reference.getVariability() == null || reference.getVariability().isEmpty())) {\r
+ b.append(" " + module.getName() + "." + reference.getModelicaName() + " = " + variable.getModelicaName() + ";\n");\r
+ moduleInputs.get(module.getName()).remove(reference);\r
+ }\r
+ }\r
+\r
+ b.append("// Default values for inputs in modules\n");\r
+ for(String moduleLabel : moduleInputs.keySet()) {\r
+ for(Input input : moduleInputs.get(moduleLabel)) {\r
+ if(input.getVariability() == null || input.getVariability().isEmpty())\r
+ b.append(" " + moduleLabel + "." + input.getModelicaName() + " = " + input.getDefaultInputValue(moduleLabel) + ";\n");\r
+ }\r
+ }\r
+\r
+ if(defTime) {\r
+ if(configuration.isGameConfiguration() && !modules.isEmpty()) {\r
+ b.append("// Time values for module\n");\r
+ for(Module m : modules) {\r
+ b.append(" " + m.getName() + ".time = time;\n");\r
+ }\r
+ }\r
+ }\r
+\r
+ if(className != null)\r
+ b.append("end ").append(className).append(";\n\n");\r
+\r
+ }\r
+\r
+ /**\r
+ * Define continuous input references\r
+ * @param b String builder\r
+ * @param inputReferences Input references\r
+ */\r
+ private static void continuousInputReferences(StringBuilder b, HashMap<Input, String> inputReferences) {\r
+ b.append("// Inputs\n");\r
+ for(Input i : inputReferences.keySet()) {\r
+ if(i.getVariability() == null || i.getVariability().isEmpty()) {\r
+ // Define only continuous variables here\r
+ b.append(" " + i.getModelicaName() + " = " + inputReferences.get(i));\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Setup input references for all inputs that are defined in child modules\r
+ * \r
+ * @param inputReferences Map containing the references\r
+ * @param inputDependencies List of input dependencies\r
+ */\r
+ private static void setupInputReferences(HashMap<Input, String> inputReferences, ArrayList<Dependency> inputDependencies) {\r
+ for(Dependency dependency : inputDependencies) {\r
+ Input input = (Input)dependency.getHead();\r
+ Module module = (Module)dependency.getTail();\r
+ Variable reference = (Variable)dependency.refersTo();\r
+ String expression;\r
+ // If reference exists, use reference name. Otherwise, use default value.\r
+ if(reference != null && reference.getName() != null)\r
+ expression = module.getName() + "." + reference.getModelicaName() + ";\n";\r
+\r
+ else\r
+ expression = input.getDefaultInputValue() + ";\n";\r
+\r
+ inputReferences.put(input, expression);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Build input definitions\r
+ * \r
+ * @param b String builder\r
+ * @param configuration Module configuration\r
+ * @param inputs All inputs of this module\r
+ * @param inputReferences \r
+ */\r
+ private static void inputDefinitions(StringBuilder b, Configuration configuration, ArrayList<Input> inputs, HashMap<Input, String> inputReferences) {\r
+ if(inputs.isEmpty())\r
+ return;\r
+\r
+ b.append("// Input definitions\n");\r
+ for(Input i : inputs) {\r
+ if(i.getVariability() != null && !i.getVariability().isEmpty()) {\r
+ // Input is NOT continuous\r
+ if(inputReferences.containsKey(i)) {\r
+ // Input is defined in a child module\r
+ String declaration = i.getDeclaration();\r
+ declaration = declaration.substring(0, declaration.length() - 2); // remove ";\n" from the end\r
+ b.append(declaration + " = " + inputReferences.get(i));\r
+ } else {\r
+ // Input is not defined in a child module, use default value\r
+ b.append(i.getDeclarationWithValue());\r
+ }\r
+ } else if(configuration.getModel() != null && !i.isHeadOfDependency()) {\r
+ /*\r
+ * Input is in the top of the hierarchy, \r
+ * and it does not get value from anywhere else.\r
+ * => Declare it wit its default value \r
+ */\r
+ b.append(i.getDeclarationWithValue());\r
+ } else {\r
+ // Continuous => Parent module takes care of declaring a value for the input\r
+ b.append(i.getDeclaration());\r
+ }\r
+ }\r
+ }\r
+\r
+ public String escape(String name) {\r
+ return name.replace(' ', '_');\r
+ }\r
+ \r
+ public static final String DELAY_TIME = "delayTime";\r
+ public static final String DELAY_INITIAL = "initialValue";\r
+\r
+ private static String getDelayClass(int order) {\r
+ StringBuilder buffer = new StringBuilder();\r
+\r
+ buffer.append("class " + getDelayName(order) + "\n");\r
+\r
+ // variable block\r
+\r
+ // (possibly) continuous auxiliary variable\r
+ buffer.append("\tReal DL;\n");\r
+ // (possibly) continuous delay time\r
+ buffer.append("\tReal " + DELAY_TIME + ";\n");\r
+ // (possibly) continuous initial value\r
+ buffer.append("\tReal " + DELAY_INITIAL + ";\n");\r
+\r
+ // first valve\r
+ buffer.append("\tReal " + getDelayValve(0) + ";\n");\r
+\r
+ // stocks and valves, valves are delayed values of the variable\r
+ for (int i = 1; i <= order; i++) {\r
+ buffer.append("\tReal LV"+i + "(fixed=false);\n");\r
+ buffer.append("\tReal "+ getDelayValve(i) + ";\n");\r
+ }\r
+\r
+ // initial equation block\r
+ buffer.append("initial equation\n");\r
+\r
+ // Each stock gets the same initial value\r
+ for (int i = 1; i <= order; i++) {\r
+ buffer.append("\tLV"+i + " = DL * " + DELAY_INITIAL + ";\n");\r
+ }\r
+\r
+ // equation block\r
+ buffer.append("equation\n");\r
+ \r
+ buffer.append("\tDL = " + DELAY_TIME + " / "+order+";\n");\r
+\r
+ // valves and stocks\r
+ for (int i = 1; i <= order; i++) {\r
+ buffer.append("\tder(LV"+i + ") = - " + getDelayValve(i) + " + " + getDelayValve(i-1) + ";\n");\r
+ buffer.append("\t"+ getDelayValve(i) + " = LV"+i + " / DL;\n");\r
+ }\r
+\r
+ buffer.append("end ");\r
+ buffer.append(getDelayName(order));\r
+ buffer.append(";\n");\r
+\r
+ return buffer.toString();\r
+ }\r
+\r
+ public static String getDelayName(int order) {\r
+ return "order_"+order+"_delay";\r
+ }\r
+ \r
+ public static String getDelayValve(int order) {\r
+ return "delay"+order;\r
+ }\r
\r
}\r
\r
// ;\n\r
sb.append(";\n");\r
-\r
+ \r
// Possible additions to expressions. e.g. helper classes and variables\r
if(getExpressions() != null) {\r
- String addition;\r
for(IExpression e : getExpressions()) {\r
- addition = e.getDeclarationAddition();\r
+ String addition = e.getDeclarationAddition();\r
if(addition != null)\r
sb.append(addition);\r
}\r
if (Variability.getVariability(this) == Variability.CONTINUOUS) {\r
// start parameter is not used, everything needs to be fixed=false\r
if(getArrayIndexes() != null && !getArrayIndexes().isEmpty())\r
- each = "each";\r
- return " " + getType() + " " + getModelicaName() + getRange() + "(" + each + " fixed=false);\n";\r
+ each = "each ";\r
+ return " " + getType() + " " + getModelicaName() + getRange() + "(" + each + "fixed=false);\n";\r
} else {\r
// Start parameter is used. Parameter guarantees that there is only one expression.\r
StockExpression e = (StockExpression)getExpressions().get(0);\r
initialEquation = SheetFormatUtils.reformatSheetReferences(this, initialEquation);\r
\r
if(getArrayIndexes() != null && !getArrayIndexes().isEmpty())\r
- each = "each";\r
-\r
+ each = "each ";\r
\r
+ // TODO: there is probably a bug with startvalue here\r
return " " + \r
getType() + \r
" " + \r
getRange() + \r
"(" + \r
(e.getStartValue() != null ? each : "") + \r
- " start=" + \r
+ "start=" + \r
initialEquation + \r
", " + \r
each + \r
- " fixed=true);\n";\r
+ "fixed=true);\n";\r
}\r
}\r
\r
import org.simantics.objmap.annotations.RelatedValue;\r
import org.simantics.sysdyn.SysdynResource;\r
import org.simantics.sysdyn.manager.SysdynModel;\r
-import org.simantics.sysdyn.representation.IndependentVariable;\r
-import org.simantics.sysdyn.representation.Variability;\r
+import org.simantics.sysdyn.modelica.ModelicaWriter;\r
import org.simantics.sysdyn.representation.utils.FormatUtils;\r
import org.simantics.sysdyn.representation.utils.IndexUtils;\r
import org.simantics.sysdyn.representation.utils.UnitUtils;\r
@GraphType(SysdynResource.URIs.DelayExpression)\r
public class DelayExpression extends Expression {\r
\r
- @RelatedValue(SysdynResource.URIs.DelayExpression_initialValue)\r
- private String initialValue;\r
-\r
- @RelatedValue(SysdynResource.URIs.DelayExpression_delayTime)\r
- private String delayTime;\r
-\r
- @RelatedValue(SysdynResource.URIs.DelayExpression_order)\r
- private Integer order;\r
-\r
- @RelatedValue(SysdynResource.URIs.DelayExpression_expression)\r
- private String equation;\r
-\r
- @Override\r
- public String getDeclarationAddition() {\r
- String delayTime = FormatUtils.replaceWhitespace(this.delayTime);\r
- delayTime = FormatUtils.formatExpressionForModelica(parent, delayTime);\r
- String initialValue = FormatUtils.replaceWhitespace(this.initialValue);\r
- initialValue = FormatUtils.formatExpressionForModelica(parent, initialValue);\r
- Variability delayTimeVariability = Variability.getVariability((IndependentVariable)parent, delayTime);\r
- Variability initialVariability = Variability.CONTINUOUS;\r
- if(initialValue != null && initialValue.length() > 0) {\r
- /*\r
- * By default, initial value variability is continuous.\r
- * If initial value has been set, it can be some other. \r
- */\r
- initialVariability = Variability.getVariability(parent, initialValue);\r
- }\r
-\r
-\r
- StringBuilder declaration = new StringBuilder();\r
-\r
- String range = parent.getRange();\r
-\r
- // Delay declaration\r
- declaration.append(" " + parent.getModelicaName() + "_delayClass " + parent.getModelicaName() + "_delayClass_instance");\r
-\r
- // Change enumeration sizes from the delay class. Supports overridden enumerations in modules.\r
- if(range.length() > 0 || !initialVariability.equals(Variability.CONTINUOUS) || !delayTimeVariability.equals(Variability.CONTINUOUS)) {\r
- declaration.append("(");\r
-\r
- boolean started = false;\r
- if(range.length() > 0) {\r
- started = true;\r
- String[] ranges = range.substring(1, range.length() - 1).split(",");\r
- for(int i = 0; i < ranges.length; i++ ) {\r
- String r = ranges[i];\r
- declaration.append(r.replace(".size", "size") + " = " + r);\r
- if(i < ranges.length - 1) {\r
- declaration.append(", ");\r
- }\r
- }\r
- }\r
-\r
- // If initial value is not continuous, it is set in the module declaration\r
- if(!initialVariability.equals(Variability.CONTINUOUS)) {\r
- if(started)\r
- declaration.append(", ");\r
- started = true;\r
- declaration.append("initialValue = " + initialValue);\r
- }\r
-\r
- // If delay time is not continuous, it is set in the module declaration \r
- if(!delayTimeVariability.equals(Variability.CONTINUOUS)) {\r
- if(started)\r
- declaration.append(", ");\r
- declaration.append("delayTime = " + delayTime);\r
- }\r
-\r
- declaration.append(")");\r
- }\r
- declaration.append(";\n");\r
-\r
- // Write the delay class\r
- declaration.append(getDelayClass(range, order));\r
- return declaration.toString();\r
- }\r
-\r
- /**\r
- * Creates a class that is used to implement the delay. Class contains\r
- * a basic delay structure with "stocks and flows". The number of \r
- * stocks and flows is determined by the order of the delay\r
- * \r
- * @param variable The variable for which the delay is created\r
- * @param range Array range\r
- * @param n Order of the delay\r
- * @return\r
- */\r
- private String getDelayClass(String range, int n) {\r
- StringBuilder sb = new StringBuilder();\r
-\r
- sb.append("class " + parent.getModelicaName() + "_delayClass\n");\r
-\r
- // Enumeration sizes as parameters. Sizes correspond the enumeration sizes of variable\r
- if(range.length() > 0) {\r
- range = range.replaceAll(".size", "size");\r
- for(String r : range.substring(1, range.length() - 1).split(",")) {\r
- sb.append("\t parameter Integer " + r + ";\n");\r
- }\r
- }\r
-\r
- String delayTime = FormatUtils.replaceWhitespace(this.delayTime);\r
- String dt = FormatUtils.formatExpressionForModelica(parent,delayTime);\r
- Variability delayTimeVariability = Variability.getVariability(parent, dt);\r
- if(!delayTimeVariability.equals(Variability.CONTINUOUS)) {\r
- // Auxiliary variable\r
- sb.append("\t" + delayTimeVariability.getText() + " Real" + range + " DL = delayTime/" + n + ";\n");\r
- // Delay time\r
- sb.append("\t" + delayTimeVariability.getText() + " Real" + range + " delayTime;\n");\r
- } else {\r
- // Continuous auxiliary variable\r
- sb.append("\tReal" + range + " DL;\n");\r
- // Continuous delay time\r
- sb.append("\tReal" + range + " delayTime;\n");\r
- }\r
-\r
-\r
- // Get initial value variability\r
- Variability initialValueVariability = Variability.CONTINUOUS;\r
- String initEquation = FormatUtils.replaceWhitespace(this.initialValue);\r
- initEquation = FormatUtils.formatExpressionForModelica(parent, initEquation);\r
- if(initialValue != null && initialValue.length() > 0) {\r
- initialValueVariability = Variability.getVariability(parent, initEquation);\r
- }\r
-\r
- // Declare initial value (continuous or other)\r
- String ivv = !initialValueVariability.equals(Variability.CONTINUOUS) ? initialValueVariability.getText() + " " : "";\r
- sb.append("\t" + ivv + "Real" + range + " initialValue;\n");\r
-\r
- // First valve\r
- sb.append("\tReal" + range + " delay0;\n");\r
-\r
- // Stocks and valves. Valves are the delayed values of the variable\r
- for(int i = 1; i <= n; i++) {\r
- if(initialValueVariability.equals(Variability.CONTINUOUS) || delayTimeVariability.equals(Variability.CONTINUOUS))\r
- // Continuous initial value or delay time\r
- sb.append("\tReal" + range + " LV" + i + "(" + (range.length() > 0 ? "each " : "") + "fixed=false);\n");\r
- else\r
- // initial value and delay time are not continuous\r
- sb.append("\tReal" + range + " LV" + i + \r
- "(" + (range.length() > 0 ? "each " : "") + "fixed=true, start=initialValue " + (range.isEmpty() ? "*" : ".*") + " DL);\n");\r
- sb.append("\tReal" + range + " delay" + i + ";\n");\r
- }\r
-\r
- // If initial value or delay time are continuous, use initial equation block\r
- if(initialValueVariability.equals(Variability.CONTINUOUS) || delayTimeVariability.equals(Variability.CONTINUOUS)) {\r
- sb.append("initial equation\n");\r
-\r
- // Each stock gets the same initial value\r
- for(int i = 1; i <= n; i++)\r
- sb.append("\tLV" + i +" = DL " + (range.isEmpty() ? "*" : ".*") + " initialValue;\n");\r
- }\r
-\r
- // Equation block\r
- sb.append("equation\n");\r
-\r
- if(delayTimeVariability.equals(Variability.CONTINUOUS))\r
- sb.append("\tDL = delayTime/" + n + ";\n");\r
-\r
- // Valves and stocks\r
- for(int i = 1; i <= n; i++) {\r
- sb.append("\tder(LV" + i + ") = - delay" + i + " + delay" + (i - 1) + ";\n");\r
- sb.append("\tdelay" + i + " = LV" + i + " " + (range.isEmpty() ? "/" : "./") + "DL;\n");\r
- }\r
-\r
- sb.append("end " + parent.getModelicaName() + "_delayClass;\n");\r
- return sb.toString();\r
- }\r
-\r
- @Override\r
- public String getEquation() {\r
- StringBuilder sb = new StringBuilder();\r
-\r
- String equation = FormatUtils.replaceWhitespace(this.equation);\r
- equation = FormatUtils.formatExpressionForModelica(parent, equation);\r
- String delayTime = FormatUtils.replaceWhitespace(this.delayTime);\r
- delayTime = FormatUtils.formatExpressionForModelica(parent, delayTime);\r
- String initialValue = FormatUtils.replaceWhitespace(this.initialValue);\r
- initialValue = FormatUtils.formatExpressionForModelica(parent, initialValue);\r
-\r
- // First "valve" in the delay\r
- sb.append(" " + parent.getModelicaName() + "_delayClass_instance.delay0 = " + equation + ";\n");\r
-\r
- // Delay time (if continuous)\r
- Variability delayTimeVariability = Variability.getVariability(parent, delayTime);\r
- if(delayTimeVariability.equals(Variability.CONTINUOUS)) {\r
- sb.append(" " + parent.getModelicaName() + "_delayClass_instance.delayTime = " + delayTime + ";\n");\r
- }\r
-\r
- // Initial value\r
- if(initialValue == null || initialValue.length() == 0) {\r
- // No initial value set, use delay0 (the first "valve")\r
- sb.append(" " + parent.getModelicaName() + "_delayClass_instance.initialValue = " + parent.getModelicaName() + "_delayClass_instance.delay0;\n");\r
- } else {\r
- // Continuous initial value\r
- Variability initialVariability = Variability.getVariability(parent, initialValue);\r
- if(initialVariability.equals(Variability.CONTINUOUS)) {\r
- sb.append(" " + parent.getModelicaName() + "_delayClass_instance.initialValue = " + initialValue + ";\n");\r
- }\r
- }\r
-\r
- // The value of the actual variable\r
- String range = IndexUtils.rangeToIndexes(parent, this.getArrayRange());\r
- sb.append(" " + parent.getModelicaName() + (range.equals("[:]") ? "" : range) + " = " + parent.getModelicaName() + "_delayClass_instance.delay" + order + ";\n");\r
- return sb.toString();\r
- }\r
-\r
- @Override\r
- public String getExpression() {\r
- return "This + is + not + a + parameter + at + any + time";\r
- }\r
-\r
- @Override\r
- public String getModelicaExpression() {\r
- return getExpression();\r
- }\r
-\r
- @Override\r
- public String validateUnits(ReadGraph graph, SysdynModel model) {\r
- if(parent.getUnit() == null)\r
- return "Unit not defined for " + parent.getName();\r
- \r
- String result = UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), parent.getUnit(), equation);\r
- if(result == null)\r
- result = UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), parent.getUnit(), initialValue);\r
- if(result == null)\r
- result = UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), UnitUtils.getTimeUnit(graph, model), delayTime);\r
- \r
- return result;\r
- }\r
+ @RelatedValue(SysdynResource.URIs.DelayExpression_initialValue)\r
+ private String initialValue;\r
+\r
+ @RelatedValue(SysdynResource.URIs.DelayExpression_delayTime)\r
+ private String delayTime;\r
+\r
+ @RelatedValue(SysdynResource.URIs.DelayExpression_order)\r
+ private Integer order;\r
+\r
+ @RelatedValue(SysdynResource.URIs.DelayExpression_expression)\r
+ private String equation;\r
+\r
+ @Override\r
+ public String getDeclarationAddition() {\r
+ // instantiate the correct delay class for this expression\r
+ return "\t" + ModelicaWriter.getDelayName(order) + " " + instance() + ";\n";\r
+ }\r
+\r
+ @Override\r
+ public String getEquation() {\r
+ StringBuilder sb = new StringBuilder();\r
+\r
+ String equation = FormatUtils.replaceWhitespace(this.equation);\r
+ equation = FormatUtils.formatExpressionForModelica(parent, equation);\r
+ String delayTime = FormatUtils.replaceWhitespace(this.delayTime);\r
+ delayTime = FormatUtils.formatExpressionForModelica(parent, delayTime);\r
+ String initialValue = FormatUtils.replaceWhitespace(this.initialValue);\r
+ initialValue = FormatUtils.formatExpressionForModelica(parent, initialValue);\r
+\r
+ sb.append("\t" + instance() + "." + ModelicaWriter.getDelayValve(0) + " = " + equation + ";\n");\r
+\r
+ sb.append("\t" + instance() + "." + ModelicaWriter.DELAY_TIME + " = " + delayTime + ";\n");\r
+\r
+ sb.append("\t" + instance() + "." + ModelicaWriter.DELAY_INITIAL + " = ");\r
+ if (initialValue != null && !initialValue.isEmpty()) {\r
+ sb.append(initialValue);\r
+ } \r
+ else {\r
+ // if an initial value is not set, use the value of the first valve\r
+ sb.append(instance() + "." + ModelicaWriter.getDelayValve(0));\r
+ }\r
+ sb.append(";\n");\r
+\r
+ // set the value of the variable\r
+ String range = IndexUtils.rangeToIndexes(parent, getArrayRange());\r
+ // TODO: this variable name thing here (and in other expressions) is a hack and should be fixed\r
+ sb.append("\t" + parent.getModelicaName() + (range.equals("[:]") ? "" : range) + " = " + \r
+ instance() + "." + ModelicaWriter.getDelayValve(order) + ";\n");\r
+ \r
+ return sb.toString();\r
+ }\r
+\r
+ @Override\r
+ public String getExpression() {\r
+ return "This + is + not + a + parameter + at + any + time";\r
+ }\r
+\r
+ @Override\r
+ public String getModelicaExpression() {\r
+ return getExpression();\r
+ }\r
+\r
+ @Override\r
+ public String validateUnits(ReadGraph graph, SysdynModel model) {\r
+ if(parent.getUnit() == null)\r
+ return "Unit not defined for " + parent.getName();\r
+\r
+ String result = UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), parent.getUnit(), equation);\r
+ if(result == null)\r
+ result = UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), parent.getUnit(), initialValue);\r
+ if(result == null)\r
+ result = UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), UnitUtils.getTimeUnit(graph, model), delayTime);\r
+\r
+ return result;\r
+ }\r
+\r
+ public int getOrder() {\r
+ return order;\r
+ }\r
+\r
+ private String instance() {\r
+ // construct an identifier for this expression based on the array \r
+ // indices if necessary\r
+ String identifier;\r
+ if (getArrayRange() != null && !getArrayRange().isEmpty()) {\r
+ identifier = IndexUtils.rangeToIndexes(parent, getArrayRange()).replaceAll("[\\[\\]{},]", "_");\r
+ }\r
+ else {\r
+ identifier = "_";\r
+ }\r
+ return parent.getModelicaName() + identifier + "instance";\r
+ }\r
\r
}\r
\r
/**\r
* Get any possible additions to variable declaration.\r
- * \r
- * @param variable Declared independent variable\r
* @return additions or null\r
*/\r
String getDeclarationAddition();\r
\r
/**\r
* Initial value for this variable and expression\r
- * @param variable IndependentVariable\r
* @return initial value or null\r
*/\r
String getInitialEquation();\r
\r
/**\r
* Get the actual equation of this expression\r
- * @param variable IndependentVariable\r
* @return equation or null\r
*/\r
String getEquation();\r
\r
/**\r
* Get the plain (possibly unformatted) expression from this expression. (type variable = EXPRESSION ;\n)\r
- * @param variable\r
- * @return\r
+ * @return \r
*/\r
String getExpression();\r
\r
String equation = FormatUtils.replaceWhitespace(this.equation);\r
return equation + " /* Actual value read from init file */";\r
}\r
- \r
- @Override\r
- public String getDeclarationAddition() {\r
- return ""; \r
- }\r
\r
\r
/**\r
// Stock equation is always der(Stock)\r
StringBuilder b = new StringBuilder();\r
b.append(" der(")\r
- .append(modelicaEquation ? parent.getModelicaName() : parent.getName() + range)\r
+ .append(parent.getModelicaName() + (range.equals("[:]") ? "" : range))\r
.append(") = ");\r
\r
if (integralEquation != null) {\r
try {\r
value = Double.parseDouble(initialEquation);\r
} catch(NumberFormatException e1) {\r
- \r
+ return null;\r
}\r
}\r
}\r
DefaultXYDataset dataset = new DefaultXYDataset();\r
dataset.addSeries("lookup", new double[][] {y, x});\r
JFreeChart chart = ChartFactory.createXYLineChart(\r
- "", // chart title\r
- "", // domain axis label\r
- "", // range axis label\r
- dataset, // data\r
+ "", // chart title\r
+ "", // domain axis label\r
+ "", // range axis label\r
+ dataset, // data\r
PlotOrientation.HORIZONTAL, // Orientation\r
- false, // include legend\r
- false, // tooltips\r
- false // urls\r
+ false, // include legend\r
+ false, // tooltips\r
+ false // urls\r
);\r
\r
StringWriter writer = new StringWriter();\r
\r
public class RepresentationUtils {\r
\r
-\r
/**\r
* Returns true, if there is an active experiment and the active experiment\r
* is a game experiment\r
* @return\r
*/\r
public static boolean isPartOfGameExperiment(Variable variable) {\r
- Configuration conf = variable.getParentConfiguration();\r
- if(conf != null)\r
- return conf.isGameConfiguration();\r
- else\r
- return false;\r
+ Configuration conf = variable.getParentConfiguration();\r
+ if(conf != null)\r
+ return conf.isGameConfiguration();\r
+ else\r
+ return false;\r
}\r
- \r
+\r
/**\r
- * Find out if a module is part of a game configuration. (This means that the module is a \r
- * part of a game experiment)\r
- * @param variable\r
- * @return\r
- */\r
- public static boolean isPartOfGameExperiment(Module module) {\r
- Configuration conf = module.getParentConfiguration();\r
- if(conf != null)\r
- return conf.isGameConfiguration();\r
- else\r
- return false;\r
- }\r
+ * Find out if a module is part of a game configuration. (This means that the module is a \r
+ * part of a game experiment)\r
+ * @param variable\r
+ * @return\r
+ */\r
+ public static boolean isPartOfGameExperiment(Module module) {\r
+ Configuration conf = module.getParentConfiguration();\r
+ if(conf != null)\r
+ return conf.isGameConfiguration();\r
+ else\r
+ return false;\r
+ }\r
\r
\r
/**\r
if(v.getName().equals(variable.getName())) {\r
return null;// Reference to self.\r
} else {\r
- if(Variability.PARAMETER.equals(Variability.getVariability(v, false, null))) {\r
- return v;\r
- } else {\r
- return null;\r
- }\r
- \r
- /*\r
+ if(Variability.PARAMETER.equals(Variability.getVariability(v, false, null))) {\r
+ return v;\r
+ } else {\r
+ return null;\r
+ }\r
+\r
+ /*\r
if(v.getExpressions() == null || v.getExpressions().getExpressions().size() > 1)\r
return null;\r
- \r
+\r
IExpression e = v.getExpressions().getExpressions().get(0);\r
- \r
+\r
if(e instanceof ParameterExpression)\r
return v;\r
*/\r
\r
\r
public static Variable getVariable(Configuration configuration, String name) {\r
- Configuration conf = configuration;\r
- // This function seems to be used with both whitespaced and\r
- // underscored versions of the variable name.\r
- String whitespacedName = name.replace('_', ' ');\r
- String[] components = whitespacedName.split("\\.");\r
- \r
- for(String component : components) {\r
- \r
- Configuration newConf = null;\r
- \r
- for(IElement element : conf.getElements()) {\r
- if(element instanceof Variable) {\r
- Variable variable = (Variable) element;\r
- if(variable.getName().equals(component)) {\r
- return variable;\r
- }\r
- } else if(element instanceof Module) {\r
- Module m = (Module)element;\r
- if(m.getName().equals(component)) {\r
- newConf = m.getType().getConfiguration();\r
- }\r
- }\r
- }\r
- \r
- // If variable or configuration has not been found, return null\r
- if(newConf == null)\r
- return null;\r
- }\r
- \r
- return null;\r
+ Configuration conf = configuration;\r
+ // This function seems to be used with both whitespaced and\r
+ // underscored versions of the variable name.\r
+ String whitespacedName = name.replace('_', ' ');\r
+ String[] components = whitespacedName.split("\\.");\r
+\r
+ for(String component : components) {\r
+\r
+ Configuration newConf = null;\r
+\r
+ for(IElement element : conf.getElements()) {\r
+ if(element instanceof Variable) {\r
+ Variable variable = (Variable) element;\r
+ if(variable.getName().equals(component)) {\r
+ return variable;\r
+ }\r
+ } else if(element instanceof Module) {\r
+ Module m = (Module)element;\r
+ if(m.getName().equals(component)) {\r
+ newConf = m.getType().getConfiguration();\r
+ }\r
+ }\r
+ }\r
+\r
+ // If variable or configuration has not been found, return null\r
+ if(newConf == null)\r
+ return null;\r
+ }\r
+\r
+ return null;\r
}\r
\r
}\r
return model;\r
}\r
\r
- public static void createModel(WriteGraph graph) {\r
- createModelAt(graph, Simantics.getProject().get());\r
+ public static Resource createModel(WriteGraph graph) {\r
+ return createModelAt(graph, Simantics.getProject().get());\r
}\r
\r
+ // TODO: remove this\r
public static Resource createModelAt(WriteGraph g, Resource library) {\r
try {\r
Layer0 l0 = Layer0.getInstance(g);\r