From: lehtonen Date: Tue, 5 Jun 2012 10:02:46 +0000 (+0000) Subject: Merge until trunk@25101 to branches/stable on 2012-06-05. refs #3468 X-Git-Url: https://gerrit.simantics.org/r/gitweb?a=commitdiff_plain;h=0bb69a3d651cb92967259c962d21cfe860280314;p=simantics%2Fsysdyn.git Merge until trunk@25101 to branches/stable on 2012-06-05. refs #3468 git-svn-id: https://www.simantics.org/svn/simantics/sysdyn/branches@25105 ac1ea38d-2e2b-0410-8846-a27921b304fc --- diff --git a/stable/org.simantics.modelica/FMUSolution/FMUSolution.opensdf b/stable/org.simantics.modelica/FMUSolution/FMUSolution.opensdf deleted file mode 100644 index f8442e66..00000000 Binary files a/stable/org.simantics.modelica/FMUSolution/FMUSolution.opensdf and /dev/null differ diff --git a/stable/org.simantics.modelica/src/org/simantics/modelica/data/CSVSimulationResult.java b/stable/org.simantics.modelica/src/org/simantics/modelica/data/CSVSimulationResult.java index 1c3b1e2f..8787adf9 100644 --- a/stable/org.simantics.modelica/src/org/simantics/modelica/data/CSVSimulationResult.java +++ b/stable/org.simantics.modelica/src/org/simantics/modelica/data/CSVSimulationResult.java @@ -28,7 +28,7 @@ public class CSVSimulationResult extends SimulationResult { * Overridden method to support csv-formatted simulation results */ @Override - public void read(InputStream stream) { + public void read(InputStream stream, int outputInterval) { errors.clear(); // First line contains the variable names in format "name" (including quotes); @@ -42,7 +42,7 @@ public class CSVSimulationResult extends SimulationResult { // Create lists for receiving values for each variable. Names still with quotes. for(String name : names) { if(!name.isEmpty()) - valueMap.put(name, new DataSet(name, new double[numberOfTimeSteps], new double[numberOfTimeSteps])); + valueMap.put(name, new DataSet(name, new double[numberOfLines], new double[numberOfLines])); } int row = 0; diff --git a/stable/org.simantics.modelica/src/org/simantics/modelica/data/Mat4Reader.java b/stable/org.simantics.modelica/src/org/simantics/modelica/data/Mat4Reader.java index 0d896368..ceafe6b0 100644 --- a/stable/org.simantics.modelica/src/org/simantics/modelica/data/Mat4Reader.java +++ b/stable/org.simantics.modelica/src/org/simantics/modelica/data/Mat4Reader.java @@ -108,7 +108,14 @@ public class Mat4Reader { } } - public static Map read(InputStream in) throws IOException { + /** + * + * @param in InputStream of a mat file + * @param outputInterval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc... + * @return + * @throws IOException + */ + public static Map read(InputStream in, int outputInterval) throws IOException { Mat4Reader reader = new Mat4Reader(in); reader.readMatrix(); // Header StringMatrix names = (StringMatrix)reader.readMatrix(); // Variable names @@ -131,13 +138,17 @@ public class Mat4Reader { for(int i=0;i 0 ? sc-1 : 1-sc; //System.out.println("i=" + i + ", sc=" + sc + ", c=" + c); - for(int j=0;j= values.columns) adjusted = values.columns - 1; + v[j] = valueData[rows * adjusted + c]; + } if(sc < 0) for(int j=0;j valueMap = null; try { - valueMap = Mat4Reader.read(stream); + valueMap = Mat4Reader.read(stream, interval); } catch (IOException e) { e.printStackTrace(); return; diff --git a/stable/org.simantics.modelica/src/org/simantics/modelica/data/SimulationResult.java b/stable/org.simantics.modelica/src/org/simantics/modelica/data/SimulationResult.java index 725d7e71..a21a2155 100644 --- a/stable/org.simantics.modelica/src/org/simantics/modelica/data/SimulationResult.java +++ b/stable/org.simantics.modelica/src/org/simantics/modelica/data/SimulationResult.java @@ -50,7 +50,7 @@ public class SimulationResult { protected List variables = new ArrayList(); protected List initials = new ArrayList(); - protected int numberOfTimeSteps = 0; + protected int numberOfLines = 0; /** * Private class used in displaying errors @@ -262,36 +262,50 @@ public class SimulationResult { } - final static Pattern p1 = Pattern.compile("DataSet: ([^ ]*)"); + + /** + * Read result file. Read all values in the result file. + * + * @param file result file + * @throws FileNotFoundException + * @throws IOException + */ + public void read(File file) throws FileNotFoundException, IOException { + read(file, 1); + } + /** * Read result file * * @param file result file + * @param interval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc... * @throws FileNotFoundException * @throws IOException */ - public void read(File file) throws FileNotFoundException, IOException { + public void read(File file, int interval) throws FileNotFoundException, IOException { // First check the number of time steps FileReader fr = new FileReader(file); LineNumberReader lnr = new LineNumberReader(fr); lnr.skip(Long.MAX_VALUE); - numberOfTimeSteps = lnr.getLineNumber() - 1; // minus the first row, which is for names + numberOfLines = lnr.getLineNumber() - 1; // minus the first row, which is for names lnr.close(); fr.close(); InputStream is = new FileInputStream(file); - read(is); + read(is, interval); is.close(); } - + final static Pattern p1 = Pattern.compile("DataSet: ([^ ]*)"); + /** * Read result file. The basic implementation supports * plt-formatted results. Overridden to support other formats. * @param stream FileInputStream for the result file + * @param interval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc... */ - public void read(InputStream stream) { + public void read(InputStream stream, int outputInterval) { while(true) { String line = getLine(stream); if(line == null) @@ -307,8 +321,8 @@ public class SimulationResult { return; String name = matcher.group(1); - double[] dtimes = new double[numberOfTimeSteps]; - double[] dvalues = new double[numberOfTimeSteps]; + double[] dtimes = new double[numberOfLines]; + double[] dvalues = new double[numberOfLines]; int i = 0; while(true) { String line = getLine(stream); diff --git a/stable/org.simantics.sysdyn.ontology/graph.tg b/stable/org.simantics.sysdyn.ontology/graph.tg index efe3183f..8185e6cc 100644 Binary files a/stable/org.simantics.sysdyn.ontology/graph.tg and b/stable/org.simantics.sysdyn.ontology/graph.tg differ diff --git a/stable/org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph b/stable/org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph index 54086f8a..9584de37 100644 --- a/stable/org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph +++ b/stable/org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph @@ -33,6 +33,7 @@ SYSDYN.SharedModuleOntolofgy -- SYSDYN.SysdynModel.startTime --> L0.Double -- SYSDYN.SysdynModel.stopTime --> L0.Double -- SYSDYN.SysdynModel.simulationStepLength --> L0.Double -- SYSDYN.SysdynModel.outputInterval --> L0.Double -- SYSDYN.SysdynModel.tolerance --> L0.Double -- SYSDYN.SysdynModel.solver --> L0.String FL = : SYSDYN.SysdynModelicaFunctionLibrary +FL.minmax : SYSDYN.SysdynModelicaFunction + L0.HasDescription "Limits the result of an equation to between the given minimum and maximum values." + SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """ input Real expression; + input Real minimum; + input Real maximum; + output Real result; +algorithm + result := min(maximum, max(minimum, expression));""" + FL.xidz : SYSDYN.SysdynModelicaFunction L0.HasDescription "X if divided by zero" diff --git a/stable/org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java b/stable/org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java index d4ebd8ce..79f98c2a 100644 --- a/stable/org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java +++ b/stable/org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java @@ -51,6 +51,7 @@ public class SysdynResource { public final Resource Built$in_Functions_Vensim_Functions_ZIDZ; public final Resource Built$in_Functions_interpolate; public final Resource Built$in_Functions_interpolateFull; + public final Resource Built$in_Functions_minmax; public final Resource Built$in_Functions_xidz; public final Resource Built$in_Functions_zidz; public final Resource Center; @@ -284,6 +285,8 @@ public class SysdynResource { public final Resource SysdynModel; public final Resource SysdynModel_outputInterval; public final Resource SysdynModel_outputInterval_Inverse; + public final Resource SysdynModel_simulationStepLength; + public final Resource SysdynModel_simulationStepLength_Inverse; public final Resource SysdynModel_solver; public final Resource SysdynModel_solver_Inverse; public final Resource SysdynModel_startTime; @@ -401,6 +404,7 @@ public class SysdynResource { public static final String Built$in_Functions_Vensim_Functions_ZIDZ = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/ZIDZ"; public static final String Built$in_Functions_interpolate = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolate"; public static final String Built$in_Functions_interpolateFull = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolateFull"; + public static final String Built$in_Functions_minmax = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/minmax"; public static final String Built$in_Functions_xidz = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/xidz"; public static final String Built$in_Functions_zidz = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/zidz"; public static final String Center = "http://www.simantics.org/Sysdyn-1.1/Center"; @@ -634,6 +638,8 @@ public class SysdynResource { public static final String SysdynModel = "http://www.simantics.org/Sysdyn-1.1/SysdynModel"; public static final String SysdynModel_outputInterval = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/outputInterval"; public static final String SysdynModel_outputInterval_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/outputInterval/Inverse"; + public static final String SysdynModel_simulationStepLength = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/simulationStepLength"; + public static final String SysdynModel_simulationStepLength_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/simulationStepLength/Inverse"; public static final String SysdynModel_solver = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/solver"; public static final String SysdynModel_solver_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/solver/Inverse"; public static final String SysdynModel_startTime = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/startTime"; @@ -761,6 +767,7 @@ public class SysdynResource { Built$in_Functions_Vensim_Functions_ZIDZ = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_ZIDZ); Built$in_Functions_interpolate = getResourceOrNull(graph, URIs.Built$in_Functions_interpolate); Built$in_Functions_interpolateFull = getResourceOrNull(graph, URIs.Built$in_Functions_interpolateFull); + Built$in_Functions_minmax = getResourceOrNull(graph, URIs.Built$in_Functions_minmax); Built$in_Functions_xidz = getResourceOrNull(graph, URIs.Built$in_Functions_xidz); Built$in_Functions_zidz = getResourceOrNull(graph, URIs.Built$in_Functions_zidz); Center = getResourceOrNull(graph, URIs.Center); @@ -994,6 +1001,8 @@ public class SysdynResource { SysdynModel = getResourceOrNull(graph, URIs.SysdynModel); SysdynModel_outputInterval = getResourceOrNull(graph, URIs.SysdynModel_outputInterval); SysdynModel_outputInterval_Inverse = getResourceOrNull(graph, URIs.SysdynModel_outputInterval_Inverse); + SysdynModel_simulationStepLength = getResourceOrNull(graph, URIs.SysdynModel_simulationStepLength); + SysdynModel_simulationStepLength_Inverse = getResourceOrNull(graph, URIs.SysdynModel_simulationStepLength_Inverse); SysdynModel_solver = getResourceOrNull(graph, URIs.SysdynModel_solver); SysdynModel_solver_Inverse = getResourceOrNull(graph, URIs.SysdynModel_solver_Inverse); SysdynModel_startTime = getResourceOrNull(graph, URIs.SysdynModel_startTime); diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Configuration.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Configuration.java index c874e042..d50bfbc2 100644 --- a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Configuration.java +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Configuration.java @@ -13,6 +13,7 @@ package org.simantics.sysdyn.ui.browser.contributions; import java.util.ArrayList; import java.util.Collection; +import java.util.TreeMap; import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor; import org.simantics.db.ReadGraph; @@ -22,7 +23,6 @@ import org.simantics.db.exception.DatabaseException; import org.simantics.db.layer0.variable.Variable; import org.simantics.db.layer0.variable.Variables; import org.simantics.layer0.Layer0; -import org.simantics.modeling.ui.modelBrowser2.model.SheetsNode; import org.simantics.spreadsheet.resource.SpreadsheetResource; import org.simantics.sysdyn.SysdynResource; import org.simantics.sysdyn.ui.browser.nodes.BookNode; @@ -31,6 +31,7 @@ import org.simantics.sysdyn.ui.browser.nodes.EnumerationNode; import org.simantics.sysdyn.ui.browser.nodes.InputNode; import org.simantics.sysdyn.ui.browser.nodes.ModuleNode; import org.simantics.sysdyn.ui.browser.nodes.VariableNode; +import org.simantics.utils.strings.AlphanumComparator; public class Configuration extends ViewpointContributor> { @@ -44,37 +45,45 @@ public class Configuration extends ViewpointContributor variables = new ArrayList(); - ArrayList inputs = new ArrayList(); - ArrayList modules = new ArrayList(); - ArrayList enumerations = new ArrayList(); + TreeMap variables = new TreeMap(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR); + TreeMap inputs = new TreeMap(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR); + TreeMap modules = new TreeMap(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR); + TreeMap enumerations = new TreeMap(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR); + for(Variable child : variable.browseChildren(graph)) { Resource represents = (Resource)child.getPropertyValue(graph, Variables.REPRESENTS); if(graph.isInstanceOf(represents, sr.IndependentVariable)) { - variables.add(child); + variables.put(child.getName(graph), child); } else if (graph.isInstanceOf(represents, sr.Input)) { - inputs.add(child); + inputs.put(child.getName(graph), child); } else if (graph.isInstanceOf(represents, sr.Module)) { - modules.add(child); + modules.put(child.getName(graph), child); } else if (graph.isInstanceOf(represents, sr.Enumeration)) { - enumerations.add(child); + enumerations.put(child.getName(graph), child); } } - for (Variable v : variables) { + for (String s : variables.keySet()) { + Variable v = variables.get(s); Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS); result.add(new VariableNode(v, represents)); } - for (Variable v : inputs) { + + for (String s : inputs.keySet()) { + Variable v = inputs.get(s); Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS); result.add(new InputNode(v, represents)); } - for (Variable v : modules) { + + for (String s : modules.keySet()) { + Variable v = modules.get(s); Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS); result.add(new ModuleNode(v, represents)); } - for (Variable v : enumerations) { + + for (String s : enumerations.keySet()) { + Variable v = enumerations.get(s); Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS); result.add(new EnumerationNode(v, represents)); } diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionLibraries.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionLibraries.java index 87151394..5cd6bbee 100644 --- a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionLibraries.java +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionLibraries.java @@ -13,12 +13,14 @@ package org.simantics.sysdyn.ui.browser.contributions; import java.util.ArrayList; import java.util.Collection; +import java.util.TreeMap; import org.simantics.browsing.ui.common.node.AbstractNode; import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.common.request.ObjectsWithType; +import org.simantics.db.common.utils.NameUtils; import org.simantics.db.exception.DatabaseException; import org.simantics.layer0.Layer0; import org.simantics.sysdyn.SysdynResource; @@ -26,6 +28,7 @@ import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode; import org.simantics.sysdyn.ui.browser.nodes.FunctionNode; import org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder; import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionsFolder; +import org.simantics.utils.strings.AlphanumComparator; public class FunctionLibraries extends ViewpointContributor { @@ -38,16 +41,23 @@ public class FunctionLibraries extends ViewpointContributor { ArrayList> result = new ArrayList>(); - // Find model functions + TreeMap sortResult = new TreeMap(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR); + // Find and sort model functions for(Resource function : graph.syncRequest(new ObjectsWithType(functionsFolder.data, l0.ConsistsOf, sr.SysdynModelicaFunction))) { - result.add(new FunctionNode(function)); + sortResult.put(NameUtils.getSafeName(graph, function), function); } + for(Resource function : sortResult.values()) + result.add(new FunctionNode(function)); - // Find model function libraries + // Find and sort model function libraries + sortResult.clear(); for(Resource functionLibrary : graph.syncRequest(new ObjectsWithType(functionsFolder.data, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))) { - result.add(new FunctionLibraryNode(functionLibrary)); - } - + sortResult.put(NameUtils.getSafeName(graph, functionLibrary), functionLibrary); + } + for(Resource functionLibrary : sortResult.values()) + result.add(new FunctionLibraryNode(functionLibrary)); + + // Find built-in functions Resource sysdyn = graph.getPossibleResource("http://www.simantics.org/Sysdyn-1.1"); if(sysdyn != null) { for(Resource library : graph.syncRequest(new ObjectsWithType(sysdyn, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))) { diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryFunctions.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryFunctions.java index c37ea465..6e3a1a1f 100644 --- a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryFunctions.java +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryFunctions.java @@ -13,17 +13,20 @@ package org.simantics.sysdyn.ui.browser.contributions; import java.util.ArrayList; import java.util.Collection; +import java.util.TreeMap; import org.simantics.browsing.ui.common.node.AbstractNode; import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.common.request.ObjectsWithType; +import org.simantics.db.common.utils.NameUtils; import org.simantics.db.exception.DatabaseException; import org.simantics.layer0.Layer0; import org.simantics.sysdyn.SysdynResource; import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode; import org.simantics.sysdyn.ui.browser.nodes.FunctionNode; +import org.simantics.utils.strings.AlphanumComparator; public class LibraryFunctions extends ViewpointContributor> { @@ -32,16 +35,28 @@ public class LibraryFunctions extends ViewpointContributor library) throws DatabaseException { Layer0 l0 = Layer0.getInstance(graph); ArrayList> result = new ArrayList>(); + + TreeMap sortResult = new TreeMap(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR); + + // Find and sort functions in library for(Resource function : graph.syncRequest(new ObjectsWithType(library.data, l0.ConsistsOf, SysdynResource.getInstance(graph).SysdynModelicaFunction))) { - result.add(new FunctionNode(function)); + sortResult.put(NameUtils.getSafeName(graph, function), function); } + for(Resource function : sortResult.values()) + result.add(new FunctionNode(function)); + + // Find and sort libraries in library + sortResult.clear(); for(Resource functionLibrary : graph.syncRequest(new ObjectsWithType(library.data, l0.ConsistsOf, SysdynResource.getInstance(graph).SysdynModelicaFunctionLibrary))) { - result.add(new FunctionLibraryNode(functionLibrary)); + sortResult.put(NameUtils.getSafeName(graph, functionLibrary), functionLibrary); } + for(Resource functionLibrary : sortResult.values()) + result.add(new FunctionLibraryNode(functionLibrary)); + return result; } - + @Override public String getViewpointId() { return "Standard"; diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleType.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleType.java index ed5a9ead..4ebe335e 100644 --- a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleType.java +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleType.java @@ -13,9 +13,11 @@ package org.simantics.sysdyn.ui.browser.contributions; import java.util.ArrayList; import java.util.Collection; +import java.util.TreeMap; import org.simantics.browsing.ui.common.node.AbstractNode; import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor; +import org.simantics.databoard.Bindings; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.common.request.ObjectsWithType; @@ -29,6 +31,7 @@ import org.simantics.sysdyn.ui.browser.nodes.InputNode; import org.simantics.sysdyn.ui.browser.nodes.ModuleNode; import org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode; import org.simantics.sysdyn.ui.browser.nodes.VariableNode; +import org.simantics.utils.strings.AlphanumComparator; public class ModuleType extends ViewpointContributor { @@ -44,18 +47,39 @@ public class ModuleType extends ViewpointContributor { if(instance == null) return result; Resource conf = graph.getSingleObject(instance, str.IsDefinedBy); + + // Independent variables + TreeMap variables = new TreeMap(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR); for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.IndependentVariable))) { - result.add(new VariableNode(r)); + variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r); } + for(String key : variables.keySet()) + result.add(new VariableNode(variables.get(key))); + + // Inputs + variables.clear(); for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.Input))) { - result.add(new InputNode(r)); + variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r); } + for(String key : variables.keySet()) + result.add(new InputNode(variables.get(key))); + + // Modules + variables.clear(); for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.Module))) { - result.add(new ModuleNode(r)); + variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r); } + for(String key : variables.keySet()) + result.add(new ModuleNode(variables.get(key))); + + // Enumerations + variables.clear(); for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.Enumeration))) { - result.add(new EnumerationNode(r)); + variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r); } + for(String key : variables.keySet()) + result.add(new EnumerationNode(variables.get(key))); + return result; } diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynComponentCopyAdvisor.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynComponentCopyAdvisor.java index 62672a39..94e3a9f0 100644 --- a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynComponentCopyAdvisor.java +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynComponentCopyAdvisor.java @@ -11,6 +11,8 @@ *******************************************************************************/ package org.simantics.sysdyn.ui.editor.participant; +import java.util.Map; + import org.simantics.databoard.Bindings; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; @@ -26,10 +28,10 @@ import org.simantics.modeling.mapping.ComponentCopyAdvisor; import org.simantics.structural.stubs.StructuralResource2; import org.simantics.utils.datastructures.BinaryFunction; -public class SysdynComponentCopyAdvisor extends ComponentCopyAdvisor{ +public class SysdynComponentCopyAdvisor extends ComponentCopyAdvisor { @Override - public Object copy(ISynchronizationContext context, WriteGraph graph, Resource source, Resource sourceContainer, Resource targetContainer) throws DatabaseException { + public Object copy(ISynchronizationContext context, WriteGraph graph, Resource source, Resource sourceContainer, Resource targetContainer, Map map) throws DatabaseException { BinaryFunction tester = new BinaryFunction() { @@ -56,7 +58,7 @@ public class SysdynComponentCopyAdvisor extends ComponentCopyAdvisor{ StructuralResource2 sr2 = StructuralResource2.getInstance(graph); if(graph.isInstanceOf(source, sr2.Connection)) { - copy = CopyAdvisorUtil.copy(graph, source, tester); + copy = CopyAdvisorUtil.copy(graph, source, tester, map); } else { copy = CopyAdvisorUtil.copy4(graph, source); } diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java index aae0b0ef..27e3b551 100644 --- a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java @@ -61,17 +61,16 @@ public class PlaybackSliderContribution extends ToolBarContributionItem { return; spe = (SysdynPlaybackExperiment)experiment; - Double[] numbers = new Double[3]; + Double[] numbers = new Double[2]; try { numbers = SimanticsUI.getSession().syncRequest(new Read() { @Override public Double[] perform(ReadGraph graph) throws DatabaseException { - Double[] numbers = new Double[3]; + Double[] numbers = new Double[2]; Resource model = spe.getModel(); SysdynResource sr = SysdynResource.getInstance(graph); numbers[0] = graph.getRelatedValue(model, sr.SysdynModel_startTime); numbers[1] = graph.getRelatedValue(model, sr.SysdynModel_stopTime); - numbers[2] = graph.getPossibleRelatedValue(model, sr.SysdynModel_outputInterval); return numbers; } }); diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ConfigurationTab.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ConfigurationTab.java index f0d9b324..96dea950 100644 --- a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ConfigurationTab.java +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ConfigurationTab.java @@ -120,12 +120,22 @@ public class ConfigurationTab extends LabelPropertyTabContributor { label = new Label(composite, SWT.NONE); label.setText("Step length\n(empty = default)"); + TrackedText stepLength = new TrackedText(composite, support, SWT.BORDER | SWT.RIGHT); + stepLength.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.SysdynModel_simulationStepLength)); + stepLength.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.SysdynModel_simulationStepLength)); + stepLength.setInputValidator(new DoubleValidator()); + GridDataFactory.fillDefaults().hint(200, SWT.DEFAULT).applyTo(stepLength.getWidget()); + + label = new Label(composite, SWT.NONE); + label.setText("Output interval\n(empty = all steps)"); + TrackedText outputInterval = new TrackedText(composite, support, SWT.BORDER | SWT.RIGHT); outputInterval.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.SysdynModel_outputInterval)); outputInterval.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.SysdynModel_outputInterval)); outputInterval.setInputValidator(new DoubleValidator()); GridDataFactory.fillDefaults().hint(200, SWT.DEFAULT).applyTo(outputInterval.getWidget()); + label = new Label(composite, SWT.NONE); label.setText("Method"); diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EquationTab.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EquationTab.java index e27c80de..58fb0eb0 100644 --- a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EquationTab.java +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EquationTab.java @@ -72,6 +72,7 @@ import org.simantics.sysdyn.ui.properties.widgets.ExpressionTypes.ExpressionType import org.simantics.sysdyn.ui.properties.widgets.ExpressionWidget; import org.simantics.sysdyn.ui.properties.widgets.IsOutputWidget; import org.simantics.sysdyn.ui.properties.widgets.ShortcutTabWidget; +import org.simantics.sysdyn.ui.properties.widgets.arrays.NameAndArrayRangeModifyListener; import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionWidgetInput; import org.simantics.sysdyn.ui.properties.widgets.factories.VariableNameValidator; import org.simantics.ui.SimanticsUI; @@ -182,6 +183,8 @@ public class EquationTab extends LabelPropertyTabContributor implements Widget { expressionWidget = new ExpressionWidget(expressionComposite, expressionSupport, SWT.NONE); expressionWidget.setVariableTable(shortcutTabWidget.getVariableTable()); + arrayEquationCombo.addModifyListener(new NameAndArrayRangeModifyListener(support, expressionWidget, (ArrayExpressionCombo)arrayEquationCombo)); + addListeners(context); } diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ArrayExpressionCombo.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ArrayExpressionCombo.java index 5994a0c5..bab2c395 100644 --- a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ArrayExpressionCombo.java +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ArrayExpressionCombo.java @@ -2,33 +2,23 @@ package org.simantics.sysdyn.ui.properties.widgets; import java.util.ArrayList; import java.util.Iterator; -import java.util.Map; -import java.util.StringTokenizer; import java.util.LinkedHashMap; +import java.util.Map; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.simantics.browsing.ui.swt.widgets.TrackedCombo; -import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl; import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl; -import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent; -import org.simantics.browsing.ui.swt.widgets.impl.Widget; import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; -import org.simantics.db.Session; -import org.simantics.db.VirtualGraph; -import org.simantics.db.WriteGraph; -import org.simantics.db.common.request.WriteRequest; import org.simantics.db.common.utils.NameUtils; import org.simantics.db.common.utils.OrderedSetUtils; import org.simantics.db.exception.DatabaseException; import org.simantics.db.management.ISessionContext; import org.simantics.db.procedure.Listener; -import org.simantics.db.service.VirtualGraphSupport; import org.simantics.layer0.Layer0; import org.simantics.sysdyn.SysdynResource; -import org.simantics.sysdyn.ui.utils.VariableNameUtils; public class ArrayExpressionCombo extends TrackedCombo { @@ -110,7 +100,6 @@ public class ArrayExpressionCombo extends TrackedCombo { } }); - this.addModifyListener(new NameAndArrayRangeModifyListener(support)); } @@ -185,92 +174,18 @@ public class ArrayExpressionCombo extends TrackedCombo { sb.append("]"); return sb.toString(); } - - private class NameAndArrayRangeModifyListener extends ComboModifyListenerImpl implements Widget { - - Resource lastExpression; - - public NameAndArrayRangeModifyListener(WidgetSupport support) { - support.register(this); - } - - @Override - public void setInput(ISessionContext context, Object input) { - super.setInput(context, input); - } - - @Override - public void modifyText(TrackedModifyEvent e) { - - Combo combo = (Combo)e.getWidget(); - LinkedHashMap data = (LinkedHashMap) combo.getData(); - - Resource expression = (Resource) data.get(combo.getText()); - if(expression != null) { - lastExpression = expression; - lastSelectedIndex = combo.getSelectionIndex(); - } else { - for(Object key : data.keySet()) { - int index = lastSelectedIndex < 0 ? 0 : lastSelectedIndex; - if((Integer)combo.getData((String)key) == index) { - lastExpression = (Resource) data.get((String)key); - break; - } - } - } - - super.modifyText(e); - } - - @Override - public void applyText(WriteGraph graph, final Resource variable, String text) - throws DatabaseException { - StringTokenizer st = new StringTokenizer(text, "[]"); - final String newName = st.nextToken(); - String range = null; - if(st.hasMoreTokens()) { - range = st.nextToken(); - } - String originalName = graph.getRelatedValue(variable, Layer0.getInstance(graph).HasName); - if(!originalName.equals(newName)) { - VariableNameUtils.renameInEquations(graph, variable, originalName, newName); - graph.claimLiteral(variable, Layer0.getInstance(graph).HasName, newName); - } - - SysdynResource sr = SysdynResource.getInstance(graph); - - if(range != null && lastExpression != null) { - String oldRange = graph.getPossibleRelatedValue(lastExpression, sr.Expression_arrayRange); - if(oldRange == null || !range.equals(oldRange)) { - graph.claimLiteral(lastExpression, sr.Expression_arrayRange, "[" + range + "]"); - } - } else if (range == null && lastExpression != null && graph.hasStatement(lastExpression, sr.Expression_arrayRange)) { - graph.deny(lastExpression, sr.Expression_arrayRange); - } - - Resource activeExpression = graph.getPossibleObject(variable, sr.IndependentVariable_activeExpression); - - if(lastExpression != null && !lastExpression.equals(activeExpression)) { - VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class); - final Session session = graph.getSession(); - session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) { - @Override - public void perform(WriteGraph graph) throws DatabaseException { - VirtualGraph runtime = graph.getService(VirtualGraph.class); - session.asyncRequest(new WriteRequest(runtime) { - @Override - public void perform(WriteGraph graph) throws DatabaseException { - SysdynResource sr = SysdynResource.getInstance(graph); - if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression)) - graph.deny(variable, sr.IndependentVariable_activeExpression); - graph.claim(variable, sr.IndependentVariable_activeExpression, lastExpression); - } - } - ); - } - }); - } - } + + /** + * Get the index that has previously been selected + * @return + */ + public int getLastSelectedIndex() { + return lastSelectedIndex; + } + + public void setLastSelectedIndex(int lastSelectedIndex) { + this.lastSelectedIndex = lastSelectedIndex; } + } diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/NameAndArrayRangeModifyListener.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/NameAndArrayRangeModifyListener.java new file mode 100644 index 00000000..2d814007 --- /dev/null +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/NameAndArrayRangeModifyListener.java @@ -0,0 +1,146 @@ +package org.simantics.sysdyn.ui.properties.widgets.arrays; + +import java.util.LinkedHashMap; +import java.util.StringTokenizer; + +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.swt.widgets.Combo; +import org.simantics.Simantics; +import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl; +import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent; +import org.simantics.browsing.ui.swt.widgets.impl.Widget; +import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.VirtualGraph; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.management.ISessionContext; +import org.simantics.db.request.Read; +import org.simantics.db.service.VirtualGraphSupport; +import org.simantics.layer0.Layer0; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.ui.properties.widgets.ArrayExpressionCombo; +import org.simantics.sysdyn.ui.properties.widgets.ExpressionWidget; +import org.simantics.sysdyn.ui.utils.VariableNameUtils; +import org.simantics.utils.ui.ISelectionUtils; + +/** + * Modification listener ONLY for ArrayExpressionCombos in EquationTabs. + * @author Teemu Lempinen + * + */ +public class NameAndArrayRangeModifyListener extends ComboModifyListenerImpl implements Widget { + + Resource lastExpression; + ExpressionWidget expressionWidget; + ArrayExpressionCombo arrayExpressionCombo; + Object lastInput; + + public NameAndArrayRangeModifyListener(WidgetSupport support, ExpressionWidget expressionWidget, ArrayExpressionCombo arrayExpressionCombo) { + support.register(this); + this.expressionWidget = expressionWidget; + this.arrayExpressionCombo = arrayExpressionCombo; + } + + @Override + public void setInput(ISessionContext context, Object input) { + super.setInput(context, input); + this.lastInput = input; + } + + public void modifyText(TrackedModifyEvent e) { + Combo combo = (Combo)e.getWidget(); + LinkedHashMap data = (LinkedHashMap) combo.getData(); + + Resource activeExpression = null; + try { + final Object input = lastInput; + activeExpression = Simantics.getSession().syncRequest(new Read() { + @Override + public Resource perform(ReadGraph graph) + throws DatabaseException { + Resource variable = ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class); + return graph.getPossibleObject(variable, SysdynResource.getInstance(graph).IndependentVariable_activeExpression); + } + + }); + } catch (DatabaseException e1) { + e1.printStackTrace(); + } + + + Resource expression = (Resource) data.get(combo.getText()); + if(expression != null) { + lastExpression = expression; + arrayExpressionCombo.setLastSelectedIndex(combo.getSelectionIndex()); + } else { + for(Object key : data.keySet()) { + int index = arrayExpressionCombo.getLastSelectedIndex() < 0 ? 0 : arrayExpressionCombo.getLastSelectedIndex(); + if((Integer)combo.getData((String)key) == index) { + lastExpression = (Resource) data.get((String)key); + break; + } + } + } + + // If expression has changed (i.e. user actually selects a different item in the combo), save the previous + if(lastExpression != null && !lastExpression.equals(activeExpression)) { + expressionWidget.save(); + } + + super.modifyText(e); + } + + @Override + public void applyText(WriteGraph graph, final Resource variable, String text) + throws DatabaseException { + StringTokenizer st = new StringTokenizer(text, "[]"); + final String newName = st.nextToken(); + String range = null; + if(st.hasMoreTokens()) { + range = st.nextToken(); + } + String originalName = graph.getRelatedValue(variable, Layer0.getInstance(graph).HasName); + if(!originalName.equals(newName)) { + VariableNameUtils.renameInEquations(graph, variable, originalName, newName); + graph.claimLiteral(variable, Layer0.getInstance(graph).HasName, newName); + } + + SysdynResource sr = SysdynResource.getInstance(graph); + + if(range != null && lastExpression != null) { + String oldRange = graph.getPossibleRelatedValue(lastExpression, sr.Expression_arrayRange); + if(oldRange == null || !range.equals(oldRange)) { + graph.claimLiteral(lastExpression, sr.Expression_arrayRange, "[" + range + "]"); + } + } else if (range == null && lastExpression != null && graph.hasStatement(lastExpression, sr.Expression_arrayRange)) { + graph.deny(lastExpression, sr.Expression_arrayRange); + } + + Resource activeExpression = graph.getPossibleObject(variable, sr.IndependentVariable_activeExpression); + + if(lastExpression != null && !lastExpression.equals(activeExpression)) { + VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class); + final Session session = graph.getSession(); + session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) { + @Override + public void perform(WriteGraph graph) throws DatabaseException { + VirtualGraph runtime = graph.getService(VirtualGraph.class); + session.asyncRequest(new WriteRequest(runtime) { + @Override + public void perform(WriteGraph graph) throws DatabaseException { + SysdynResource sr = SysdynResource.getInstance(graph); + if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression)) + graph.deny(variable, sr.IndependentVariable_activeExpression); + graph.claim(variable, sr.IndependentVariable_activeExpression, lastExpression); + } + }); + } + }); + } + } + +} diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructureGraphRequest.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructureGraphRequest.java index 4724a0d5..c32a3004 100644 --- a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructureGraphRequest.java +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructureGraphRequest.java @@ -24,6 +24,8 @@ import org.simantics.graphviz.Edge; import org.simantics.graphviz.Graph; import org.simantics.graphviz.Node; import org.simantics.layer0.Layer0; +import org.simantics.modeling.ModelingResources; +import org.simantics.simulation.ontology.SimulationResource; import org.simantics.sysdyn.SysdynResource; /** @@ -61,13 +63,21 @@ public class ModuleStructureGraphRequest implements Read { // Model root was not found, return empty graph if(model == null) return g; + + // Find the parent module/model of the selected resource + Resource parentResource = graph.getPossibleObject(resource, l0.PartOf); + if(graph.isInstanceOf(parentResource, sr.ConfigurationDiagram)) { + parentResource = graph.getPossibleObject(parentResource, ModelingResources.getInstance(graph).DiagramToComposite); + } else if(graph.isInstanceOf(parentResource, sr.SysdynModel)) { + parentResource = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration); + } // Set root node Node rootNode = new Node(g, NameUtils.getSafeLabel(graph, model)); rootNode.setShape("rectangle"); HashSet visited = new HashSet(); visited.add(model); - findChildModules(g, rootNode, graph, model, visited); + findChildModules(g, rootNode, graph, model, parentResource, visited); return g; @@ -79,17 +89,23 @@ public class ModuleStructureGraphRequest implements Read { * @param parent Parent module or model * @param graph ReadGraph * @param resource Module type or model + * @param parent2 * @param visited All visited modules. Needed to check for loops in the structure. Loops are not allowed. * @throws DatabaseException */ - private void findChildModules(Graph g, Node parent, ReadGraph graph, Resource resource, HashSet visited) throws DatabaseException { + private void findChildModules(Graph g, Node parent, ReadGraph graph, Resource resource, Resource parentResource, HashSet visited) throws DatabaseException { SysdynResource sr = SysdynResource.getInstance(graph); Layer0 l0 = Layer0.getInstance(graph); + Resource configuration = graph.syncRequest(new PossibleObjectWithType(resource, l0.ConsistsOf, sr.Configuration)); + + // Set the parent color different, if it is the parent of the selected resource + if(configuration.equals(parentResource)) + parent.setColor("#ff8c00"); + HashMap modules = new HashMap(); // Find all module children - Resource configuration = graph.syncRequest(new PossibleObjectWithType(resource, l0.ConsistsOf, sr.Configuration)); for(Resource m : graph.getObjects(configuration, l0.ConsistsOf)) { Resource type = graph.getPossibleObject(m, l0.InstanceOf); if(graph.isInheritedFrom(type, sr.Module)) { @@ -120,8 +136,9 @@ public class ModuleStructureGraphRequest implements Read { node.setFontColor("#FF0000"); continue; } else { - visited.add(type); - findChildModules(g, node, graph, type, visited); + HashSet copy = new HashSet(visited); + copy.add(type); + findChildModules(g, node, graph, type, parentResource, copy); } } diff --git a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ExpressionUtils.java b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ExpressionUtils.java index 6773376d..fa3d62ab 100644 --- a/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ExpressionUtils.java +++ b/stable/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ExpressionUtils.java @@ -43,6 +43,7 @@ import org.simantics.sysdyn.representation.Configuration; import org.simantics.sysdyn.representation.Enumeration; import org.simantics.sysdyn.representation.EnumerationIndex; import org.simantics.sysdyn.representation.IElement; +import org.simantics.sysdyn.representation.Model; import org.simantics.sysdyn.representation.Module; import org.simantics.sysdyn.representation.Sheet; import org.simantics.sysdyn.representation.Variable; @@ -184,6 +185,14 @@ public class ExpressionUtils { for(int i = 0; i < parts.length && current != null; i++) { current = getElement(current, parts[i]); } + + if(current == null) { + // Sheets are currently located in the model root. Try to find the sheet. + current = conf.getModuleType().getParent(); // Get module type parent (should be a model) + if(current instanceof Model) + current = getElement(((Model)current).getModelConfiguration(), parts[0]); // Try to get the sheet + } + if(current != null && current instanceof Sheet) { Sheet sheet = (Sheet) current; String e = ef.getExpression(); diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableRVIUtils.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableRVIUtils.java index 62118077..63143b0e 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableRVIUtils.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableRVIUtils.java @@ -59,7 +59,7 @@ public class VariableRVIUtils { * @throws DatabaseException */ private static void traverseIndexes(ReadGraph g, String rvi, HashMap rvis, List arrayIndexes) throws DatabaseException { - traverseIndexes(g, rvi, rvis, arrayIndexes, arrayIndexes.get(0), "", ""); + traverseIndexes(g, rvi, rvis, arrayIndexes, 0, "", ""); } /** @@ -76,10 +76,10 @@ public class VariableRVIUtils { * @param indexNamesSoFar String representation of the indexes so far in name format * @throws DatabaseException */ - private static void traverseIndexes(ReadGraph g, String rvi, HashMap rvis, List arrayIndexes, Resource currentEnumeration, String indexesSoFar, String indexNamesSoFar) throws DatabaseException { + private static void traverseIndexes(ReadGraph g, String rvi, HashMap rvis, List arrayIndexes, int currentIndex, String indexesSoFar, String indexNamesSoFar) throws DatabaseException { SysdynResource sr = SysdynResource.getInstance(g); // Enumeration indexes of the current enumeration (e.g. the first EnumIndexes in Var[EnumIndexes, EnumIndexes, EnumIndexes]) - Resource enumerationIndexes = g.getPossibleObject(currentEnumeration, sr.Enumeration_enumerationIndexes); + Resource enumerationIndexes = g.getPossibleObject(arrayIndexes.get(currentIndex), sr.Enumeration_enumerationIndexes); if(enumerationIndexes == null) return; List indexes = OrderedSetUtils.toList(g, enumerationIndexes); @@ -87,12 +87,11 @@ public class VariableRVIUtils { Boolean b = g.getPossibleRelatedValue(indexes.get(i), sr.EnumerationIndex_showEnumerationIndexInCharts, Bindings.BOOLEAN); // If this index is not wanted to be shown in charts, the recursion does not go any further and rvis.put() is not called for this enumeration if(Boolean.TRUE.equals(b)) { - int arrayIndex = arrayIndexes.indexOf(currentEnumeration); // Get the name of the index String name = g.getRelatedValue(indexes.get(i), Layer0.getInstance(g).HasName); - if(arrayIndex < arrayIndexes.size() - 1) + if(currentIndex < arrayIndexes.size() - 1) // If there are still more EnumIndexes, recursively call the function and add current index to indexesSoFar and indexNamesSoFar - traverseIndexes(g, rvi, rvis, arrayIndexes, arrayIndexes.get(arrayIndex + 1), + traverseIndexes(g, rvi, rvis, arrayIndexes, currentIndex + 1, indexesSoFar + (i + 1) +",", indexNamesSoFar + (name) +","); else { // The last enumeration. Add [rvi[1, 1, 1] = rvi[index1, index1, index1]}and so on to the rvis map @@ -129,7 +128,7 @@ public class VariableRVIUtils { // Find all redeclarations for(Resource redeclaration : graph.syncRequest(new ObjectsWithType(module, sr.Module_redeclaration, sr.Redeclaration))) { Resource replaced = graph.getSingleObject(redeclaration, sr.Redeclaration_replacedEnumeration); - if(enumerations.contains(replaced)) { + while(enumerations.contains(replaced)) { // Replace the redelcared enumeration in enumerations -list with the replacing enumeration enumerations.add(enumerations.indexOf(replaced), graph.getSingleObject(redeclaration, sr.Redeclaration_replacingEnumeration)); enumerations.remove(replaced); diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetResult.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetResult.java index 9b0d515c..17d8bac1 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetResult.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetResult.java @@ -49,9 +49,9 @@ import org.simantics.utils.datastructures.Pair; */ public class HistoryDatasetResult extends SimulationResult { @Override - public void read(File file) {} // Do nothing + public void read(File file, int interval) {} // Do nothing @Override - public void read(InputStream stream) {} // Do nothing + public void read(InputStream stream, int interval) {} // Do nothing private boolean disposed; diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java index c82649c3..1c1852b1 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java @@ -196,17 +196,22 @@ public class SysdynExperiment extends Experiment implements IDynamicExperiment { Model model = configuration.getModel(); Double startTime = model.getStartTime(); Double stopTime = model.getStopTime(); - Double numberOfIntervals = model.getOutputInterval(); inits.put(SysdynInitKeys.START_VALUE, startTime.toString()); inits.put(SysdynInitKeys.STOP_VALUE, stopTime.toString()); String outputFormat = "\"mat\""; inits.put(SysdynInitKeys.OUTPUT_FORMAT, outputFormat); - if(numberOfIntervals != null) { - inits.put(SysdynInitKeys.STEP_VALUE, numberOfIntervals.toString()); - inits.put(SysdynInitKeys.NUMBER_OF_INTERVALS, "" + ((int)((stopTime - startTime) / numberOfIntervals))); + + Double simulationStepLength = model.getSimulationStepLength(); + if(simulationStepLength != null) { + inits.put(SysdynInitKeys.STEP_VALUE, simulationStepLength.toString()); + inits.put(SysdynInitKeys.NUMBER_OF_INTERVALS, "" + ((int)((stopTime - startTime) / simulationStepLength))); } else { inits.put(SysdynInitKeys.STEP_VALUE, "" + (stopTime - startTime) / 500); } + + Double outputInterval = model.getOutputInterval(); + inits.put(SysdynInitKeys.OUTPUT_INTERVAL, outputInterval != null ? outputInterval.toString() : inits.get(SysdynInitKeys.STEP_VALUE)); + String method = "\"" + model.getSolver() + "\""; inits.put(SysdynInitKeys.METHOD, method); if(model.getTolerance() != null) @@ -251,7 +256,7 @@ public class SysdynExperiment extends Experiment implements IDynamicExperiment { ); ModelicaManager.printProcessOutput(process, monitor); - Thread resultThread = getResultThread(simulationLocation, monitor, progressMonitor); + Thread resultThread = getResultThread(simulationLocation, inits, monitor, progressMonitor); resultThread.run(); process = null; @@ -260,11 +265,12 @@ public class SysdynExperiment extends Experiment implements IDynamicExperiment { /** * Get a thread for reading and saving reuslts from a normal simulation * @param simulationLocation + * @param inits * @param monitor * @param progressMonitor * @return */ - protected Thread getResultThread(final SimulationLocation simulationLocation, final IModelicaMonitor monitor, final IProgressMonitor progressMonitor) { + protected Thread getResultThread(final SimulationLocation simulationLocation, final HashMap inits, final IModelicaMonitor monitor, final IProgressMonitor progressMonitor) { return new Thread() { @Override public void run() { @@ -282,7 +288,23 @@ public class SysdynExperiment extends Experiment implements IDynamicExperiment { result = new SimulationResult(); else result = new MatSimulationResult(); // The latest format - result.read(simulationLocation.outputFile); + + + // The interval of results saved. Every result? Every other result? etc... + int outIntervalInt = 1; + String outputInterval = inits.get(SysdynInitKeys.OUTPUT_INTERVAL); + if(outputInterval != null) { + String stepTime = inits.get(SysdynInitKeys.STEP_VALUE); + + Double step = Double.parseDouble(stepTime); + Double outInterval = Double.parseDouble(outputInterval); + + double nearest = roundUp(outInterval, step); + outIntervalInt = (int)(nearest / step); + if(outIntervalInt <= 0) outIntervalInt = 1; + } + + result.read(simulationLocation.outputFile, outIntervalInt); result.readInits(simulationLocation.initFile); result.filter(); sysdynModel.getSysdynResult().setResult(result); @@ -305,6 +327,17 @@ public class SysdynExperiment extends Experiment implements IDynamicExperiment { } }; } + + protected static double roundUp(double numToRound, double multiple) { + if(multiple == 0) { + return numToRound; + } + double remainder = numToRound % multiple; + if (remainder == 0) { + return numToRound; + } + return numToRound + multiple - remainder; + } /** @@ -319,7 +352,7 @@ public class SysdynExperiment extends Experiment implements IDynamicExperiment { protected static SimulationLocation createSimulationFiles(SysdynModel sysdynModel, String modelText, HashMap inits, String additionalScript, boolean fmu) throws IOException { return ModelicaManager.createSimulationFiles( sysdynModel.getSimulationDir(), - sysdynModel.getConfiguration().getName(), + sysdynModel.getConfiguration().getLabel(), modelText, inits, additionalScript, @@ -340,11 +373,11 @@ public class SysdynExperiment extends Experiment implements IDynamicExperiment { protected void storeImportantInits(HashMap inits) { previousImportantInits.clear(); - previousImportantInits.put("start value", inits.get(SysdynInitKeys.START_VALUE)); - previousImportantInits.put("stop value", inits.get(SysdynInitKeys.STOP_VALUE)); - previousImportantInits.put("method", inits.get(SysdynInitKeys.METHOD)); - previousImportantInits.put("outputFormat", inits.get(SysdynInitKeys.OUTPUT_FORMAT)); - previousImportantInits.put("variableFilter", inits.get(SysdynInitKeys.VARIABLE_FILTER)); + previousImportantInits.put(SysdynInitKeys.START_VALUE, inits.get(SysdynInitKeys.START_VALUE)); + previousImportantInits.put(SysdynInitKeys.STOP_VALUE, inits.get(SysdynInitKeys.STOP_VALUE)); + previousImportantInits.put(SysdynInitKeys.METHOD, inits.get(SysdynInitKeys.METHOD)); + previousImportantInits.put(SysdynInitKeys.OUTPUT_FORMAT, inits.get(SysdynInitKeys.OUTPUT_FORMAT)); + previousImportantInits.put(SysdynInitKeys.VARIABLE_FILTER, inits.get(SysdynInitKeys.VARIABLE_FILTER)); } /** diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java index 8d82b12f..f5918430 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java @@ -33,7 +33,7 @@ import org.simantics.modelica.fmi.FMUControlJNI; import org.simantics.modelica.fmi.FMUJNIException; import org.simantics.simulation.experiment.ExperimentState; import org.simantics.sysdyn.SysdynResource; -import org.simantics.utils.datastructures.Pair; +import org.simantics.utils.datastructures.Triple; /** * Game experiment @@ -47,9 +47,11 @@ public class SysdynGameExperiment extends SysdynExperiment { private HashMap> results; private double stepLength = DEFAULT_STEP_LENGTH; private double stepDuration = DEFAULT_STEP_DURATION; + private int savePer = 1; public static double DEFAULT_STEP_DURATION = 1.0; public static double DEFAULT_STEP_LENGTH = 0.1; + public static int DEFAULT_OUTPUT_INTERVAL = 1; public SysdynGameExperiment(Resource experiment, Resource model) { super(experiment, model); @@ -71,6 +73,11 @@ public class SysdynGameExperiment extends SysdynExperiment { this.stepLength = stepLength; } + public void setOutputInterval(int interval) { + this.savePer = interval; + } + + public FMUControlJNI getFMUControl() { return control; } @@ -84,23 +91,33 @@ public class SysdynGameExperiment extends SysdynExperiment { results = new HashMap>(); - g.asyncRequest(new Read>() { + g.asyncRequest(new Read>() { @Override - public Pair perform(ReadGraph graph) + public Triple perform(ReadGraph graph) throws DatabaseException { SysdynResource sr = SysdynResource.getInstance(graph); Double stepDuration = graph.getPossibleRelatedValue(experiment, sr.GameExperiment_stepDuration); - Double stepLength =graph.getPossibleRelatedValue(experiment, sr.GameExperiment_stepLength); - return new Pair(stepDuration, stepLength); + Double stepLength = graph.getPossibleRelatedValue(experiment, sr.GameExperiment_stepLength); + Double outputInterval = graph.getPossibleRelatedValue(model, sr.SysdynModel_outputInterval); + return new Triple(stepDuration, stepLength, outputInterval); } - }, new AsyncListener>() { + }, new AsyncListener>() { @Override public void execute(AsyncReadGraph graph, - Pair result) { + Triple result) { setStepDuration(result.first != null ? result.first : DEFAULT_STEP_DURATION); setStepLength(result.second != null ? result.second : DEFAULT_STEP_LENGTH); + + if(result.third == null) { + setOutputInterval(DEFAULT_OUTPUT_INTERVAL); + } else { + double nearest = roundUp(result.third, getStepLength()); + int interval = (int)(nearest / getStepLength()); + if(interval <= 0) interval = 1; + setOutputInterval(interval); + } } @Override @@ -108,6 +125,7 @@ public class SysdynGameExperiment extends SysdynExperiment { throwable.printStackTrace(); setStepDuration(DEFAULT_STEP_DURATION); setStepLength(DEFAULT_STEP_LENGTH); + setOutputInterval(DEFAULT_OUTPUT_INTERVAL); } @Override @@ -219,7 +237,6 @@ public class SysdynGameExperiment extends SysdynExperiment { @Override protected IStatus run(IProgressMonitor monitor) { - int nSteps = (int)(duration / stepLength); int work = 1 + nSteps * 3 + 2; // initialization + number of steps * number of phases per step + set result + call result listeners @@ -241,20 +258,26 @@ public class SysdynGameExperiment extends SysdynExperiment { double[] results = new double[subscription.length]; monitor.worked(1); - + + int stepNumber = 1; while(control.getTime() < (eTime - 1e-9)) { // Substract a very small number, because OpenModelica is not very precise with its Real numbers monitor.subTask("Simulate step (time = " + control.getTime() + ")"); control.simulateStep(); monitor.worked(1); - monitor.subTask("Get results (time = " + control.getTime() + ")"); - results = control.getSubscribedResults(results); - monitor.worked(1); - - monitor.subTask("Save results (time = " + control.getTime() + ")"); - for(int k = 0; k < subscription.length; k++) { - SysdynGameExperiment.this.results.get(subscription[k]).add(results[k]); + if(stepNumber % savePer == 0) { + monitor.subTask("Get results (time = " + control.getTime() + ")"); + results = control.getSubscribedResults(results); + monitor.worked(1); + + monitor.subTask("Save results (time = " + control.getTime() + ")"); + for(int k = 0; k < subscription.length; k++) { + SysdynGameExperiment.this.results.get(subscription[k]).add(results[k]); + } + } else { + monitor.worked(1); } + stepNumber++; monitor.worked(1); } @@ -268,7 +291,6 @@ public class SysdynGameExperiment extends SysdynExperiment { } catch (FMUJNIException e) { System.err.println("SysdynGameExperiment simulateDuration failed: \n\t" + e.getMessage()); } - return Status.OK_STATUS; } } diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynInitKeys.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynInitKeys.java index 3d405ebd..65168bcb 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynInitKeys.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynInitKeys.java @@ -26,5 +26,6 @@ public class SysdynInitKeys { public static String METHOD = "method"; public static String TOLERANCE = "tolerance"; public static String VARIABLE_FILTER = "variableFilter"; + public static String OUTPUT_INTERVAL = "outputInterval"; } diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java index 740ae5a2..3912a70e 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java @@ -213,10 +213,6 @@ public class SysdynModel implements IMappingListener, IModel { e.printStackTrace(); } - // Add the current result if there is one - if(getSysdynResult() != null) - activeResults.add(0, getSysdynResult() ); - return activeResults; } @@ -224,6 +220,10 @@ public class SysdynModel implements IMappingListener, IModel { @Override public void execute(ArrayList result) { + // Add the current result if there is one + if(result != null && getSysdynResult() != null) + result.add(0, getSysdynResult() ); + activeResults = result; resultChanged(); } @@ -497,7 +497,7 @@ public class SysdynModel implements IMappingListener, IModel { public File getSimulationDir() { if(simulationDir == null) { File modelsDir = Activator.getBundleContext().getDataFile("models"); - String configName = configuration.getName(); + String configName = configuration.getLabel(); List files = Arrays.asList(modelsDir.list()); if (files.contains(configName)) { int i = 2; diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java index 5c8f955c..45cebeab 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java @@ -232,7 +232,6 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam SysdynResource sr = SysdynResource.getInstance(graph); numbers[0] = graph.getRelatedValue(model, sr.SysdynModel_startTime); numbers[1] = graph.getRelatedValue(model, sr.SysdynModel_stopTime); - numbers[2] = graph.getPossibleRelatedValue(model, sr.SysdynModel_outputInterval); PlaybackConfiguration config = new PlaybackConfiguration(); config.simulationDuration = numbers[1] - numbers[0] - time; diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/modelica/ModelicaWriter.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/modelica/ModelicaWriter.java index ab41ec5f..ea24ec70 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/modelica/ModelicaWriter.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/modelica/ModelicaWriter.java @@ -50,12 +50,32 @@ public class ModelicaWriter { b.append(" parameter Integer size;\n"); b.append(" parameter Integer elements[:];\n"); b.append("end Enumeration_class;\n\n"); - + for(Configuration conf : configurations) - writeConfiguration(conf, b); + writeConfiguration(conf, "SpreadSheetBook", b); + + b.append(getGlobalSpreadSheets(configurations)); return b.toString(); } + + /** + * + */ + private static String getGlobalSpreadSheets(Collection configurations) { + StringBuilder sheets = new StringBuilder(); + for(Configuration conf : configurations) { + if(conf.getModel() != null) { + for(IElement e : conf.getElements()) { + if(e instanceof Book) { + return ((Book)e).getBook(); + } + } + } + } + + return sheets.toString(); + } /** * Write a single configuration to a given string builder @@ -63,7 +83,7 @@ public class ModelicaWriter { * @param configuration Model or module configuration * @param b String builder */ - private static void writeConfiguration(Configuration configuration, StringBuilder b) { + private static void writeConfiguration(Configuration configuration, String spreadSheetClass, StringBuilder b) { String app; boolean game = RepresentationUtils.isGameExperimentActive(); @@ -77,7 +97,6 @@ public class ModelicaWriter { ArrayList inputDependencies = new ArrayList(); ArrayList outputDependencies = new ArrayList(); HashMap> moduleInputs = new HashMap>(); - Book book = null; // Initialize lists for(IElement element : configuration.getElements()) { @@ -112,9 +131,6 @@ public class ModelicaWriter { // References from child modules inputDependencies.add(dependency); } - } else if (element instanceof Book) { - // Spreadsheet book - book = (Book)element; } } @@ -125,8 +141,15 @@ public class ModelicaWriter { // If the configuration is model configuration, use model name. Otherwise, use configuration name. ModuleType mt = configuration.getModuleType(); - String className = mt != null ? (mt.getName().replace(" ", "")) : (configuration.getName().replace(" ", "")); - b.append("class ").append(className).append('\n'); + String className = mt != null ? (mt.getName().replace(" ", "")) : (configuration.getLabel().replace(" ", "")); + + b.append("class ").append(className); + + // Extend spreadsheetclass to get spreadsheet cell info + if(spreadSheetClass != null && !spreadSheetClass.isEmpty()) + b.append("\n extends " + spreadSheetClass + ";"); + + b.append("\n"); b.append("// Variable definitions\n"); for(IndependentVariable variable : variables) { @@ -164,11 +187,6 @@ public class ModelicaWriter { } } - if(book != null) { - b.append("// Spreadsheet definition\n"); - b.append(book.markBook()); - } - boolean initialEquations = false; for(Stock stock : stocks) { app = stock.getInitialEquation(); @@ -221,12 +239,6 @@ public class ModelicaWriter { b.append("end ").append(className).append(";\n\n"); - - // Update sheet definitions to contain the elements that were used. - if(book != null) { - int s = b.indexOf(book.markBook()); - b.replace(s, s + book.markBook().length(), book.getBook()); - } } /** diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Book.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Book.java index c4621a7e..031d4f43 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Book.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Book.java @@ -31,9 +31,16 @@ public class Book extends Variable { public String getBook() { StringBuilder book = new StringBuilder(); + + book.append("partial class SpreadSheetBook\n"); + for(Sheet sheet : sheets) book.append(sheet.getStringRepresentation()); + + book.append("end SpreadSheetBook;"); + return book.toString(); + } } diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Configuration.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Configuration.java index f13b4044..00d0efb3 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Configuration.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Configuration.java @@ -75,7 +75,7 @@ public class Configuration { } public String getLabel() { - return label; + return label != null ? label : name; } public ModuleType getModuleType() { diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Model.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Model.java index dbda4ea3..6e22190f 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Model.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Model.java @@ -16,8 +16,10 @@ import java.util.HashMap; import org.simantics.layer0.Layer0; import org.simantics.objmap.annotations.GraphType; +import org.simantics.objmap.annotations.RelatedElement; import org.simantics.objmap.annotations.RelatedElements; import org.simantics.objmap.annotations.RelatedValue; +import org.simantics.simulation.ontology.SimulationResource; import org.simantics.sysdyn.SysdynResource; import org.simantics.sysdyn.representation.annotations.BuiltinFunctions; @@ -37,6 +39,9 @@ public class Model { @RelatedValue(SysdynResource.URIs.SysdynModel_outputInterval) private Double outputInterval; + + @RelatedValue(SysdynResource.URIs.SysdynModel_simulationStepLength) + private Double stepLength; @RelatedValue(SysdynResource.URIs.SysdynModel_tolerance) private Double tolerance; @@ -46,6 +51,9 @@ public class Model { @RelatedValue(SysdynResource.URIs.SysdynModel_variableFilter) private String variableFilter; + + @RelatedElement(SimulationResource.URIs.HasConfiguration) + private Configuration configuration; @RelatedElements( value = Layer0.URIs.ConsistsOf, @@ -78,13 +86,20 @@ public class Model { } /** - * Result output interval + * Simulation output interval * @return */ public Double getOutputInterval() { return outputInterval; } + /** + * Simulation step length + * @return + */ + public Double getSimulationStepLength() { + return stepLength; + } /** * * @return Tolerance for simulation engine @@ -176,4 +191,13 @@ public class Model { public FunctionLibrary getBuiltins() { return builtins; } + + + /** + * + * @return Configuration of this model + */ + public Configuration getModelConfiguration() { + return configuration; + } } diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Sheet.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Sheet.java index 24106097..71a3b756 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Sheet.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Sheet.java @@ -66,7 +66,7 @@ public class Sheet extends org.simantics.sysdyn.representation.Variable { final StringBuilder clazz = new StringBuilder(); final HashSet possibleRanges = new HashSet(); - clazz.append(" class " + name + "_class\n "); + clazz.append(" class " + name + "_class\n"); // Write all doubles that have been used in expressions int counter = 0; @@ -83,7 +83,7 @@ public class Sheet extends org.simantics.sysdyn.representation.Variable { if(value instanceof Double) { Double d = (Double)value; - clazz.append("constant Real " + key + " = " + d + "; "); + clazz.append(" constant Real " + key + " = " + d + "; "); counter++; if(counter > 10) { counter = 0; @@ -116,7 +116,7 @@ public class Sheet extends org.simantics.sysdyn.representation.Variable { if(array[0].length > 1) { // Has two dimensions - clazz.append("constant Real[" + array.length + ", " + array[0].length + "] "); + clazz.append(" constant Real[" + array.length + ", " + array[0].length + "] "); clazz.append(possibleRange.replace(":", "_") + " = {"); for(int i = 0; i < array.length; i++) { clazz.append("{"); @@ -132,7 +132,7 @@ public class Sheet extends org.simantics.sysdyn.representation.Variable { clazz.append("};\n"); } else { // Has one dimension - clazz.append("constant Real[" + array.length + "] "); + clazz.append(" constant Real[" + array.length + "] "); clazz.append(possibleRange.replace(":", "_") + " = {"); for(int i = 0; i < array.length; i++) { clazz.append(array[i][0]); @@ -151,7 +151,7 @@ public class Sheet extends org.simantics.sysdyn.representation.Variable { } - clazz.append("\n end " + name + "_class;\n"); + clazz.append(" end " + name + "_class;\n"); clazz.append(" " + name + "_class " + name + ";\n"); return clazz.toString(); } @@ -163,7 +163,7 @@ public class Sheet extends org.simantics.sysdyn.representation.Variable { Variant cell = matrix.get(i, j); if(cell.getBinding().equals(Bindings.DOUBLE)) { array[i][j] = (Double)cell.getValue(); - } else if (cell.getBinding().equals(Bindings.MUTABLE_STRING)) { + } else if (cell.getBinding().equals(Bindings.MUTABLE_STRING) || (cell.getBinding().equals(Bindings.STRING))) { try { array[i][j] = Double.parseDouble(cell.getValue().toString()); } catch (NumberFormatException e) { diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variability.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variability.java index 7a5f165b..e12969f8 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variability.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variability.java @@ -71,7 +71,6 @@ public enum Variability { private static boolean isParameter(IndependentVariable variable, Configuration configuration, String reference, boolean allowVariables) { // Check if references are references to sheets or enumerations. // Sheet and Enumeration references are allowed, since sheets contain only constants / parameters - String r = reference.split("\\.")[0]; for(IElement element : configuration.getElements()) { if(element instanceof Module) { @@ -124,6 +123,27 @@ public enum Variability { } } } + + // Try to find sheet in another way: this might be a module type configuration. Find the model configuration and its sheet + if(configuration.getModuleType() != null) { + Object parent = configuration.getModuleType().getParent(); + if(parent != null && parent instanceof Model) { + configuration = ((Model)parent).getModelConfiguration(); + for(IElement element : configuration.getElements()) { + if(element instanceof Book) { + for(Sheet sheet : ((Book)element).getSheets()) { + if(r.equals(sheet.getName())) { + return true; + } + } + break; + } + } + } + } + + + // If there was no sheet for this reference name, or there was some other problem, return false return false; } diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/WithLookupExpression.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/WithLookupExpression.java index 15e34766..f40cc43e 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/WithLookupExpression.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/WithLookupExpression.java @@ -17,6 +17,7 @@ import org.simantics.sysdyn.SysdynResource; import org.simantics.sysdyn.representation.IndependentVariable; import org.simantics.sysdyn.representation.utils.FormatUtils; import org.simantics.sysdyn.representation.utils.IndexUtils; +import org.simantics.sysdyn.representation.utils.SheetFormatUtils; /** * Representation of a withlookup expression @@ -38,7 +39,7 @@ public class WithLookupExpression extends Expression { String range = IndexUtils.rangeToIndexes(variable, this.getArrayRange()); return - " " + variable.getName() + (range.equals("[:]") ? "" : range) + " = interpolate(" + equation + ", " + lookupTable + ");\n"; + " " + variable.getName() + (range.equals("[:]") ? "" : range) + " = interpolate(" + equation + ", " + SheetFormatUtils.reformatSheetReferences(variable, lookupTable) + ");\n"; } @Override diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/IndexUtils.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/IndexUtils.java index e2bfc7a0..053d146a 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/IndexUtils.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/IndexUtils.java @@ -38,11 +38,11 @@ public class IndexUtils { } return result; } - - + + public static String rangeToIndexes(Variable variable, String range) { - if(variable == null) - return range; + if(variable == null) + return range; StringBuilder sb = new StringBuilder(); ArrayIndexes arrayIndexes = variable.getArrayIndexes(); if(arrayIndexes == null || range == null) @@ -66,61 +66,66 @@ public class IndexUtils { else sb.append(rangeToken); } - + } return sb.toString(); } - + private static String fixForRangeEnumerations(Variable variable, String equation) { - ExpressionParser parser = new ExpressionParser(new StringReader(equation)); - try { - parser.expr(); - for(ForRange forRange : parser.getForRanges()) { - if(forRange.start.equals(forRange.end)) { - Variable v = getVariable(variable.getParentConfiguration(), forRange.start.image); - if(v instanceof Enumeration) { - equation = equation.replaceAll("in[\\s]*" + forRange.start.image + "($|[^\\.])", "in " + forRange.start.image + ".elements$1"); - } - } - } - } catch (ParseException e) { + ExpressionParser parser = new ExpressionParser(new StringReader(equation)); + try { + parser.expr(); + for(ForRange forRange : parser.getForRanges()) { + if(forRange.start.equals(forRange.end)) { + Variable v = getVariable(variable.getParentConfiguration(), forRange.start.image); + if(v instanceof Enumeration) { + equation = equation.replaceAll("in[\\s]*" + forRange.start.image + "($|[^\\.])", "in " + forRange.start.image + ".elements$1"); + } + } + } + } catch (ParseException e) { e.printStackTrace(); } return equation; } - + public static String equationRangesToIndexes(Variable variable, String equation) { - if(equation == null || !equation.contains("[")) return equation; - - StringBuilder result = new StringBuilder(); - String delimiters = "+-*/(){}[],. "; - StringTokenizer st = new StringTokenizer(equation, delimiters, true); - String prevToken = st.nextToken(); - result.append(prevToken); - while (st.hasMoreTokens()) { - String nextToken = st.nextToken(); - if (nextToken.equals("[")) { - StringBuilder range = new StringBuilder(); - range.append("["); - String rangeToken = st.nextToken(); - while(!rangeToken.equals("]")) { - range.append(rangeToken); - rangeToken = st.nextToken(); - } - range.append("]"); - - Variable prevVar = getVariable(variable.getParentConfiguration(), prevToken.trim()); - result.append(rangeToIndexes(prevVar, range.toString())); - } else { - result.append(nextToken); - } - prevToken = nextToken; - } - - equation = fixForRangeEnumerations(variable, result.toString()); - return equation; + if(equation == null) return equation; + + if(equation.contains("[")) { + StringBuilder result = new StringBuilder(); + String delimiters = "+-*/(){}[],. "; + StringTokenizer st = new StringTokenizer(equation, delimiters, true); + String prevToken = st.nextToken(); + result.append(prevToken); + while (st.hasMoreTokens()) { + String nextToken = st.nextToken(); + if (nextToken.equals("[")) { + StringBuilder range = new StringBuilder(); + range.append("["); + String rangeToken = st.nextToken(); + while(!rangeToken.equals("]")) { + range.append(rangeToken); + rangeToken = st.nextToken(); + } + range.append("]"); + + Variable prevVar = getVariable(variable.getParentConfiguration(), prevToken.trim()); + result.append(rangeToIndexes(prevVar, range.toString())); + } else { + result.append(nextToken); + } + prevToken = nextToken; + } + equation = fixForRangeEnumerations(variable, result.toString()); + } else if(equation.contains("{")){ + // Cases where there are {something for i in Enum} without [] brackets + equation = fixForRangeEnumerations(variable, equation); + } + + return equation; } - + private static Variable getVariable(Configuration configuration, String name) { for(IElement element : configuration.getElements()) { if(element instanceof Variable) { diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/SheetFormatUtils.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/SheetFormatUtils.java index 918eccbb..19b14ce8 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/SheetFormatUtils.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/SheetFormatUtils.java @@ -22,6 +22,8 @@ import org.simantics.sysdyn.expressionParser.ParseException; import org.simantics.sysdyn.expressionParser.Token; import org.simantics.sysdyn.representation.Configuration; import org.simantics.sysdyn.representation.IElement; +import org.simantics.sysdyn.representation.Model; +import org.simantics.sysdyn.representation.ModuleType; import org.simantics.sysdyn.representation.Sheet; import org.simantics.sysdyn.representation.Variable; @@ -38,6 +40,15 @@ public class SheetFormatUtils { for(String key : functionCalls.keySet()) { String[] parts = key.split("\\."); Object current = v.getParentConfiguration(); + + // Hack. Sheets can currently exist only in models, not in module types. + ModuleType moduleType= ((Configuration)current).getModuleType(); + if(moduleType != null) { + if(moduleType.getParent() != null && moduleType.getParent() instanceof Model) + current = ((Model)moduleType.getParent()).getModelConfiguration(); + } + // end Hack. + Object found = null; for(int i = 0; i < parts.length && current != null; i++) { found = null; @@ -62,7 +73,7 @@ public class SheetFormatUtils { String tmp = ""; int start = 0, end = 0, call = 0; String cellOrRange = null; - while((call = expression.indexOf(key, end)) >= 0) { + while((call = expression.indexOf(key + "(", end)) >= 0) { start = expression.indexOf("(", call); tmp += expression.substring(end, start); @@ -90,7 +101,7 @@ public class SheetFormatUtils { tmp += "." + cellOrRange; } tmp += expression.substring(end, expression.length()); - return tmp; + expression = tmp; } } diff --git a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java index df6b06ae..ccb4d92e 100644 --- a/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java +++ b/stable/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java @@ -42,7 +42,7 @@ public class SimulationJob extends Job { IModelicaMonitor monitor; public SimulationJob(SysdynModel model, Experiment experiment) { - super("Simulate " + model.getConfiguration().getName()); + super("Simulate " + model.getConfiguration().getLabel()); this.model = model; this.experiment = experiment; if(PlatformUI.isWorkbenchRunning()) { @@ -55,8 +55,8 @@ public class SimulationJob extends Job { @Override protected IStatus run(IProgressMonitor monitor) { - monitor.beginTask("Simulate " + model.getConfiguration().getName(), 5); - this.monitor.message("Simulate " + model.getConfiguration().getName()); + monitor.beginTask("Simulate " + model.getConfiguration().getLabel(), 5); + this.monitor.message("Simulate " + model.getConfiguration().getLabel()); try { model.update(); if(experiment instanceof SysdynExperiment)