\r
import java.io.File;\r
import java.io.FileInputStream;\r
+import java.io.FileNotFoundException;\r
import java.io.IOException;\r
import java.io.InputStream;\r
import java.io.PrintStream;\r
+import java.util.HashMap;\r
+\r
import org.simantics.modelica.data.SimulationResult;\r
\r
public class ModelicaManager {\r
\r
+\r
+\r
protected static File getOpenModelicaHome() {\r
String dir = System.getenv("OPENMODELICAHOME");\r
if(dir == null)\r
}\r
}\r
\r
- static class SimulationLocation {\r
- File simulationDir;\r
- File inputFile;\r
- File outputFile;\r
- File initFile;\r
-\r
- public SimulationLocation(File simulationDir, File inputFile,\r
- File outputFile, File initFile) {\r
- this.simulationDir = simulationDir;\r
- this.inputFile = inputFile;\r
- this.outputFile = outputFile;\r
- this.initFile = initFile;\r
- }\r
- }\r
-\r
- protected static SimulationLocation createInputFiles(String modelName, String modelText, Double startTime, Double stopTime, Double tolerance) throws IOException {\r
- File simulationDir = createTempDirectory();\r
+ public static SimulationLocation createInputFiles(File simulationDir, String modelName, String modelText, HashMap<String, Double> inits) throws IOException {\r
modelName = modelName.replace(" ", "");\r
File modelFile = new File(simulationDir, modelName + ".mo");\r
File scriptFile = new File(simulationDir, modelName + ".mos");\r
{\r
PrintStream s = new PrintStream(scriptFile);\r
s.println("loadFile(\"" + modelName + ".mo\");");\r
- s.print("simulate("+modelName+\r
- ",startTime="+startTime+\r
- ",stopTime="+stopTime);\r
- if(tolerance != null) {\r
- s.print(",tolerance="+tolerance);\r
+ s.print("buildModel("+modelName+\r
+ ",startTime="+inits.get("startTime")+\r
+ ",stopTime="+inits.get("stopTime"));\r
+ if(inits.containsKey("tolerance")) {\r
+ s.print(",tolerance="+inits.get("tolerance"));\r
}\r
s.print(");\n");\r
s.close();\r
simulationDir,\r
new File(simulationDir, modelName + ".mos"),\r
new File(simulationDir, modelName + "_res.plt"),\r
- new File(simulationDir, modelName + "_init.txt")\r
+ new File(simulationDir, modelName + "_init.txt"),\r
+ new File(simulationDir, modelName + ".exe")\r
);\r
}\r
\r
- public static SimulationResult runModelica(String modelName, String modelText,\r
- IModelicaMonitor monitor, Double startTime, Double stopTime, Double tolerance) throws IOException {\r
- SimulationLocation simulationLocation = \r
- createInputFiles(modelName, modelText, startTime, stopTime, tolerance);\r
-\r
+ public static void buildModel(SimulationLocation simulationLocation, IModelicaMonitor monitor) {\r
try {\r
File modelicaHome = getOpenModelicaHome();\r
File omc = new File(modelicaHome, "bin/omc.exe");\r
.start();\r
printProcessOutput(process, monitor);\r
\r
+ } catch(IOException e) {\r
+ e.printStackTrace();\r
+ }\r
+\r
+ }\r
+\r
+ public static SimulationResult runModelica(SimulationLocation simulationLocation, IModelicaMonitor monitor, HashMap<String, Double> inits) throws IOException {\r
+\r
+ try {\r
+\r
+ writeInits(simulationLocation, inits);\r
+\r
+ Process process = new ProcessBuilder(\r
+ simulationLocation.exeFile.getAbsolutePath()\r
+ )\r
+ .directory(simulationLocation.simulationDir.getAbsoluteFile())\r
+ .redirectErrorStream(true)\r
+ .start();\r
+ printProcessOutput(process, monitor);\r
+\r
SimulationResult result = new SimulationResult();\r
result.read(simulationLocation.outputFile);\r
result.readInits(simulationLocation.initFile);\r
return result;\r
} catch(IOException e) {\r
e.printStackTrace();\r
- } finally {\r
- recursiveDelete(simulationLocation.simulationDir); \r
- } \r
+ } \r
return null;\r
}\r
\r
+ private static void writeInits(SimulationLocation simulationLocation, HashMap<String, Double> inits) {\r
+\r
+ HashMap<String, String> initials = new HashMap<String, String>();\r
+ HashMap<Integer, String> order = new HashMap<Integer, String>();\r
+\r
+ InputStream is;\r
+ try {\r
+ is = new FileInputStream(simulationLocation.initFile);\r
+ int orderNumber = 0;\r
+ while(true) {\r
+ String line = getLine(is);\r
+ if(line == null)\r
+ return;\r
+ if(line.isEmpty())\r
+ break;\r
+ if(line.contains("//")) {\r
+ String[] nn = line.split("//", 2);\r
+ String key = nn[1].trim();\r
+ String value = nn[0].trim();\r
+ if(inits.containsKey(key)) {\r
+ value = inits.get(key).toString();\r
+ }\r
+ initials.put(key, value);\r
+ order.put(orderNumber, key);\r
+ }\r
+ orderNumber++;\r
+ }\r
+ is.close();\r
+\r
+ PrintStream s = new PrintStream(simulationLocation.initFile);\r
+ for(int j = 0; j < orderNumber ; j++) {\r
+ String key = order.get(j);\r
+ if (key != null) {\r
+ s.println(initials.get(key) + " // " + key);\r
+ } else {\r
+ s.println("0.0");\r
+ }\r
+ }\r
+ s.close();\r
+\r
+ } catch (FileNotFoundException e) {\r
+ e.printStackTrace();\r
+ } catch (IOException e) {\r
+ e.printStackTrace();\r
+ }\r
+ }\r
+\r
+\r
+ private static String getLine(InputStream stream) {\r
+ if(stream == null)\r
+ return null;\r
+ StringBuilder b = new StringBuilder();\r
+ try {\r
+ while(true) {\r
+ int c = stream.read();\r
+ if(c == -1) {\r
+ stream = null;\r
+ return b.toString();\r
+ }\r
+ else if(c == '\n') \r
+ return b.toString();\r
+ else if(c == '\r')\r
+ ;\r
+ else\r
+ b.append((char)c);\r
+ }\r
+ } catch (IOException e) {\r
+ return null;\r
+ } \r
+\r
+ }\r
+\r
}\r
--- /dev/null
+package org.simantics.modelica;\r
+\r
+import java.io.File;\r
+\r
+public class SimulationLocation {\r
+ public File simulationDir;\r
+ public File inputFile;\r
+ public File outputFile;\r
+ public File initFile;\r
+ public File exeFile;\r
+ \r
+ public SimulationLocation(File simulationDir, File inputFile,\r
+ File outputFile, File initFile, File exeFile) {\r
+ this.simulationDir = simulationDir;\r
+ this.inputFile = inputFile;\r
+ this.outputFile = outputFile;\r
+ this.initFile = initFile;\r
+ this.exeFile = exeFile;\r
+ }\r
+}
\ No newline at end of file
}\r
\r
\r
- public void readInits(File file) throws FileNotFoundException {\r
- readInits(new FileInputStream(file));\r
+ public void readInits(File file) throws FileNotFoundException, IOException {\r
+ InputStream is = new FileInputStream(file);\r
+ readInits(is);\r
+ is.close();\r
}\r
\r
public void readInits(InputStream stream) {\r
\r
final static Pattern p1 = Pattern.compile("DataSet: ([^ ]*)");\r
\r
- public void read(File file) throws FileNotFoundException {\r
- read(new FileInputStream(file));\r
+ public void read(File file) throws FileNotFoundException, IOException {\r
+ InputStream is = new FileInputStream(file);\r
+ read(is);\r
+ is.close();\r
}\r
\r
public void read(InputStream stream) {\r
org.simantics.sysdyn.representation.visitors,
org.simantics.sysdyn.simulation,
org.simantics.sysdyn.tableParser
+Bundle-Activator: org.simantics.sysdyn.Activator
+Bundle-ActivationPolicy: lazy
--- /dev/null
+package org.simantics.sysdyn;\r
+\r
+import java.io.File;\r
+\r
+import org.osgi.framework.BundleActivator;\r
+import org.osgi.framework.BundleContext;\r
+\r
+public class Activator implements BundleActivator {\r
+\r
+ private static BundleContext bundleContext;\r
+ \r
+ @Override\r
+ public void start(BundleContext context) throws Exception {\r
+ bundleContext = context;\r
+ File modelsDir = Activator.getBundleContext().getDataFile("models");\r
+ if (!modelsDir.exists()) {\r
+ modelsDir.mkdir();\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public void stop(BundleContext context) throws Exception {\r
+ File modelsDir = Activator.getBundleContext().getDataFile("models");\r
+ if (modelsDir.exists()) {\r
+ recursiveDelete(modelsDir);\r
+ }\r
+ }\r
+\r
+ public static BundleContext getBundleContext() {\r
+ return bundleContext;\r
+ }\r
+ \r
+ private static boolean recursiveDelete(File fileOrDir) {\r
+ if(fileOrDir.isDirectory())\r
+ for(File innerFile: fileOrDir.listFiles())\r
+ if(!recursiveDelete(innerFile))\r
+ return false;\r
+ return fileOrDir.delete();\r
+ }\r
+}\r
*******************************************************************************/\r
package org.simantics.sysdyn.manager;\r
\r
+import java.io.File;\r
import java.io.IOException;\r
import java.util.ArrayList;\r
+import java.util.Arrays;\r
import java.util.Collection;\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
import java.util.concurrent.CopyOnWriteArrayList;\r
import org.simantics.db.exception.DatabaseException;\r
import org.simantics.modelica.IModelicaMonitor;\r
import org.simantics.modelica.ModelicaManager;\r
+import org.simantics.modelica.SimulationLocation;\r
import org.simantics.modelica.data.SimulationResult;\r
import org.simantics.objmap.IMapping;\r
import org.simantics.objmap.IMappingListener;\r
import org.simantics.simulation.model.IModel;\r
import org.simantics.simulation.project.IExperimentActivationListener;\r
import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.Activator;\r
import org.simantics.sysdyn.SysdynResource;\r
import org.simantics.sysdyn.modelica.ModelicaWriter;\r
import org.simantics.sysdyn.representation.Configuration;\r
import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+import org.simantics.sysdyn.representation.Module;\r
import org.simantics.sysdyn.representation.SysdynSchema;\r
+import org.simantics.sysdyn.representation.expressions.ParameterExpression;\r
\r
/**\r
* Maintains a Java representation of system dynamic model.\r
public class SysdynModel implements IMappingListener, IModel {\r
\r
Session session;\r
- Resource configurationResource; \r
\r
IMapping mapping;\r
+\r
+ Resource configurationResource; \r
Configuration configuration;\r
+\r
Set<Configuration> modules = new HashSet<Configuration>();\r
+\r
SimulationResult result;\r
SysdynResult sysdynResult;\r
\r
\r
Map<Class, Object> services = new HashMap<Class, Object>();\r
\r
+ String previousModelStructure;\r
+\r
+ File simulationDir;\r
+\r
void readModules(ReadGraph graph, Resource configResource, Set<Resource> result) throws DatabaseException {\r
- \r
- if(!result.add(configResource)) return;\r
- \r
- Builtins b = graph.getBuiltins();\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- StructuralResource2 str = StructuralResource2.getInstance(graph);\r
- \r
- for(Resource part : graph.getObjects(configResource, b.ConsistsOf)) {\r
- if(graph.isInstanceOf(part, sr.Module)) {\r
- Resource type = graph.getPossibleType(part, sr.Module);\r
- Resource config = graph.getPossibleObject(type, str.IsDefinedBy);\r
- readModules(graph, config, result);\r
- }\r
- }\r
- \r
+\r
+ if(!result.add(configResource)) return;\r
+\r
+ Builtins b = graph.getBuiltins();\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ StructuralResource2 str = StructuralResource2.getInstance(graph);\r
+\r
+ for(Resource part : graph.getObjects(configResource, b.ConsistsOf)) {\r
+ if(graph.isInstanceOf(part, sr.Module)) {\r
+ Resource type = graph.getPossibleType(part, sr.Module);\r
+ Resource config = graph.getPossibleObject(type, str.IsDefinedBy);\r
+ readModules(graph, config, result);\r
+ }\r
+ }\r
+\r
}\r
- \r
+\r
Set<Resource> readModules(ReadGraph graph, Resource configResource) throws DatabaseException {\r
- HashSet<Resource> result = new HashSet<Resource>();\r
- readModules(graph, configResource, result);\r
- return result;\r
+ HashSet<Resource> result = new HashSet<Resource>();\r
+ readModules(graph, configResource, result);\r
+ return result;\r
}\r
- \r
+\r
private void createMapping(ReadGraph g) throws DatabaseException {\r
SysdynSchema schema = new SysdynSchema(g);\r
mapping = Mappings.createWithListening(schema);\r
mapping.addMappingListener(SysdynModel.this);\r
configuration = (Configuration)mapping.map(g, configurationResource);\r
for(Resource config : readModules(g, configurationResource)) {\r
- modules.add((Configuration)mapping.map(g, config));\r
+ modules.add((Configuration)mapping.map(g, config));\r
}\r
- System.out.println("Loaded model with " + modules.size() + " modules.");\r
+ System.out.println("Loaded model with " + modules.size() + " modules.");\r
}\r
\r
public SysdynModel(ReadGraph g, Resource configurationResource) {\r
}\r
sysdynResult = new SysdynResult();\r
sysdynResult.setResult(new SimulationResult());\r
+\r
+ previousModelStructure = "";\r
+\r
+ File modelsDir = Activator.getBundleContext().getDataFile("models");\r
+ String configName = configuration.getName();\r
+ List<String> files = Arrays.asList(modelsDir.list());\r
+ if (files.contains(configName)) {\r
+ int i = 2;\r
+ while (files.contains(configName + "_" + i)){\r
+ i++;\r
+ }\r
+ configName += "_" + i;\r
+ }\r
+ \r
+ simulationDir = Activator.getBundleContext().getDataFile("models/" + configName);\r
+ if (!simulationDir.exists()) {\r
+ simulationDir.mkdir();\r
+ } \r
}\r
\r
\r
}\r
\r
public synchronized void simulate(IModelicaMonitor monitor) throws IOException {\r
+\r
try {\r
ModelicaWriter writer = new ModelicaWriter();\r
//writer.write(configuration);\r
for(Configuration c : modules) {\r
- writer.write(c);\r
+ writer.write(c);\r
}\r
\r
- System.out.println("== Modelica == ");\r
- System.out.println(writer.toString());\r
- System.out.println("== Modelica ends == ");\r
- \r
- result = ModelicaManager.runModelica(\r
+ String modelText = writer.toString();\r
+\r
+ HashMap<String, Double> inits = getInits(configuration, "");\r
+\r
+ inits.put("startTime", configuration.startTime);\r
+ inits.put("stopTime", configuration.stopTime);\r
+ if(configuration.tolerance != null) {\r
+ inits.put("tolerance", configuration.tolerance);\r
+ }\r
+\r
+\r
+ SimulationLocation simulationLocation = ModelicaManager.createInputFiles(\r
+ simulationDir,\r
configuration.getName(),\r
writer.toString(), \r
- monitor,\r
- configuration.startTime,\r
- configuration.stopTime,\r
- configuration.tolerance); \r
+ inits); \r
+\r
+ if (simulationLocation == null || !modelText.equals(previousModelStructure)) {\r
+ previousModelStructure = modelText;\r
+ System.out.println("== Modelica == ");\r
+ System.out.println(writer.toString());\r
+ System.out.println("== Modelica ends == ");\r
+\r
+ ModelicaManager.buildModel(simulationLocation, monitor);\r
+\r
+ } \r
+\r
+ if(simulationLocation != null)\r
+ result = ModelicaManager.runModelica(\r
+ simulationLocation,\r
+ monitor,\r
+ inits\r
+ );\r
+\r
sysdynResult.setResult(result);\r
} catch(Exception e) {\r
e.printStackTrace();\r
public SimulationResult getSimulationResult() {\r
return result;\r
}\r
- \r
+\r
public SysdynResult getSysdynResult() {\r
return sysdynResult;\r
}\r
return results;\r
}\r
\r
+ private HashMap<String, Double> getInits(Configuration configuration, String prefix) {\r
+ HashMap<String, Double> inits = new HashMap<String, Double>();\r
+ for (IElement element : configuration.getElements()) {\r
+ if (element instanceof Module) {\r
+ Module module = (Module) element;\r
+ Configuration conf = module.getType().getConfiguration();\r
+ inits.putAll(getInits(conf, prefix + module.getName() + "."));\r
+ } else if (element instanceof IndependentVariable) {\r
+ IndependentVariable variable = (IndependentVariable) element;\r
+ if (variable.getExpression() instanceof ParameterExpression) {\r
+ inits.put(prefix + variable.getName(), ((ParameterExpression)variable.getExpression()).getValue());\r
+ }\r
+ }\r
+ }\r
+ return inits;\r
+ }\r
+\r
}\r
public String getDeclaration(IndependentVariable variable) {\r
StringBuilder b = new StringBuilder();\r
b.append(" parameter " + variable.getType() + " " + variable.getName());\r
- b.append(" = " + equation + ";\n");\r
+ b.append(" = " + 0.0 + " /* Value read from init file */;\n");\r
return b.toString();\r
}\r
+ \r
+ public double getValue() {\r
+ return Double.parseDouble(equation);\r
+ }\r
}\r