]> gerrit.simantics Code Review - simantics/sysdyn.git/commitdiff
Modelica files are recompiled only if the structure of the model is changed. Paramete...
authorlempinen <lempinen@ac1ea38d-2e2b-0410-8846-a27921b304fc>
Mon, 9 Aug 2010 13:12:20 +0000 (13:12 +0000)
committerlempinen <lempinen@ac1ea38d-2e2b-0410-8846-a27921b304fc>
Mon, 9 Aug 2010 13:12:20 +0000 (13:12 +0000)
git-svn-id: https://www.simantics.org/svn/simantics/sysdyn/trunk@17037 ac1ea38d-2e2b-0410-8846-a27921b304fc

org.simantics.modelica/src/org/simantics/modelica/ModelicaManager.java
org.simantics.modelica/src/org/simantics/modelica/SimulationLocation.java [new file with mode: 0644]
org.simantics.modelica/src/org/simantics/modelica/data/SimulationResult.java
org.simantics.sysdyn/META-INF/MANIFEST.MF
org.simantics.sysdyn/src/org/simantics/sysdyn/Activator.java [new file with mode: 0644]
org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java
org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/ParameterExpression.java

index 198dde1ef5e009320863be1f867df90dd29ef866..15a8cc9a397a36011da29970bccc10439c2f6e66 100644 (file)
@@ -13,13 +13,18 @@ package org.simantics.modelica;
 \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
@@ -69,23 +74,7 @@ public class ModelicaManager {
         }\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
@@ -99,11 +88,11 @@ public class ModelicaManager {
         {\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
@@ -113,15 +102,12 @@ public class ModelicaManager {
                 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
@@ -135,6 +121,26 @@ public class ModelicaManager {
             .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
@@ -143,10 +149,80 @@ public class ModelicaManager {
             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
diff --git a/org.simantics.modelica/src/org/simantics/modelica/SimulationLocation.java b/org.simantics.modelica/src/org/simantics/modelica/SimulationLocation.java
new file mode 100644 (file)
index 0000000..6ed4ffb
--- /dev/null
@@ -0,0 +1,20 @@
+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
index 6b0b44755d842d41a911095df1689e3d83d21f7f..6fdd8217e0dd308eb57cd86a2f2f11bb51df6904 100644 (file)
@@ -58,8 +58,10 @@ public class SimulationResult {
     }\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
@@ -98,8 +100,10 @@ public class SimulationResult {
 \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
index 63ce97595084a600c136522d5ad9dfef10804fc5..1fe0f848e4835a4835808534dcd9f7e9e60cb5ef 100644 (file)
@@ -24,3 +24,5 @@ Export-Package: org.simantics.sysdyn,
  org.simantics.sysdyn.representation.visitors,
  org.simantics.sysdyn.simulation,
  org.simantics.sysdyn.tableParser
+Bundle-Activator: org.simantics.sysdyn.Activator
+Bundle-ActivationPolicy: lazy
diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/Activator.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/Activator.java
new file mode 100644 (file)
index 0000000..71b644e
--- /dev/null
@@ -0,0 +1,40 @@
+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
index c8accfab2411c610ea1dfa236ecc8f7bf0dd4245..ba42c8d8b9ef884589853bf8f135ccafea8be672 100644 (file)
  *******************************************************************************/\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
@@ -28,6 +31,7 @@ import org.simantics.db.common.request.ReadRequest;
 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
@@ -36,11 +40,15 @@ import org.simantics.simulation.experiment.IExperiment;
 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
@@ -49,11 +57,14 @@ import org.simantics.sysdyn.representation.SysdynSchema;
 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
@@ -64,39 +75,43 @@ public class SysdynModel implements IMappingListener, IModel {
 \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
@@ -110,6 +125,24 @@ public class SysdynModel implements IMappingListener, IModel {
         }\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
@@ -121,24 +154,48 @@ public class SysdynModel implements IMappingListener, IModel {
     }\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
@@ -167,7 +224,7 @@ public class SysdynModel implements IMappingListener, IModel {
     public SimulationResult getSimulationResult() {\r
         return result;\r
     }\r
-    \r
+\r
     public SysdynResult getSysdynResult() {\r
         return sysdynResult;\r
     }\r
@@ -276,4 +333,21 @@ public class SysdynModel implements IMappingListener, IModel {
         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
index 6a92d4c136ff9e0d11a334dc448ab6174ef83056..372dc54c18a7457be5f2d0b05bc1a9f31b3a561e 100644 (file)
@@ -25,7 +25,11 @@ public class ParameterExpression extends Expression {
     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