* Overridden method to support csv-formatted simulation results\r
*/\r
@Override\r
- public void read(InputStream stream) {\r
+ public void read(InputStream stream, int outputInterval) {\r
errors.clear();\r
\r
// First line contains the variable names in format "name" (including quotes);\r
// Create lists for receiving values for each variable. Names still with quotes.\r
for(String name : names) {\r
if(!name.isEmpty())\r
- valueMap.put(name, new DataSet(name, new double[numberOfTimeSteps], new double[numberOfTimeSteps]));\r
+ valueMap.put(name, new DataSet(name, new double[numberOfLines], new double[numberOfLines]));\r
}\r
\r
int row = 0;\r
}\r
}\r
\r
- public static Map<String, double[]> read(InputStream in) throws IOException {\r
+ /**\r
+ * \r
+ * @param in InputStream of a mat file\r
+ * @param outputInterval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc... \r
+ * @return\r
+ * @throws IOException\r
+ */\r
+ public static Map<String, double[]> read(InputStream in, int outputInterval) throws IOException {\r
Mat4Reader reader = new Mat4Reader(in);\r
reader.readMatrix(); // Header\r
StringMatrix names = (StringMatrix)reader.readMatrix(); // Variable names\r
for(int i=0;i<info.columns;++i) {\r
if(infoData[i*4] != 2)\r
continue;\r
- double[] v = new double[values.columns];\r
+ // If values.columns % outputInterval != 0, the value in the last time step would not be displayed without adding a +1;\r
+ int size = values.columns % outputInterval != 0 ? values.columns / outputInterval + 1 : values.columns; \r
+ double[] v = new double[size];\r
int sc = infoData[i*4+1];\r
int c = sc > 0 ? sc-1 : 1-sc;\r
//System.out.println("i=" + i + ", sc=" + sc + ", c=" + c);\r
- for(int j=0;j<v.length;++j)\r
- v[j] = valueData[rows*j+c];\r
- if(sc < 0)\r
+ for(int j=0;j<v.length;++j) {\r
+ int adjusted = j * outputInterval;\r
+ if(adjusted >= values.columns) adjusted = values.columns - 1;\r
+ v[j] = valueData[rows * adjusted + c];\r
+ } if(sc < 0)\r
for(int j=0;j<v.length;++j)\r
v[j] = -v[j];\r
result.put(names.data[i], v);\r
public class MatSimulationResult extends SimulationResult {\r
\r
@Override\r
- public void read(InputStream stream) {\r
+ public void read(InputStream stream, int interval) {\r
Map<String, double[]> valueMap = null;\r
try {\r
- valueMap = Mat4Reader.read(stream);\r
+ valueMap = Mat4Reader.read(stream, interval);\r
} catch (IOException e) {\r
e.printStackTrace();\r
return;\r
\r
protected List<DataSet> variables = new ArrayList<DataSet>();\r
protected List<DataSet> initials = new ArrayList<DataSet>();\r
- protected int numberOfTimeSteps = 0;\r
+ protected int numberOfLines = 0;\r
\r
/**\r
* Private class used in displaying errors\r
}\r
\r
\r
- final static Pattern p1 = Pattern.compile("DataSet: ([^ ]*)");\r
+ \r
+ /**\r
+ * Read result file. Read all values in the result file.\r
+ * \r
+ * @param file result file\r
+ * @throws FileNotFoundException\r
+ * @throws IOException\r
+ */\r
+ public void read(File file) throws FileNotFoundException, IOException {\r
+ read(file, 1);\r
+ }\r
+\r
\r
/**\r
* Read result file\r
* \r
* @param file result file\r
+ * @param interval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc...\r
* @throws FileNotFoundException\r
* @throws IOException\r
*/\r
- public void read(File file) throws FileNotFoundException, IOException {\r
+ public void read(File file, int interval) throws FileNotFoundException, IOException {\r
// First check the number of time steps\r
FileReader fr = new FileReader(file);\r
LineNumberReader lnr = new LineNumberReader(fr);\r
lnr.skip(Long.MAX_VALUE);\r
- numberOfTimeSteps = lnr.getLineNumber() - 1; // minus the first row, which is for names\r
+ numberOfLines = lnr.getLineNumber() - 1; // minus the first row, which is for names\r
lnr.close();\r
fr.close();\r
\r
InputStream is = new FileInputStream(file);\r
- read(is);\r
+ read(is, interval);\r
is.close();\r
}\r
\r
- \r
+ final static Pattern p1 = Pattern.compile("DataSet: ([^ ]*)");\r
+\r
/**\r
* Read result file. The basic implementation supports\r
* plt-formatted results. Overridden to support other formats. \r
* @param stream FileInputStream for the result file\r
+ * @param interval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc...\r
*/\r
- public void read(InputStream stream) {\r
+ public void read(InputStream stream, int outputInterval) {\r
while(true) {\r
String line = getLine(stream);\r
if(line == null)\r
return;\r
String name = matcher.group(1);\r
\r
- double[] dtimes = new double[numberOfTimeSteps];\r
- double[] dvalues = new double[numberOfTimeSteps];\r
+ double[] dtimes = new double[numberOfLines];\r
+ double[] dvalues = new double[numberOfLines];\r
int i = 0;\r
while(true) {\r
String line = getLine(stream);\r
SYSDYN.SysdynModel <T MOD.StructuralModel
>-- SYSDYN.SysdynModel.startTime --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
>-- SYSDYN.SysdynModel.stopTime --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+ >-- SYSDYN.SysdynModel.simulationStepLength --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
>-- SYSDYN.SysdynModel.outputInterval --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
>-- SYSDYN.SysdynModel.tolerance --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
>-- SYSDYN.SysdynModel.solver --> L0.String <R L0.HasProperty : L0.FunctionalRelation
\r
FL = <http://www.simantics.org/Sysdyn-1.1/Built-in Functions> : SYSDYN.SysdynModelicaFunctionLibrary\r
\r
+FL.minmax : SYSDYN.SysdynModelicaFunction\r
+ L0.HasDescription "Limits the result of an equation to between the given minimum and maximum values."\r
+ SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """ input Real expression;\r
+ input Real minimum;\r
+ input Real maximum;\r
+ output Real result;\r
+algorithm\r
+ result := min(maximum, max(minimum, expression));"""\r
+\r
\r
FL.xidz : SYSDYN.SysdynModelicaFunction\r
L0.HasDescription "X if divided by zero"\r
public final Resource Built$in_Functions_Vensim_Functions_ZIDZ;\r
public final Resource Built$in_Functions_interpolate;\r
public final Resource Built$in_Functions_interpolateFull;\r
+ public final Resource Built$in_Functions_minmax;\r
public final Resource Built$in_Functions_xidz;\r
public final Resource Built$in_Functions_zidz;\r
public final Resource Center;\r
public final Resource SysdynModel;\r
public final Resource SysdynModel_outputInterval;\r
public final Resource SysdynModel_outputInterval_Inverse;\r
+ public final Resource SysdynModel_simulationStepLength;\r
+ public final Resource SysdynModel_simulationStepLength_Inverse;\r
public final Resource SysdynModel_solver;\r
public final Resource SysdynModel_solver_Inverse;\r
public final Resource SysdynModel_startTime;\r
public static final String Built$in_Functions_Vensim_Functions_ZIDZ = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/ZIDZ";\r
public static final String Built$in_Functions_interpolate = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolate";\r
public static final String Built$in_Functions_interpolateFull = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolateFull";\r
+ public static final String Built$in_Functions_minmax = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/minmax";\r
public static final String Built$in_Functions_xidz = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/xidz";\r
public static final String Built$in_Functions_zidz = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/zidz";\r
public static final String Center = "http://www.simantics.org/Sysdyn-1.1/Center";\r
public static final String SysdynModel = "http://www.simantics.org/Sysdyn-1.1/SysdynModel";\r
public static final String SysdynModel_outputInterval = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/outputInterval";\r
public static final String SysdynModel_outputInterval_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/outputInterval/Inverse";\r
+ public static final String SysdynModel_simulationStepLength = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/simulationStepLength";\r
+ public static final String SysdynModel_simulationStepLength_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/simulationStepLength/Inverse";\r
public static final String SysdynModel_solver = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/solver";\r
public static final String SysdynModel_solver_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/solver/Inverse";\r
public static final String SysdynModel_startTime = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/startTime";\r
Built$in_Functions_Vensim_Functions_ZIDZ = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_ZIDZ);\r
Built$in_Functions_interpolate = getResourceOrNull(graph, URIs.Built$in_Functions_interpolate);\r
Built$in_Functions_interpolateFull = getResourceOrNull(graph, URIs.Built$in_Functions_interpolateFull);\r
+ Built$in_Functions_minmax = getResourceOrNull(graph, URIs.Built$in_Functions_minmax);\r
Built$in_Functions_xidz = getResourceOrNull(graph, URIs.Built$in_Functions_xidz);\r
Built$in_Functions_zidz = getResourceOrNull(graph, URIs.Built$in_Functions_zidz);\r
Center = getResourceOrNull(graph, URIs.Center);\r
SysdynModel = getResourceOrNull(graph, URIs.SysdynModel);\r
SysdynModel_outputInterval = getResourceOrNull(graph, URIs.SysdynModel_outputInterval);\r
SysdynModel_outputInterval_Inverse = getResourceOrNull(graph, URIs.SysdynModel_outputInterval_Inverse);\r
+ SysdynModel_simulationStepLength = getResourceOrNull(graph, URIs.SysdynModel_simulationStepLength);\r
+ SysdynModel_simulationStepLength_Inverse = getResourceOrNull(graph, URIs.SysdynModel_simulationStepLength_Inverse);\r
SysdynModel_solver = getResourceOrNull(graph, URIs.SysdynModel_solver);\r
SysdynModel_solver_Inverse = getResourceOrNull(graph, URIs.SysdynModel_solver_Inverse);\r
SysdynModel_startTime = getResourceOrNull(graph, URIs.SysdynModel_startTime);\r
\r
import java.util.ArrayList;\r
import java.util.Collection;\r
+import java.util.TreeMap;\r
\r
import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
import org.simantics.db.ReadGraph;\r
import org.simantics.db.layer0.variable.Variable;\r
import org.simantics.db.layer0.variable.Variables;\r
import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ui.modelBrowser2.model.SheetsNode;\r
import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
import org.simantics.sysdyn.SysdynResource;\r
import org.simantics.sysdyn.ui.browser.nodes.BookNode;\r
import org.simantics.sysdyn.ui.browser.nodes.InputNode;\r
import org.simantics.sysdyn.ui.browser.nodes.ModuleNode;\r
import org.simantics.sysdyn.ui.browser.nodes.VariableNode;\r
+import org.simantics.utils.strings.AlphanumComparator;\r
\r
public class Configuration extends ViewpointContributor<ConfigurationNode<Resource>> {\r
\r
}\r
\r
SysdynResource sr = SysdynResource.getInstance(graph);\r
- ArrayList<Variable> variables = new ArrayList<Variable>();\r
- ArrayList<Variable> inputs = new ArrayList<Variable>();\r
- ArrayList<Variable> modules = new ArrayList<Variable>();\r
- ArrayList<Variable> enumerations = new ArrayList<Variable>();\r
+ TreeMap<String, Variable> variables = new TreeMap<String, Variable>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+ TreeMap<String, Variable> inputs = new TreeMap<String, Variable>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+ TreeMap<String, Variable> modules = new TreeMap<String, Variable>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+ TreeMap<String, Variable> enumerations = new TreeMap<String, Variable>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+\r
\r
for(Variable child : variable.browseChildren(graph)) {\r
Resource represents = (Resource)child.getPropertyValue(graph, Variables.REPRESENTS);\r
if(graph.isInstanceOf(represents, sr.IndependentVariable)) {\r
- variables.add(child);\r
+ variables.put(child.getName(graph), child);\r
} else if (graph.isInstanceOf(represents, sr.Input)) {\r
- inputs.add(child);\r
+ inputs.put(child.getName(graph), child);\r
} else if (graph.isInstanceOf(represents, sr.Module)) {\r
- modules.add(child);\r
+ modules.put(child.getName(graph), child);\r
} else if (graph.isInstanceOf(represents, sr.Enumeration)) {\r
- enumerations.add(child);\r
+ enumerations.put(child.getName(graph), child);\r
}\r
}\r
\r
- for (Variable v : variables) {\r
+ for (String s : variables.keySet()) {\r
+ Variable v = variables.get(s);\r
Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS);\r
result.add(new VariableNode<Variable>(v, represents));\r
}\r
- for (Variable v : inputs) {\r
+ \r
+ for (String s : inputs.keySet()) {\r
+ Variable v = inputs.get(s);\r
Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS);\r
result.add(new InputNode(v, represents));\r
}\r
- for (Variable v : modules) { \r
+ \r
+ for (String s : modules.keySet()) {\r
+ Variable v = modules.get(s);\r
Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS);\r
result.add(new ModuleNode(v, represents));\r
}\r
- for (Variable v : enumerations) {\r
+ \r
+ for (String s : enumerations.keySet()) {\r
+ Variable v = enumerations.get(s);\r
Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS);\r
result.add(new EnumerationNode(v, represents));\r
}\r
\r
import java.util.ArrayList;\r
import java.util.Collection;\r
+import java.util.TreeMap;\r
\r
import org.simantics.browsing.ui.common.node.AbstractNode;\r
import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
import org.simantics.db.ReadGraph;\r
import org.simantics.db.Resource;\r
import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
import org.simantics.db.exception.DatabaseException;\r
import org.simantics.layer0.Layer0;\r
import org.simantics.sysdyn.SysdynResource;\r
import org.simantics.sysdyn.ui.browser.nodes.FunctionNode;\r
import org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder;\r
import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionsFolder;\r
+import org.simantics.utils.strings.AlphanumComparator;\r
\r
public class FunctionLibraries extends ViewpointContributor<FunctionsFolder> {\r
\r
\r
ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
\r
- // Find model functions\r
+ TreeMap<String, Resource> sortResult = new TreeMap<String, Resource>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+ // Find and sort model functions\r
for(Resource function : graph.syncRequest(new ObjectsWithType(functionsFolder.data, l0.ConsistsOf, sr.SysdynModelicaFunction))) {\r
- result.add(new FunctionNode(function));\r
+ sortResult.put(NameUtils.getSafeName(graph, function), function);\r
}\r
+ for(Resource function : sortResult.values())\r
+ result.add(new FunctionNode(function));\r
\r
- // Find model function libraries\r
+ // Find and sort model function libraries\r
+ sortResult.clear();\r
for(Resource functionLibrary : graph.syncRequest(new ObjectsWithType(functionsFolder.data, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))) {\r
- result.add(new FunctionLibraryNode<Resource>(functionLibrary));\r
- } \r
- \r
+ sortResult.put(NameUtils.getSafeName(graph, functionLibrary), functionLibrary);\r
+ }\r
+ for(Resource functionLibrary : sortResult.values())\r
+ result.add(new FunctionLibraryNode<Resource>(functionLibrary));\r
+ \r
+ // Find built-in functions\r
Resource sysdyn = graph.getPossibleResource("http://www.simantics.org/Sysdyn-1.1");\r
if(sysdyn != null) {\r
for(Resource library : graph.syncRequest(new ObjectsWithType(sysdyn, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))) {\r
\r
import java.util.ArrayList;\r
import java.util.Collection;\r
+import java.util.TreeMap;\r
\r
import org.simantics.browsing.ui.common.node.AbstractNode;\r
import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
import org.simantics.db.ReadGraph;\r
import org.simantics.db.Resource;\r
import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
import org.simantics.db.exception.DatabaseException;\r
import org.simantics.layer0.Layer0;\r
import org.simantics.sysdyn.SysdynResource;\r
import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode;\r
import org.simantics.sysdyn.ui.browser.nodes.FunctionNode;\r
+import org.simantics.utils.strings.AlphanumComparator;\r
\r
public class LibraryFunctions extends ViewpointContributor<FunctionLibraryNode<Resource>> {\r
\r
FunctionLibraryNode<Resource> library) throws DatabaseException {\r
Layer0 l0 = Layer0.getInstance(graph);\r
ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+ \r
+ TreeMap<String, Resource> sortResult = new TreeMap<String, Resource>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+\r
+ // Find and sort functions in library\r
for(Resource function : graph.syncRequest(new ObjectsWithType(library.data, l0.ConsistsOf, SysdynResource.getInstance(graph).SysdynModelicaFunction))) {\r
- result.add(new FunctionNode(function));\r
+ sortResult.put(NameUtils.getSafeName(graph, function), function);\r
}\r
+ for(Resource function : sortResult.values())\r
+ result.add(new FunctionNode(function));\r
+\r
+ // Find and sort libraries in library\r
+ sortResult.clear();\r
for(Resource functionLibrary : graph.syncRequest(new ObjectsWithType(library.data, l0.ConsistsOf, SysdynResource.getInstance(graph).SysdynModelicaFunctionLibrary))) {\r
- result.add(new FunctionLibraryNode<Resource>(functionLibrary));\r
+ sortResult.put(NameUtils.getSafeName(graph, functionLibrary), functionLibrary);\r
}\r
+ for(Resource functionLibrary : sortResult.values())\r
+ result.add(new FunctionLibraryNode<Resource>(functionLibrary));\r
+ \r
return result;\r
\r
}\r
-\r
+ \r
@Override\r
public String getViewpointId() {\r
return "Standard";\r
\r
import java.util.ArrayList;\r
import java.util.Collection;\r
+import java.util.TreeMap;\r
\r
import org.simantics.browsing.ui.common.node.AbstractNode;\r
import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.databoard.Bindings;\r
import org.simantics.db.ReadGraph;\r
import org.simantics.db.Resource;\r
import org.simantics.db.common.request.ObjectsWithType;\r
import org.simantics.sysdyn.ui.browser.nodes.ModuleNode;\r
import org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode;\r
import org.simantics.sysdyn.ui.browser.nodes.VariableNode;\r
+import org.simantics.utils.strings.AlphanumComparator;\r
\r
public class ModuleType extends ViewpointContributor<ModuleTypeNode> {\r
\r
\r
if(instance == null) return result;\r
Resource conf = graph.getSingleObject(instance, str.IsDefinedBy);\r
+ \r
+ // Independent variables\r
+ TreeMap<String, Resource> variables = new TreeMap<String, Resource>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.IndependentVariable))) {\r
- result.add(new VariableNode<Resource>(r));\r
+ variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r);\r
}\r
+ for(String key : variables.keySet())\r
+ result.add(new VariableNode<Resource>(variables.get(key)));\r
+ \r
+ // Inputs\r
+ variables.clear();\r
for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.Input))) {\r
- result.add(new InputNode(r));\r
+ variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r);\r
}\r
+ for(String key : variables.keySet())\r
+ result.add(new InputNode(variables.get(key)));\r
+ \r
+ // Modules\r
+ variables.clear();\r
for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.Module))) {\r
- result.add(new ModuleNode(r));\r
+ variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r);\r
}\r
+ for(String key : variables.keySet())\r
+ result.add(new ModuleNode(variables.get(key)));\r
+ \r
+ // Enumerations\r
+ variables.clear();\r
for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.Enumeration))) {\r
- result.add(new EnumerationNode(r));\r
+ variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r);\r
}\r
+ for(String key : variables.keySet())\r
+ result.add(new EnumerationNode(variables.get(key)));\r
+ \r
return result;\r
}\r
\r
*******************************************************************************/\r
package org.simantics.sysdyn.ui.editor.participant;\r
\r
+import java.util.Map;\r
+\r
import org.simantics.databoard.Bindings;\r
import org.simantics.db.ReadGraph;\r
import org.simantics.db.Resource;\r
import org.simantics.structural.stubs.StructuralResource2;\r
import org.simantics.utils.datastructures.BinaryFunction;\r
\r
-public class SysdynComponentCopyAdvisor extends ComponentCopyAdvisor{\r
+public class SysdynComponentCopyAdvisor extends ComponentCopyAdvisor {\r
\r
@Override\r
- public Object copy(ISynchronizationContext context, WriteGraph graph, Resource source, Resource sourceContainer, Resource targetContainer) throws DatabaseException {\r
+ public Object copy(ISynchronizationContext context, WriteGraph graph, Resource source, Resource sourceContainer, Resource targetContainer, Map<Object, Object> map) throws DatabaseException {\r
\r
BinaryFunction<Boolean, ReadGraph, Statement> tester = new BinaryFunction<Boolean, ReadGraph, Statement>() {\r
\r
\r
StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
if(graph.isInstanceOf(source, sr2.Connection)) {\r
- copy = CopyAdvisorUtil.copy(graph, source, tester);\r
+ copy = CopyAdvisorUtil.copy(graph, source, tester, map);\r
} else {\r
copy = CopyAdvisorUtil.copy4(graph, source);\r
}\r
return;\r
spe = (SysdynPlaybackExperiment)experiment;\r
\r
- Double[] numbers = new Double[3];\r
+ Double[] numbers = new Double[2];\r
try {\r
numbers = SimanticsUI.getSession().syncRequest(new Read<Double[]>() {\r
@Override\r
public Double[] perform(ReadGraph graph) throws DatabaseException {\r
- Double[] numbers = new Double[3];\r
+ Double[] numbers = new Double[2];\r
Resource model = spe.getModel();\r
SysdynResource sr = SysdynResource.getInstance(graph);\r
numbers[0] = graph.getRelatedValue(model, sr.SysdynModel_startTime);\r
numbers[1] = graph.getRelatedValue(model, sr.SysdynModel_stopTime);\r
- numbers[2] = graph.getPossibleRelatedValue(model, sr.SysdynModel_outputInterval);\r
return numbers;\r
}\r
});\r
label = new Label(composite, SWT.NONE);\r
label.setText("Step length\n(empty = default)");\r
\r
+ TrackedText stepLength = new TrackedText(composite, support, SWT.BORDER | SWT.RIGHT);\r
+ stepLength.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.SysdynModel_simulationStepLength));\r
+ stepLength.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.SysdynModel_simulationStepLength));\r
+ stepLength.setInputValidator(new DoubleValidator());\r
+ GridDataFactory.fillDefaults().hint(200, SWT.DEFAULT).applyTo(stepLength.getWidget());\r
+ \r
+ label = new Label(composite, SWT.NONE);\r
+ label.setText("Output interval\n(empty = all steps)");\r
+\r
TrackedText outputInterval = new TrackedText(composite, support, SWT.BORDER | SWT.RIGHT);\r
outputInterval.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.SysdynModel_outputInterval));\r
outputInterval.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.SysdynModel_outputInterval));\r
outputInterval.setInputValidator(new DoubleValidator());\r
GridDataFactory.fillDefaults().hint(200, SWT.DEFAULT).applyTo(outputInterval.getWidget());\r
\r
+ \r
label = new Label(composite, SWT.NONE);\r
label.setText("Method");\r
\r
import org.simantics.sysdyn.ui.properties.widgets.ExpressionWidget;\r
import org.simantics.sysdyn.ui.properties.widgets.IsOutputWidget;\r
import org.simantics.sysdyn.ui.properties.widgets.ShortcutTabWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.arrays.NameAndArrayRangeModifyListener;\r
import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionWidgetInput;\r
import org.simantics.sysdyn.ui.properties.widgets.factories.VariableNameValidator;\r
import org.simantics.ui.SimanticsUI;\r
expressionWidget = new ExpressionWidget(expressionComposite, expressionSupport, SWT.NONE);\r
expressionWidget.setVariableTable(shortcutTabWidget.getVariableTable());\r
\r
+ arrayEquationCombo.addModifyListener(new NameAndArrayRangeModifyListener(support, expressionWidget, (ArrayExpressionCombo)arrayEquationCombo));\r
+\r
addListeners(context);\r
}\r
\r
\r
import java.util.ArrayList;\r
import java.util.Iterator;\r
-import java.util.Map;\r
-import java.util.StringTokenizer;\r
import java.util.LinkedHashMap;\r
+import java.util.Map;\r
\r
import org.eclipse.swt.widgets.Combo;\r
import org.eclipse.swt.widgets.Composite;\r
import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
-import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
import org.simantics.db.ReadGraph;\r
import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.VirtualGraph;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
import org.simantics.db.common.utils.NameUtils;\r
import org.simantics.db.common.utils.OrderedSetUtils;\r
import org.simantics.db.exception.DatabaseException;\r
import org.simantics.db.management.ISessionContext;\r
import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.service.VirtualGraphSupport;\r
import org.simantics.layer0.Layer0;\r
import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.utils.VariableNameUtils;\r
\r
public class ArrayExpressionCombo extends TrackedCombo {\r
\r
}\r
});\r
\r
- this.addModifyListener(new NameAndArrayRangeModifyListener(support));\r
}\r
\r
\r
sb.append("]");\r
return sb.toString();\r
}\r
-\r
- private class NameAndArrayRangeModifyListener extends ComboModifyListenerImpl<Resource> implements Widget {\r
-\r
- Resource lastExpression; \r
-\r
- public NameAndArrayRangeModifyListener(WidgetSupport support) {\r
- support.register(this);\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- super.setInput(context, input);\r
- }\r
-\r
- @Override\r
- public void modifyText(TrackedModifyEvent e) {\r
-\r
- Combo combo = (Combo)e.getWidget();\r
- LinkedHashMap<?, ?> data = (LinkedHashMap<?, ?>) combo.getData();\r
-\r
- Resource expression = (Resource) data.get(combo.getText());\r
- if(expression != null) {\r
- lastExpression = expression;\r
- lastSelectedIndex = combo.getSelectionIndex();\r
- } else {\r
- for(Object key : data.keySet()) {\r
- int index = lastSelectedIndex < 0 ? 0 : lastSelectedIndex;\r
- if((Integer)combo.getData((String)key) == index) {\r
- lastExpression = (Resource) data.get((String)key);\r
- break;\r
- }\r
- }\r
- }\r
-\r
- super.modifyText(e);\r
- }\r
-\r
- @Override\r
- public void applyText(WriteGraph graph, final Resource variable, String text)\r
- throws DatabaseException {\r
- StringTokenizer st = new StringTokenizer(text, "[]");\r
- final String newName = st.nextToken();\r
- String range = null;\r
- if(st.hasMoreTokens()) {\r
- range = st.nextToken();\r
- }\r
- String originalName = graph.getRelatedValue(variable, Layer0.getInstance(graph).HasName);\r
- if(!originalName.equals(newName)) {\r
- VariableNameUtils.renameInEquations(graph, variable, originalName, newName);\r
- graph.claimLiteral(variable, Layer0.getInstance(graph).HasName, newName);\r
- }\r
-\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
-\r
- if(range != null && lastExpression != null) {\r
- String oldRange = graph.getPossibleRelatedValue(lastExpression, sr.Expression_arrayRange);\r
- if(oldRange == null || !range.equals(oldRange)) {\r
- graph.claimLiteral(lastExpression, sr.Expression_arrayRange, "[" + range + "]");\r
- }\r
- } else if (range == null && lastExpression != null && graph.hasStatement(lastExpression, sr.Expression_arrayRange)) {\r
- graph.deny(lastExpression, sr.Expression_arrayRange);\r
- }\r
-\r
- Resource activeExpression = graph.getPossibleObject(variable, sr.IndependentVariable_activeExpression);\r
-\r
- if(lastExpression != null && !lastExpression.equals(activeExpression)) {\r
- VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
- final Session session = graph.getSession();\r
- session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- VirtualGraph runtime = graph.getService(VirtualGraph.class);\r
- session.asyncRequest(new WriteRequest(runtime) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))\r
- graph.deny(variable, sr.IndependentVariable_activeExpression);\r
- graph.claim(variable, sr.IndependentVariable_activeExpression, lastExpression);\r
- }\r
- }\r
- );\r
- }\r
- });\r
- }\r
- }\r
+ \r
+ /**\r
+ * Get the index that has previously been selected\r
+ * @return\r
+ */\r
+ public int getLastSelectedIndex() {\r
+ return lastSelectedIndex;\r
+ }\r
+ \r
+ public void setLastSelectedIndex(int lastSelectedIndex) {\r
+ this.lastSelectedIndex = lastSelectedIndex;\r
}\r
+\r
}\r
\r
--- /dev/null
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import java.util.LinkedHashMap;\r
+import java.util.StringTokenizer;\r
+\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.widgets.Combo;\r
+import org.simantics.Simantics;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.VirtualGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.db.service.VirtualGraphSupport;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.ArrayExpressionCombo;\r
+import org.simantics.sysdyn.ui.properties.widgets.ExpressionWidget;\r
+import org.simantics.sysdyn.ui.utils.VariableNameUtils;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Modification listener ONLY for ArrayExpressionCombos in EquationTabs.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NameAndArrayRangeModifyListener extends ComboModifyListenerImpl<Resource> implements Widget {\r
+\r
+ Resource lastExpression; \r
+ ExpressionWidget expressionWidget;\r
+ ArrayExpressionCombo arrayExpressionCombo;\r
+ Object lastInput;\r
+\r
+ public NameAndArrayRangeModifyListener(WidgetSupport support, ExpressionWidget expressionWidget, ArrayExpressionCombo arrayExpressionCombo) {\r
+ support.register(this);\r
+ this.expressionWidget = expressionWidget;\r
+ this.arrayExpressionCombo = arrayExpressionCombo;\r
+ }\r
+\r
+ @Override\r
+ public void setInput(ISessionContext context, Object input) {\r
+ super.setInput(context, input);\r
+ this.lastInput = input;\r
+ } \r
+ \r
+ public void modifyText(TrackedModifyEvent e) { \r
+ Combo combo = (Combo)e.getWidget();\r
+ LinkedHashMap<?, ?> data = (LinkedHashMap<?, ?>) combo.getData();\r
+ \r
+ Resource activeExpression = null;\r
+ try {\r
+ final Object input = lastInput;\r
+ activeExpression = Simantics.getSession().syncRequest(new Read<Resource>() {\r
+ @Override\r
+ public Resource perform(ReadGraph graph)\r
+ throws DatabaseException {\r
+ Resource variable = ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class);\r
+ return graph.getPossibleObject(variable, SysdynResource.getInstance(graph).IndependentVariable_activeExpression);\r
+ }\r
+ \r
+ });\r
+ } catch (DatabaseException e1) {\r
+ e1.printStackTrace();\r
+ }\r
+ \r
+\r
+ Resource expression = (Resource) data.get(combo.getText());\r
+ if(expression != null) {\r
+ lastExpression = expression;\r
+ arrayExpressionCombo.setLastSelectedIndex(combo.getSelectionIndex());\r
+ } else {\r
+ for(Object key : data.keySet()) {\r
+ int index = arrayExpressionCombo.getLastSelectedIndex() < 0 ? 0 : arrayExpressionCombo.getLastSelectedIndex();\r
+ if((Integer)combo.getData((String)key) == index) {\r
+ lastExpression = (Resource) data.get((String)key);\r
+ break;\r
+ }\r
+ }\r
+ }\r
+ \r
+ // If expression has changed (i.e. user actually selects a different item in the combo), save the previous \r
+ if(lastExpression != null && !lastExpression.equals(activeExpression)) {\r
+ expressionWidget.save();\r
+ }\r
+\r
+ super.modifyText(e);\r
+ }\r
+\r
+ @Override\r
+ public void applyText(WriteGraph graph, final Resource variable, String text)\r
+ throws DatabaseException {\r
+ StringTokenizer st = new StringTokenizer(text, "[]");\r
+ final String newName = st.nextToken();\r
+ String range = null;\r
+ if(st.hasMoreTokens()) {\r
+ range = st.nextToken();\r
+ }\r
+ String originalName = graph.getRelatedValue(variable, Layer0.getInstance(graph).HasName);\r
+ if(!originalName.equals(newName)) {\r
+ VariableNameUtils.renameInEquations(graph, variable, originalName, newName);\r
+ graph.claimLiteral(variable, Layer0.getInstance(graph).HasName, newName);\r
+ }\r
+\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+ if(range != null && lastExpression != null) {\r
+ String oldRange = graph.getPossibleRelatedValue(lastExpression, sr.Expression_arrayRange);\r
+ if(oldRange == null || !range.equals(oldRange)) {\r
+ graph.claimLiteral(lastExpression, sr.Expression_arrayRange, "[" + range + "]");\r
+ }\r
+ } else if (range == null && lastExpression != null && graph.hasStatement(lastExpression, sr.Expression_arrayRange)) {\r
+ graph.deny(lastExpression, sr.Expression_arrayRange);\r
+ }\r
+\r
+ Resource activeExpression = graph.getPossibleObject(variable, sr.IndependentVariable_activeExpression);\r
+\r
+ if(lastExpression != null && !lastExpression.equals(activeExpression)) {\r
+ VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
+ final Session session = graph.getSession();\r
+ session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {\r
+ @Override\r
+ public void perform(WriteGraph graph) throws DatabaseException {\r
+ VirtualGraph runtime = graph.getService(VirtualGraph.class);\r
+ session.asyncRequest(new WriteRequest(runtime) {\r
+ @Override\r
+ public void perform(WriteGraph graph) throws DatabaseException {\r
+ SysdynResource sr = SysdynResource.getInstance(graph);\r
+ if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))\r
+ graph.deny(variable, sr.IndependentVariable_activeExpression);\r
+ graph.claim(variable, sr.IndependentVariable_activeExpression, lastExpression);\r
+ }\r
+ });\r
+ }\r
+ });\r
+ }\r
+ }\r
+\r
+}\r
import org.simantics.graphviz.Graph;\r
import org.simantics.graphviz.Node;\r
import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
import org.simantics.sysdyn.SysdynResource;\r
\r
/**\r
// Model root was not found, return empty graph\r
if(model == null)\r
return g;\r
+ \r
+ // Find the parent module/model of the selected resource\r
+ Resource parentResource = graph.getPossibleObject(resource, l0.PartOf);\r
+ if(graph.isInstanceOf(parentResource, sr.ConfigurationDiagram)) {\r
+ parentResource = graph.getPossibleObject(parentResource, ModelingResources.getInstance(graph).DiagramToComposite);\r
+ } else if(graph.isInstanceOf(parentResource, sr.SysdynModel)) {\r
+ parentResource = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
+ }\r
\r
// Set root node\r
Node rootNode = new Node(g, NameUtils.getSafeLabel(graph, model));\r
rootNode.setShape("rectangle");\r
HashSet<Resource> visited = new HashSet<Resource>();\r
visited.add(model);\r
- findChildModules(g, rootNode, graph, model, visited);\r
+ findChildModules(g, rootNode, graph, model, parentResource, visited);\r
\r
\r
return g;\r
* @param parent Parent module or model\r
* @param graph ReadGraph\r
* @param resource Module type or model\r
+ * @param parent2 \r
* @param visited All visited modules. Needed to check for loops in the structure. Loops are not allowed.\r
* @throws DatabaseException\r
*/\r
- private void findChildModules(Graph g, Node parent, ReadGraph graph, Resource resource, HashSet<Resource> visited) throws DatabaseException {\r
+ private void findChildModules(Graph g, Node parent, ReadGraph graph, Resource resource, Resource parentResource, HashSet<Resource> visited) throws DatabaseException {\r
SysdynResource sr = SysdynResource.getInstance(graph);\r
Layer0 l0 = Layer0.getInstance(graph);\r
\r
+ Resource configuration = graph.syncRequest(new PossibleObjectWithType(resource, l0.ConsistsOf, sr.Configuration));\r
+\r
+ // Set the parent color different, if it is the parent of the selected resource\r
+ if(configuration.equals(parentResource))\r
+ parent.setColor("#ff8c00");\r
+ \r
HashMap<Resource, Integer> modules = new HashMap<Resource, Integer>();\r
\r
// Find all module children\r
- Resource configuration = graph.syncRequest(new PossibleObjectWithType(resource, l0.ConsistsOf, sr.Configuration));\r
for(Resource m : graph.getObjects(configuration, l0.ConsistsOf)) {\r
Resource type = graph.getPossibleObject(m, l0.InstanceOf);\r
if(graph.isInheritedFrom(type, sr.Module)) {\r
node.setFontColor("#FF0000");\r
continue;\r
} else {\r
- visited.add(type);\r
- findChildModules(g, node, graph, type, visited);\r
+ HashSet<Resource> copy = new HashSet<Resource>(visited);\r
+ copy.add(type);\r
+ findChildModules(g, node, graph, type, parentResource, copy);\r
}\r
\r
}\r
import org.simantics.sysdyn.representation.Enumeration;\r
import org.simantics.sysdyn.representation.EnumerationIndex;\r
import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.Model;\r
import org.simantics.sysdyn.representation.Module;\r
import org.simantics.sysdyn.representation.Sheet;\r
import org.simantics.sysdyn.representation.Variable;\r
for(int i = 0; i < parts.length && current != null; i++) {\r
current = getElement(current, parts[i]);\r
}\r
+ \r
+ if(current == null) {\r
+ // Sheets are currently located in the model root. Try to find the sheet.\r
+ current = conf.getModuleType().getParent(); // Get module type parent (should be a model)\r
+ if(current instanceof Model)\r
+ current = getElement(((Model)current).getModelConfiguration(), parts[0]); // Try to get the sheet\r
+ }\r
+ \r
if(current != null && current instanceof Sheet) {\r
Sheet sheet = (Sheet) current;\r
String e = ef.getExpression();\r
* @throws DatabaseException\r
*/\r
private static void traverseIndexes(ReadGraph g, String rvi, HashMap<String, String> rvis, List<Resource> arrayIndexes) throws DatabaseException {\r
- traverseIndexes(g, rvi, rvis, arrayIndexes, arrayIndexes.get(0), "", "");\r
+ traverseIndexes(g, rvi, rvis, arrayIndexes, 0, "", "");\r
}\r
\r
/**\r
* @param indexNamesSoFar String representation of the indexes so far in name format\r
* @throws DatabaseException\r
*/\r
- private static void traverseIndexes(ReadGraph g, String rvi, HashMap<String, String> rvis, List<Resource> arrayIndexes, Resource currentEnumeration, String indexesSoFar, String indexNamesSoFar) throws DatabaseException {\r
+ private static void traverseIndexes(ReadGraph g, String rvi, HashMap<String, String> rvis, List<Resource> arrayIndexes, int currentIndex, String indexesSoFar, String indexNamesSoFar) throws DatabaseException {\r
SysdynResource sr = SysdynResource.getInstance(g);\r
// Enumeration indexes of the current enumeration (e.g. the first EnumIndexes in Var[EnumIndexes, EnumIndexes, EnumIndexes])\r
- Resource enumerationIndexes = g.getPossibleObject(currentEnumeration, sr.Enumeration_enumerationIndexes);\r
+ Resource enumerationIndexes = g.getPossibleObject(arrayIndexes.get(currentIndex), sr.Enumeration_enumerationIndexes);\r
if(enumerationIndexes == null)\r
return;\r
List<Resource> indexes = OrderedSetUtils.toList(g, enumerationIndexes);\r
Boolean b = g.getPossibleRelatedValue(indexes.get(i), sr.EnumerationIndex_showEnumerationIndexInCharts, Bindings.BOOLEAN);\r
// 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\r
if(Boolean.TRUE.equals(b)) {\r
- int arrayIndex = arrayIndexes.indexOf(currentEnumeration);\r
// Get the name of the index\r
String name = g.getRelatedValue(indexes.get(i), Layer0.getInstance(g).HasName);\r
- if(arrayIndex < arrayIndexes.size() - 1)\r
+ if(currentIndex < arrayIndexes.size() - 1)\r
// If there are still more EnumIndexes, recursively call the function and add current index to indexesSoFar and indexNamesSoFar\r
- traverseIndexes(g, rvi, rvis, arrayIndexes, arrayIndexes.get(arrayIndex + 1), \r
+ traverseIndexes(g, rvi, rvis, arrayIndexes, currentIndex + 1, \r
indexesSoFar + (i + 1) +",", indexNamesSoFar + (name) +",");\r
else {\r
// The last enumeration. Add [rvi[1, 1, 1] = rvi[index1, index1, index1]}and so on to the rvis map\r
// Find all redeclarations\r
for(Resource redeclaration : graph.syncRequest(new ObjectsWithType(module, sr.Module_redeclaration, sr.Redeclaration))) {\r
Resource replaced = graph.getSingleObject(redeclaration, sr.Redeclaration_replacedEnumeration);\r
- if(enumerations.contains(replaced)) {\r
+ while(enumerations.contains(replaced)) {\r
// Replace the redelcared enumeration in enumerations -list with the replacing enumeration\r
enumerations.add(enumerations.indexOf(replaced), graph.getSingleObject(redeclaration, sr.Redeclaration_replacingEnumeration));\r
enumerations.remove(replaced);\r
*/\r
public class HistoryDatasetResult extends SimulationResult {\r
@Override\r
- public void read(File file) {} // Do nothing\r
+ public void read(File file, int interval) {} // Do nothing\r
@Override\r
- public void read(InputStream stream) {} // Do nothing\r
+ public void read(InputStream stream, int interval) {} // Do nothing\r
\r
private boolean disposed;\r
\r
Model model = configuration.getModel();\r
Double startTime = model.getStartTime();\r
Double stopTime = model.getStopTime();\r
- Double numberOfIntervals = model.getOutputInterval();\r
inits.put(SysdynInitKeys.START_VALUE, startTime.toString());\r
inits.put(SysdynInitKeys.STOP_VALUE, stopTime.toString());\r
String outputFormat = "\"mat\"";\r
inits.put(SysdynInitKeys.OUTPUT_FORMAT, outputFormat);\r
- if(numberOfIntervals != null) {\r
- inits.put(SysdynInitKeys.STEP_VALUE, numberOfIntervals.toString());\r
- inits.put(SysdynInitKeys.NUMBER_OF_INTERVALS, "" + ((int)((stopTime - startTime) / numberOfIntervals)));\r
+ \r
+ Double simulationStepLength = model.getSimulationStepLength();\r
+ if(simulationStepLength != null) {\r
+ inits.put(SysdynInitKeys.STEP_VALUE, simulationStepLength.toString());\r
+ inits.put(SysdynInitKeys.NUMBER_OF_INTERVALS, "" + ((int)((stopTime - startTime) / simulationStepLength)));\r
} else {\r
inits.put(SysdynInitKeys.STEP_VALUE, "" + (stopTime - startTime) / 500);\r
}\r
+ \r
+ Double outputInterval = model.getOutputInterval();\r
+ inits.put(SysdynInitKeys.OUTPUT_INTERVAL, outputInterval != null ? outputInterval.toString() : inits.get(SysdynInitKeys.STEP_VALUE));\r
+ \r
String method = "\"" + model.getSolver() + "\"";\r
inits.put(SysdynInitKeys.METHOD, method);\r
if(model.getTolerance() != null)\r
);\r
ModelicaManager.printProcessOutput(process, monitor);\r
\r
- Thread resultThread = getResultThread(simulationLocation, monitor, progressMonitor);\r
+ Thread resultThread = getResultThread(simulationLocation, inits, monitor, progressMonitor);\r
resultThread.run();\r
\r
process = null;\r
/**\r
* Get a thread for reading and saving reuslts from a normal simulation\r
* @param simulationLocation\r
+ * @param inits \r
* @param monitor\r
* @param progressMonitor\r
* @return\r
*/\r
- protected Thread getResultThread(final SimulationLocation simulationLocation, final IModelicaMonitor monitor, final IProgressMonitor progressMonitor) {\r
+ protected Thread getResultThread(final SimulationLocation simulationLocation, final HashMap<String, String> inits, final IModelicaMonitor monitor, final IProgressMonitor progressMonitor) {\r
return new Thread() {\r
@Override\r
public void run() {\r
result = new SimulationResult();\r
else\r
result = new MatSimulationResult(); // The latest format\r
- result.read(simulationLocation.outputFile);\r
+ \r
+ \r
+ // The interval of results saved. Every result? Every other result? etc...\r
+ int outIntervalInt = 1;\r
+ String outputInterval = inits.get(SysdynInitKeys.OUTPUT_INTERVAL);\r
+ if(outputInterval != null) {\r
+ String stepTime = inits.get(SysdynInitKeys.STEP_VALUE);\r
+ \r
+ Double step = Double.parseDouble(stepTime);\r
+ Double outInterval = Double.parseDouble(outputInterval);\r
+ \r
+ double nearest = roundUp(outInterval, step);\r
+ outIntervalInt = (int)(nearest / step);\r
+ if(outIntervalInt <= 0) outIntervalInt = 1;\r
+ }\r
+ \r
+ result.read(simulationLocation.outputFile, outIntervalInt);\r
result.readInits(simulationLocation.initFile);\r
result.filter();\r
sysdynModel.getSysdynResult().setResult(result);\r
}\r
};\r
}\r
+ \r
+ protected static double roundUp(double numToRound, double multiple) { \r
+ if(multiple == 0) {\r
+ return numToRound; \r
+ }\r
+ double remainder = numToRound % multiple; \r
+ if (remainder == 0) {\r
+ return numToRound; \r
+ }\r
+ return numToRound + multiple - remainder; \r
+ } \r
\r
\r
/**\r
protected static SimulationLocation createSimulationFiles(SysdynModel sysdynModel, String modelText, HashMap<String, String> inits, String additionalScript, boolean fmu) throws IOException {\r
return ModelicaManager.createSimulationFiles(\r
sysdynModel.getSimulationDir(),\r
- sysdynModel.getConfiguration().getName(),\r
+ sysdynModel.getConfiguration().getLabel(),\r
modelText,\r
inits,\r
additionalScript,\r
\r
protected void storeImportantInits(HashMap<String, String> inits) {\r
previousImportantInits.clear();\r
- previousImportantInits.put("start value", inits.get(SysdynInitKeys.START_VALUE));\r
- previousImportantInits.put("stop value", inits.get(SysdynInitKeys.STOP_VALUE));\r
- previousImportantInits.put("method", inits.get(SysdynInitKeys.METHOD));\r
- previousImportantInits.put("outputFormat", inits.get(SysdynInitKeys.OUTPUT_FORMAT));\r
- previousImportantInits.put("variableFilter", inits.get(SysdynInitKeys.VARIABLE_FILTER));\r
+ previousImportantInits.put(SysdynInitKeys.START_VALUE, inits.get(SysdynInitKeys.START_VALUE));\r
+ previousImportantInits.put(SysdynInitKeys.STOP_VALUE, inits.get(SysdynInitKeys.STOP_VALUE));\r
+ previousImportantInits.put(SysdynInitKeys.METHOD, inits.get(SysdynInitKeys.METHOD));\r
+ previousImportantInits.put(SysdynInitKeys.OUTPUT_FORMAT, inits.get(SysdynInitKeys.OUTPUT_FORMAT));\r
+ previousImportantInits.put(SysdynInitKeys.VARIABLE_FILTER, inits.get(SysdynInitKeys.VARIABLE_FILTER));\r
}\r
\r
/**\r
import org.simantics.modelica.fmi.FMUJNIException;\r
import org.simantics.simulation.experiment.ExperimentState;\r
import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.utils.datastructures.Pair;\r
+import org.simantics.utils.datastructures.Triple;\r
\r
/**\r
* Game experiment\r
private HashMap<String, ArrayList<Double>> results;\r
private double stepLength = DEFAULT_STEP_LENGTH;\r
private double stepDuration = DEFAULT_STEP_DURATION;\r
+ private int savePer = 1;\r
\r
public static double DEFAULT_STEP_DURATION = 1.0;\r
public static double DEFAULT_STEP_LENGTH = 0.1;\r
+ public static int DEFAULT_OUTPUT_INTERVAL = 1;\r
\r
public SysdynGameExperiment(Resource experiment, Resource model) {\r
super(experiment, model);\r
this.stepLength = stepLength;\r
}\r
\r
+ public void setOutputInterval(int interval) {\r
+ this.savePer = interval;\r
+ }\r
+\r
+ \r
public FMUControlJNI getFMUControl() {\r
return control;\r
}\r
\r
results = new HashMap<String, ArrayList<Double>>();\r
\r
- g.asyncRequest(new Read<Pair<Double, Double>>() {\r
+ g.asyncRequest(new Read<Triple<Double, Double, Double>>() {\r
\r
@Override\r
- public Pair<Double, Double> perform(ReadGraph graph)\r
+ public Triple<Double, Double, Double> perform(ReadGraph graph)\r
throws DatabaseException {\r
SysdynResource sr = SysdynResource.getInstance(graph);\r
Double stepDuration = graph.getPossibleRelatedValue(experiment, sr.GameExperiment_stepDuration);\r
- Double stepLength =graph.getPossibleRelatedValue(experiment, sr.GameExperiment_stepLength);\r
- return new Pair<Double, Double>(stepDuration, stepLength);\r
+ Double stepLength = graph.getPossibleRelatedValue(experiment, sr.GameExperiment_stepLength);\r
+ Double outputInterval = graph.getPossibleRelatedValue(model, sr.SysdynModel_outputInterval);\r
+ return new Triple<Double, Double, Double>(stepDuration, stepLength, outputInterval);\r
}\r
- }, new AsyncListener<Pair<Double, Double>>() {\r
+ }, new AsyncListener<Triple<Double, Double, Double>>() {\r
\r
@Override\r
public void execute(AsyncReadGraph graph,\r
- Pair<Double, Double> result) {\r
+ Triple<Double, Double, Double> result) {\r
setStepDuration(result.first != null ? result.first : DEFAULT_STEP_DURATION);\r
setStepLength(result.second != null ? result.second : DEFAULT_STEP_LENGTH);\r
+ \r
+ if(result.third == null) {\r
+ setOutputInterval(DEFAULT_OUTPUT_INTERVAL);\r
+ } else {\r
+ double nearest = roundUp(result.third, getStepLength());\r
+ int interval = (int)(nearest / getStepLength());\r
+ if(interval <= 0) interval = 1;\r
+ setOutputInterval(interval);\r
+ }\r
}\r
\r
@Override\r
throwable.printStackTrace();\r
setStepDuration(DEFAULT_STEP_DURATION);\r
setStepLength(DEFAULT_STEP_LENGTH);\r
+ setOutputInterval(DEFAULT_OUTPUT_INTERVAL);\r
}\r
\r
@Override\r
\r
@Override\r
protected IStatus run(IProgressMonitor monitor) {\r
- \r
int nSteps = (int)(duration / stepLength); \r
int work = 1 + nSteps * 3 + 2; // initialization + number of steps * number of phases per step + set result + call result listeners \r
\r
double[] results = new double[subscription.length];\r
\r
monitor.worked(1);\r
-\r
+ \r
+ int stepNumber = 1;\r
while(control.getTime() < (eTime - 1e-9)) { // Substract a very small number, because OpenModelica is not very precise with its Real numbers\r
monitor.subTask("Simulate step (time = " + control.getTime() + ")");\r
control.simulateStep();\r
monitor.worked(1);\r
\r
- monitor.subTask("Get results (time = " + control.getTime() + ")");\r
- results = control.getSubscribedResults(results);\r
- monitor.worked(1);\r
-\r
- monitor.subTask("Save results (time = " + control.getTime() + ")");\r
- for(int k = 0; k < subscription.length; k++) {\r
- SysdynGameExperiment.this.results.get(subscription[k]).add(results[k]);\r
+ if(stepNumber % savePer == 0) {\r
+ monitor.subTask("Get results (time = " + control.getTime() + ")");\r
+ results = control.getSubscribedResults(results);\r
+ monitor.worked(1);\r
+\r
+ monitor.subTask("Save results (time = " + control.getTime() + ")");\r
+ for(int k = 0; k < subscription.length; k++) {\r
+ SysdynGameExperiment.this.results.get(subscription[k]).add(results[k]);\r
+ }\r
+ } else {\r
+ monitor.worked(1);\r
}\r
+ stepNumber++;\r
monitor.worked(1);\r
}\r
\r
} catch (FMUJNIException e) {\r
System.err.println("SysdynGameExperiment simulateDuration failed: \n\t" + e.getMessage());\r
}\r
- \r
return Status.OK_STATUS;\r
}\r
}\r
public static String METHOD = "method";\r
public static String TOLERANCE = "tolerance";\r
public static String VARIABLE_FILTER = "variableFilter";\r
+ public static String OUTPUT_INTERVAL = "outputInterval";\r
\r
}\r
e.printStackTrace();\r
}\r
\r
- // Add the current result if there is one\r
- if(getSysdynResult() != null)\r
- activeResults.add(0, getSysdynResult() );\r
-\r
return activeResults;\r
}\r
\r
\r
@Override\r
public void execute(ArrayList<SysdynResult> result) {\r
+ // Add the current result if there is one\r
+ if(result != null && getSysdynResult() != null)\r
+ result.add(0, getSysdynResult() );\r
+ \r
activeResults = result;\r
resultChanged();\r
}\r
public File getSimulationDir() {\r
if(simulationDir == null) {\r
File modelsDir = Activator.getBundleContext().getDataFile("models");\r
- String configName = configuration.getName();\r
+ String configName = configuration.getLabel();\r
List<String> files = Arrays.asList(modelsDir.list());\r
if (files.contains(configName)) {\r
int i = 2;\r
SysdynResource sr = SysdynResource.getInstance(graph);\r
numbers[0] = graph.getRelatedValue(model, sr.SysdynModel_startTime);\r
numbers[1] = graph.getRelatedValue(model, sr.SysdynModel_stopTime);\r
- numbers[2] = graph.getPossibleRelatedValue(model, sr.SysdynModel_outputInterval);\r
\r
PlaybackConfiguration config = new PlaybackConfiguration();\r
config.simulationDuration = numbers[1] - numbers[0] - time;\r
b.append(" parameter Integer size;\n");\r
b.append(" parameter Integer elements[:];\n");\r
b.append("end Enumeration_class;\n\n");\r
-\r
+ \r
for(Configuration conf : configurations)\r
- writeConfiguration(conf, b);\r
+ writeConfiguration(conf, "SpreadSheetBook", b);\r
+ \r
+ b.append(getGlobalSpreadSheets(configurations));\r
\r
return b.toString();\r
}\r
+ \r
+ /**\r
+ * \r
+ */\r
+ private static String getGlobalSpreadSheets(Collection<Configuration> configurations) {\r
+ StringBuilder sheets = new StringBuilder();\r
+ for(Configuration conf : configurations) {\r
+ if(conf.getModel() != null) {\r
+ for(IElement e : conf.getElements()) {\r
+ if(e instanceof Book) {\r
+ return ((Book)e).getBook();\r
+ }\r
+ }\r
+ }\r
+ }\r
+ \r
+ return sheets.toString();\r
+ }\r
\r
/**\r
* Write a single configuration to a given string builder\r
* @param configuration Model or module configuration\r
* @param b String builder\r
*/\r
- private static void writeConfiguration(Configuration configuration, StringBuilder b) {\r
+ private static void writeConfiguration(Configuration configuration, String spreadSheetClass, StringBuilder b) {\r
String app;\r
\r
boolean game = RepresentationUtils.isGameExperimentActive();\r
ArrayList<Dependency> inputDependencies = new ArrayList<Dependency>();\r
ArrayList<Dependency> outputDependencies = new ArrayList<Dependency>();\r
HashMap<String, ArrayList<Input>> moduleInputs = new HashMap<String, ArrayList<Input>>();\r
- Book book = null;\r
\r
// Initialize lists\r
for(IElement element : configuration.getElements()) {\r
// References from child modules\r
inputDependencies.add(dependency);\r
}\r
- } else if (element instanceof Book) {\r
- // Spreadsheet book\r
- book = (Book)element;\r
}\r
}\r
\r
\r
// If the configuration is model configuration, use model name. Otherwise, use configuration name.\r
ModuleType mt = configuration.getModuleType();\r
- String className = mt != null ? (mt.getName().replace(" ", "")) : (configuration.getName().replace(" ", ""));\r
- b.append("class ").append(className).append('\n');\r
+ String className = mt != null ? (mt.getName().replace(" ", "")) : (configuration.getLabel().replace(" ", ""));\r
+ \r
+ b.append("class ").append(className);\r
+ \r
+ // Extend spreadsheetclass to get spreadsheet cell info\r
+ if(spreadSheetClass != null && !spreadSheetClass.isEmpty())\r
+ b.append("\n extends " + spreadSheetClass + ";");\r
+ \r
+ b.append("\n");\r
\r
b.append("// Variable definitions\n");\r
for(IndependentVariable variable : variables) {\r
}\r
}\r
\r
- if(book != null) {\r
- b.append("// Spreadsheet definition\n");\r
- b.append(book.markBook());\r
- }\r
-\r
boolean initialEquations = false;\r
for(Stock stock : stocks) {\r
app = stock.getInitialEquation();\r
\r
b.append("end ").append(className).append(";\n\n");\r
\r
-\r
- // Update sheet definitions to contain the elements that were used.\r
- if(book != null) {\r
- int s = b.indexOf(book.markBook());\r
- b.replace(s, s + book.markBook().length(), book.getBook());\r
- }\r
}\r
\r
/**\r
\r
public String getBook() {\r
StringBuilder book = new StringBuilder();\r
+ \r
+ book.append("partial class SpreadSheetBook\n");\r
+ \r
for(Sheet sheet : sheets)\r
book.append(sheet.getStringRepresentation());\r
+ \r
+ book.append("end SpreadSheetBook;");\r
+ \r
return book.toString();\r
+ \r
}\r
\r
}\r
}\r
\r
public String getLabel() {\r
- return label;\r
+ return label != null ? label : name;\r
}\r
\r
public ModuleType getModuleType() {\r
\r
import org.simantics.layer0.Layer0;\r
import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
import org.simantics.objmap.annotations.RelatedElements;\r
import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
import org.simantics.sysdyn.SysdynResource;\r
import org.simantics.sysdyn.representation.annotations.BuiltinFunctions;\r
\r
\r
@RelatedValue(SysdynResource.URIs.SysdynModel_outputInterval)\r
private Double outputInterval;\r
+ \r
+ @RelatedValue(SysdynResource.URIs.SysdynModel_simulationStepLength)\r
+ private Double stepLength;\r
\r
@RelatedValue(SysdynResource.URIs.SysdynModel_tolerance)\r
private Double tolerance;\r
\r
@RelatedValue(SysdynResource.URIs.SysdynModel_variableFilter)\r
private String variableFilter;\r
+ \r
+ @RelatedElement(SimulationResource.URIs.HasConfiguration)\r
+ private Configuration configuration;\r
\r
@RelatedElements(\r
value = Layer0.URIs.ConsistsOf,\r
}\r
\r
/**\r
- * Result output interval\r
+ * Simulation output interval\r
* @return\r
*/\r
public Double getOutputInterval() {\r
return outputInterval;\r
}\r
\r
+ /**\r
+ * Simulation step length\r
+ * @return\r
+ */\r
+ public Double getSimulationStepLength() {\r
+ return stepLength;\r
+ }\r
/**\r
* \r
* @return Tolerance for simulation engine\r
public FunctionLibrary getBuiltins() {\r
return builtins;\r
}\r
+ \r
+ \r
+ /**\r
+ * \r
+ * @return Configuration of this model\r
+ */\r
+ public Configuration getModelConfiguration() {\r
+ return configuration;\r
+ }\r
}\r
final StringBuilder clazz = new StringBuilder();\r
final HashSet<String> possibleRanges = new HashSet<String>();\r
\r
- clazz.append(" class " + name + "_class\n ");\r
+ clazz.append(" class " + name + "_class\n");\r
\r
// Write all doubles that have been used in expressions\r
int counter = 0;\r
\r
if(value instanceof Double) {\r
Double d = (Double)value;\r
- clazz.append("constant Real " + key + " = " + d + "; ");\r
+ clazz.append(" constant Real " + key + " = " + d + "; ");\r
counter++;\r
if(counter > 10) {\r
counter = 0;\r
\r
if(array[0].length > 1) {\r
// Has two dimensions \r
- clazz.append("constant Real[" + array.length + ", " + array[0].length + "] ");\r
+ clazz.append(" constant Real[" + array.length + ", " + array[0].length + "] ");\r
clazz.append(possibleRange.replace(":", "_") + " = {");\r
for(int i = 0; i < array.length; i++) {\r
clazz.append("{");\r
clazz.append("};\n");\r
} else {\r
// Has one dimension\r
- clazz.append("constant Real[" + array.length + "] ");\r
+ clazz.append(" constant Real[" + array.length + "] ");\r
clazz.append(possibleRange.replace(":", "_") + " = {");\r
for(int i = 0; i < array.length; i++) {\r
clazz.append(array[i][0]);\r
}\r
\r
\r
- clazz.append("\n end " + name + "_class;\n");\r
+ clazz.append(" end " + name + "_class;\n");\r
clazz.append(" " + name + "_class " + name + ";\n");\r
return clazz.toString();\r
}\r
Variant cell = matrix.get(i, j);\r
if(cell.getBinding().equals(Bindings.DOUBLE)) {\r
array[i][j] = (Double)cell.getValue();\r
- } else if (cell.getBinding().equals(Bindings.MUTABLE_STRING)) {\r
+ } else if (cell.getBinding().equals(Bindings.MUTABLE_STRING) || (cell.getBinding().equals(Bindings.STRING))) {\r
try {\r
array[i][j] = Double.parseDouble(cell.getValue().toString());\r
} catch (NumberFormatException e) {\r
private static boolean isParameter(IndependentVariable variable, Configuration configuration, String reference, boolean allowVariables) {\r
// Check if references are references to sheets or enumerations. \r
// Sheet and Enumeration references are allowed, since sheets contain only constants / parameters\r
-\r
String r = reference.split("\\.")[0]; \r
for(IElement element : configuration.getElements()) {\r
if(element instanceof Module) {\r
}\r
}\r
}\r
+ \r
+ // Try to find sheet in another way: this might be a module type configuration. Find the model configuration and its sheet\r
+ if(configuration.getModuleType() != null) {\r
+ Object parent = configuration.getModuleType().getParent();\r
+ if(parent != null && parent instanceof Model) {\r
+ configuration = ((Model)parent).getModelConfiguration();\r
+ for(IElement element : configuration.getElements()) {\r
+ if(element instanceof Book) {\r
+ for(Sheet sheet : ((Book)element).getSheets()) {\r
+ if(r.equals(sheet.getName())) {\r
+ return true;\r
+ }\r
+ }\r
+ break;\r
+ }\r
+ }\r
+ }\r
+ }\r
+ \r
+ \r
+ \r
// If there was no sheet for this reference name, or there was some other problem, return false\r
return false;\r
}\r
import org.simantics.sysdyn.representation.IndependentVariable;\r
import org.simantics.sysdyn.representation.utils.FormatUtils;\r
import org.simantics.sysdyn.representation.utils.IndexUtils;\r
+import org.simantics.sysdyn.representation.utils.SheetFormatUtils;\r
\r
/**\r
* Representation of a withlookup expression\r
String range = IndexUtils.rangeToIndexes(variable, this.getArrayRange());\r
\r
return \r
- " " + variable.getName() + (range.equals("[:]") ? "" : range) + " = interpolate(" + equation + ", " + lookupTable + ");\n";\r
+ " " + variable.getName() + (range.equals("[:]") ? "" : range) + " = interpolate(" + equation + ", " + SheetFormatUtils.reformatSheetReferences(variable, lookupTable) + ");\n";\r
}\r
\r
@Override\r
}\r
return result;\r
}\r
- \r
- \r
+\r
+\r
public static String rangeToIndexes(Variable variable, String range) {\r
- if(variable == null)\r
- return range;\r
+ if(variable == null)\r
+ return range;\r
StringBuilder sb = new StringBuilder();\r
ArrayIndexes arrayIndexes = variable.getArrayIndexes();\r
if(arrayIndexes == null || range == null)\r
else\r
sb.append(rangeToken);\r
}\r
- \r
+\r
}\r
return sb.toString();\r
}\r
- \r
+\r
private static String fixForRangeEnumerations(Variable variable, String equation) {\r
- ExpressionParser parser = new ExpressionParser(new StringReader(equation));\r
- try {\r
- parser.expr();\r
- for(ForRange forRange : parser.getForRanges()) {\r
- if(forRange.start.equals(forRange.end)) {\r
- Variable v = getVariable(variable.getParentConfiguration(), forRange.start.image);\r
- if(v instanceof Enumeration) {\r
- equation = equation.replaceAll("in[\\s]*" + forRange.start.image + "($|[^\\.])", "in " + forRange.start.image + ".elements$1");\r
- }\r
- }\r
- }\r
- } catch (ParseException e) {\r
+ ExpressionParser parser = new ExpressionParser(new StringReader(equation));\r
+ try {\r
+ parser.expr();\r
+ for(ForRange forRange : parser.getForRanges()) {\r
+ if(forRange.start.equals(forRange.end)) {\r
+ Variable v = getVariable(variable.getParentConfiguration(), forRange.start.image);\r
+ if(v instanceof Enumeration) {\r
+ equation = equation.replaceAll("in[\\s]*" + forRange.start.image + "($|[^\\.])", "in " + forRange.start.image + ".elements$1");\r
+ }\r
+ }\r
+ }\r
+ } catch (ParseException e) {\r
e.printStackTrace();\r
}\r
return equation;\r
}\r
- \r
+\r
public static String equationRangesToIndexes(Variable variable, String equation) {\r
- if(equation == null || !equation.contains("[")) return equation;\r
- \r
- StringBuilder result = new StringBuilder();\r
- String delimiters = "+-*/(){}[],. ";\r
- StringTokenizer st = new StringTokenizer(equation, delimiters, true);\r
- String prevToken = st.nextToken();\r
- result.append(prevToken);\r
- while (st.hasMoreTokens()) {\r
- String nextToken = st.nextToken();\r
- if (nextToken.equals("[")) {\r
- StringBuilder range = new StringBuilder();\r
- range.append("[");\r
- String rangeToken = st.nextToken();\r
- while(!rangeToken.equals("]")) {\r
- range.append(rangeToken);\r
- rangeToken = st.nextToken();\r
- }\r
- range.append("]");\r
- \r
- Variable prevVar = getVariable(variable.getParentConfiguration(), prevToken.trim());\r
- result.append(rangeToIndexes(prevVar, range.toString()));\r
- } else {\r
- result.append(nextToken);\r
- }\r
- prevToken = nextToken;\r
- }\r
- \r
- equation = fixForRangeEnumerations(variable, result.toString());\r
- return equation;\r
+ if(equation == null) return equation;\r
+\r
+ if(equation.contains("[")) {\r
+ StringBuilder result = new StringBuilder();\r
+ String delimiters = "+-*/(){}[],. ";\r
+ StringTokenizer st = new StringTokenizer(equation, delimiters, true);\r
+ String prevToken = st.nextToken();\r
+ result.append(prevToken);\r
+ while (st.hasMoreTokens()) {\r
+ String nextToken = st.nextToken();\r
+ if (nextToken.equals("[")) {\r
+ StringBuilder range = new StringBuilder();\r
+ range.append("[");\r
+ String rangeToken = st.nextToken();\r
+ while(!rangeToken.equals("]")) {\r
+ range.append(rangeToken);\r
+ rangeToken = st.nextToken();\r
+ }\r
+ range.append("]");\r
+\r
+ Variable prevVar = getVariable(variable.getParentConfiguration(), prevToken.trim());\r
+ result.append(rangeToIndexes(prevVar, range.toString()));\r
+ } else {\r
+ result.append(nextToken);\r
+ }\r
+ prevToken = nextToken;\r
+ }\r
+ equation = fixForRangeEnumerations(variable, result.toString());\r
+ } else if(equation.contains("{")){\r
+ // Cases where there are {something for i in Enum} without [] brackets\r
+ equation = fixForRangeEnumerations(variable, equation);\r
+ }\r
+\r
+ return equation;\r
}\r
- \r
+\r
private static Variable getVariable(Configuration configuration, String name) {\r
for(IElement element : configuration.getElements()) {\r
if(element instanceof Variable) {\r
import org.simantics.sysdyn.expressionParser.Token;\r
import org.simantics.sysdyn.representation.Configuration;\r
import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.Model;\r
+import org.simantics.sysdyn.representation.ModuleType;\r
import org.simantics.sysdyn.representation.Sheet;\r
import org.simantics.sysdyn.representation.Variable;\r
\r
for(String key : functionCalls.keySet()) {\r
String[] parts = key.split("\\.");\r
Object current = v.getParentConfiguration();\r
+ \r
+ // Hack. Sheets can currently exist only in models, not in module types.\r
+ ModuleType moduleType= ((Configuration)current).getModuleType();\r
+ if(moduleType != null) {\r
+ if(moduleType.getParent() != null && moduleType.getParent() instanceof Model)\r
+ current = ((Model)moduleType.getParent()).getModelConfiguration();\r
+ }\r
+ // end Hack.\r
+ \r
Object found = null;\r
for(int i = 0; i < parts.length && current != null; i++) {\r
found = null;\r
String tmp = "";\r
int start = 0, end = 0, call = 0;\r
String cellOrRange = null;\r
- while((call = expression.indexOf(key, end)) >= 0) {\r
+ while((call = expression.indexOf(key + "(", end)) >= 0) {\r
start = expression.indexOf("(", call);\r
\r
tmp += expression.substring(end, start);\r
tmp += "." + cellOrRange;\r
}\r
tmp += expression.substring(end, expression.length());\r
- return tmp;\r
+ expression = tmp;\r
}\r
}\r
\r
IModelicaMonitor monitor;\r
\r
public SimulationJob(SysdynModel model, Experiment experiment) {\r
- super("Simulate " + model.getConfiguration().getName());\r
+ super("Simulate " + model.getConfiguration().getLabel());\r
this.model = model;\r
this.experiment = experiment;\r
if(PlatformUI.isWorkbenchRunning()) {\r
\r
@Override\r
protected IStatus run(IProgressMonitor monitor) {\r
- monitor.beginTask("Simulate " + model.getConfiguration().getName(), 5); \r
- this.monitor.message("Simulate " + model.getConfiguration().getName());\r
+ monitor.beginTask("Simulate " + model.getConfiguration().getLabel(), 5); \r
+ this.monitor.message("Simulate " + model.getConfiguration().getLabel());\r
try {\r
model.update();\r
if(experiment instanceof SysdynExperiment)\r