From: villberg Date: Mon, 19 May 2014 06:29:16 +0000 (+0000) Subject: refs #4856 X-Git-Tag: 1.8.1~58 X-Git-Url: https://gerrit.simantics.org/r/gitweb?a=commitdiff_plain;h=6d647134c2737dfe94c5595443fe3f7716cffd72;p=simantics%2Fsysdyn.git refs #4856 git-svn-id: https://www.simantics.org/svn/simantics/sysdyn/trunk@29507 ac1ea38d-2e2b-0410-8846-a27921b304fc --- diff --git a/org.simantics.sysdyn.ui/META-INF/MANIFEST.MF b/org.simantics.sysdyn.ui/META-INF/MANIFEST.MF index 31b9e04a..790eeb2d 100644 --- a/org.simantics.sysdyn.ui/META-INF/MANIFEST.MF +++ b/org.simantics.sysdyn.ui/META-INF/MANIFEST.MF @@ -59,7 +59,8 @@ Require-Bundle: org.simantics.layer0.utils;bundle-version="0.6.2", org.simantics.db.indexing;bundle-version="1.1.0", org.simantics.workbench, org.simantics.annotation.ui;bundle-version="1.0.0", - org.simantics.annotation.ontology;bundle-version="1.0.0" + org.simantics.annotation.ontology;bundle-version="1.0.0", + org.simantics.spreadsheet.common;bundle-version="1.1.0" Bundle-Activator: org.simantics.sysdyn.ui.Activator Bundle-ActivationPolicy: lazy Export-Package: org.simantics.sysdyn.ui.browser.nodes diff --git a/org.simantics.sysdyn.ui/icons/box.png b/org.simantics.sysdyn.ui/icons/box.png new file mode 100644 index 00000000..8443c23e Binary files /dev/null and b/org.simantics.sysdyn.ui/icons/box.png differ diff --git a/org.simantics.sysdyn.ui/plugin.xml b/org.simantics.sysdyn.ui/plugin.xml index 1c55f8fb..b16564db 100644 --- a/org.simantics.sysdyn.ui/plugin.xml +++ b/org.simantics.sysdyn.ui/plugin.xml @@ -470,7 +470,25 @@ ifEmpty="false" operator="or"> + value="org.simantics.sysdyn.ui.gameExperiment"> + + + + + + + + + + @@ -863,16 +881,23 @@ checkEnabled="true"> + + + + @@ -1274,7 +1299,7 @@ label="Export"> @@ -1284,7 +1309,7 @@ variable="selection"> @@ -1704,6 +1729,11 @@ id="org.simantics.sysdyn.ui.saveIC" name="Save Initial Condition"> + + - - + + + + @@ -2438,7 +2472,7 @@ variable="selection"> @@ -2561,11 +2595,11 @@ preference="2.0"> else if (node instanceof ModuleTypeNode || node instanceof ModuleNode || node instanceof ConfigurationNode) image = "icons/bricks.png"; else if (node instanceof SCLModule) - image = "icons/bullet_gray.png"; + image = "icons/box.png"; else if (node instanceof InitialCondition) image = "icons/table.png"; else if (node instanceof ExperimentNode) { diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution.java index 3ec613f8..19d9ce12 100644 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution.java +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution.java @@ -33,9 +33,10 @@ public class AnnotationContribution extends ViewpointContributor> result = new ArrayList>(); + Layer0 L0 = Layer0.getInstance(graph); + if(node instanceof ISpecialFolder) return result; - Layer0 L0 = Layer0.getInstance(graph); AnnotationResource ANNO = AnnotationResource.getInstance(graph); if(graph.isInstanceOf(node.data, L0.Library)) { for(Resource anno : graph.syncRequest(new ObjectsWithType(node.data, L0.ConsistsOf, ANNO.AnnotationType))) { diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntology.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution2.java similarity index 53% rename from org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntology.java rename to org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution2.java index 9645b361..a29c1dab 100644 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntology.java +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution2.java @@ -14,21 +14,38 @@ package org.simantics.sysdyn.ui.browser.contributions; import java.util.ArrayList; import java.util.Collection; +import org.simantics.annotation.ontology.AnnotationResource; 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.exception.DatabaseException; -import org.simantics.sysdyn.ui.browser.nodes.SCLModulesFolder; +import org.simantics.layer0.Layer0; +import org.simantics.sysdyn.ui.browser.nodes.AnnotationType; +import org.simantics.sysdyn.ui.browser.nodes.AnnotationValue; -public class SharedOntology extends ViewpointContributor { +public class AnnotationContribution2 extends ViewpointContributor { @Override - public Collection getContribution(ReadGraph graph, SharedOntologyNode model) - throws DatabaseException { + public Collection getContribution(ReadGraph graph, Resource res) throws DatabaseException { + ArrayList> result = new ArrayList>(); - result.add(new SCLModulesFolder(model.data)); + + Layer0 L0 = Layer0.getInstance(graph); + + AnnotationResource ANNO = AnnotationResource.getInstance(graph); + if(graph.isInstanceOf(res, L0.Library)) { + for(Resource anno : graph.syncRequest(new ObjectsWithType(res, L0.ConsistsOf, ANNO.AnnotationType))) { + result.add(new AnnotationType(anno)); + } + } + for(Resource anno : graph.syncRequest(new ObjectsWithType(res, L0.ConsistsOf, ANNO.Annotation))) { + result.add(new AnnotationValue(anno)); + } + return result; + } @Override diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryContribution.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryContribution.java index e35d00f0..879cb666 100644 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryContribution.java +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryContribution.java @@ -34,7 +34,7 @@ public class LibraryContribution extends ViewpointContributor { diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyImager.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyImager.java index 44155c2c..5c51a8f6 100644 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyImager.java +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyImager.java @@ -7,6 +7,7 @@ import org.eclipse.jface.resource.ImageDescriptor; import org.simantics.browsing.ui.swt.ImagerContributor; import org.simantics.db.ReadGraph; import org.simantics.db.exception.DatabaseException; +import org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode; public class SharedOntologyImager extends ImagerContributor { diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyLabeler.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyLabeler.java index 1868c6fa..9ebfc579 100644 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyLabeler.java +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyLabeler.java @@ -2,13 +2,15 @@ package org.simantics.sysdyn.ui.browser.contributions; import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor; import org.simantics.db.ReadGraph; +import org.simantics.db.common.utils.Versions; import org.simantics.db.exception.DatabaseException; +import org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode; public class SharedOntologyLabeler extends LabelerContributor { @Override public String getLabel(ReadGraph graph, SharedOntologyNode node) throws DatabaseException { - return graph.getURI(node.data); + return Versions.getStandardNameString(graph, node.data); } @Override diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyNode.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyNode.java deleted file mode 100644 index 2013ec2a..00000000 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyNode.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.simantics.sysdyn.ui.browser.contributions; - -import org.simantics.browsing.ui.common.node.AbstractNode; -import org.simantics.browsing.ui.common.node.DeleteException; -import org.simantics.browsing.ui.common.node.IDeletableNode; -import org.simantics.browsing.ui.common.node.IModifiableNode; -import org.simantics.browsing.ui.content.Labeler.Modifier; -import org.simantics.db.Resource; - -public class SharedOntologyNode extends AbstractNode implements IDeletableNode, IModifiableNode { - - public SharedOntologyNode(Resource data) { - super(data); - } - - @Override - public void delete() throws DeleteException { - } - - @Override - public Modifier getModifier(String columnId) { - return null; - } - -} diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModule.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModule.java index c695ca63..70815ee4 100644 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModule.java +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModule.java @@ -46,7 +46,6 @@ public class SCLModule extends AbstractNode implements IDeletableNode, } catch (DatabaseException e) { ExceptionUtils.logAndShowError(e); } - } @Override diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedOntologyNode.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedOntologyNode.java new file mode 100644 index 00000000..6e6d5951 --- /dev/null +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedOntologyNode.java @@ -0,0 +1,42 @@ +package org.simantics.sysdyn.ui.browser.nodes; + +import org.simantics.browsing.ui.common.node.AbstractNode; +import org.simantics.browsing.ui.common.node.DeleteException; +import org.simantics.browsing.ui.common.node.IDeletableNode; +import org.simantics.browsing.ui.common.node.IModifiableNode; +import org.simantics.browsing.ui.content.Labeler.Modifier; +import org.simantics.db.Resource; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.exception.CancelTransactionException; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.util.RemoverUtil; +import org.simantics.ui.SimanticsUI; +import org.simantics.utils.ui.ExceptionUtils; + +public class SharedOntologyNode extends AbstractNode implements IDeletableNode, IModifiableNode { + + public SharedOntologyNode(Resource data) { + super(data); + } + + @Override + public void delete() throws DeleteException { + try { + SimanticsUI.getSession().syncRequest(new WriteRequest() { + @Override + public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException { + RemoverUtil.remove(graph, data); + } + }); + } catch (DatabaseException e) { + ExceptionUtils.logAndShowError(e); + } + } + + @Override + public Modifier getModifier(String columnId) { + return null; + } + +} diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ExportSharedOntologyHandler.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ExportSharedOntologyHandler.java index b322db1e..9d2f6703 100644 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ExportSharedOntologyHandler.java +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ExportSharedOntologyHandler.java @@ -6,7 +6,7 @@ import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.handlers.HandlerUtil; import org.simantics.modeling.ModelingUtils; -import org.simantics.sysdyn.ui.browser.contributions.SharedOntologyNode; +import org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode; import org.simantics.utils.ui.AdaptionUtils; public class ExportSharedOntologyHandler extends AbstractHandler { diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationTypeHandler.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationTypeHandler.java index 133962ee..ee052f8b 100644 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationTypeHandler.java +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationTypeHandler.java @@ -25,11 +25,15 @@ public class NewAnnotationTypeHandler extends AbstractHandler { ISelection sel = HandlerUtil.getCurrentSelection(event); @SuppressWarnings("unchecked") - AbstractNode node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class); - if (node == null) - return null; + Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class); + if(res == null) { + AbstractNode node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class); + if (node == null) + return null; + res = node.data; + } - final Resource parent = node.data; + final Resource parent = res; SimanticsUI.getSession().asyncRequest(new WriteRequest() { diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationValueHandler.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationValueHandler.java index 2f679c1c..29ad88db 100644 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationValueHandler.java +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationValueHandler.java @@ -21,11 +21,15 @@ public class NewAnnotationValueHandler extends AbstractHandler { ISelection sel = HandlerUtil.getCurrentSelection(event); @SuppressWarnings("unchecked") - AbstractNode node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class); - if (node == null) - return null; + Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class); + if(res == null) { + AbstractNode node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class); + if (node == null) + return null; + res = node.data; + } - final Resource parent = node.data; + final Resource parent = res; try { Resource model = Simantics.getSession().syncRequest(new PossibleIndexRoot(parent)); if(model == null) return null; diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewLibraryHandler.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewLibraryHandler.java index ae1b2933..009d225c 100644 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewLibraryHandler.java +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewLibraryHandler.java @@ -22,11 +22,15 @@ public class NewLibraryHandler extends AbstractHandler { ISelection sel = HandlerUtil.getCurrentSelection(event); @SuppressWarnings("unchecked") - AbstractNode node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class); - if (node == null) - return null; + Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class); + if(res == null) { + AbstractNode node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class); + if (node == null) + return null; + res = node.data; + } - final Resource parent = node.data; + final Resource parent = res; SimanticsUI.getSession().asyncRequest(new WriteRequest() { diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryDialog.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryDialog.java new file mode 100644 index 00000000..08882f88 --- /dev/null +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryDialog.java @@ -0,0 +1,149 @@ +/******************************************************************************* + * Copyright (c) 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum Oy - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.ui.handlers; + +import java.util.Map; + +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.jface.layout.GridDataFactory; +import org.eclipse.jface.layout.GridLayoutFactory; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.PlatformUI; +import org.simantics.annotation.ui.Activator; +import org.simantics.modelica.data.DataSet; +import org.simantics.spreadsheet.util.SpreadsheetUtils; +import org.simantics.ui.workbench.dialogs.ResourceSelectionDialog3; +import org.simantics.utils.datastructures.Pair; + +public class SaveHistoryDialog extends ResourceSelectionDialog3 { + + private String sheetName; + private String sheetLocation; + + public SaveHistoryDialog(Shell shell, + Map> parameter, String title) { + super(shell, parameter, title); + this.sheetName = ""; + this.sheetLocation = ""; + } + + @Override + protected IDialogSettings getBaseDialogSettings() { + return Activator.getDefault().getDialogSettings(); + } + + @Override + protected void setSelectionResult(Object[] newResult) { + super.setSelectionResult(newResult); + validatePage(); + } + + @Override + protected Control createExtendedContentArea(Composite parent_) { + + Composite parent = new Composite(parent_, SWT.NONE); + GridLayoutFactory.swtDefaults().numColumns(2).applyTo(parent); + GridDataFactory.fillDefaults().grab(true, false).applyTo(parent); + + Label l = new Label(parent, SWT.NONE); + l.setText("Select a sheet:"); + GridDataFactory.fillDefaults().grab(false, false).applyTo(l); + final Text t = new Text(parent,SWT.BORDER); + t.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + sheetName = t.getText(); + validatePage(); + } + }); + GridDataFactory.fillDefaults().grab(true, false).applyTo(t); + Label l2 = new Label(parent, SWT.NONE); + l2.setText("Select cell in sheet:"); + GridDataFactory.fillDefaults().grab(false, false).applyTo(l2); + final Text t2 = new Text(parent,SWT.BORDER); + t2.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + sheetLocation = t2.getText(); + validatePage(); + } + }); + GridDataFactory.fillDefaults().grab(true, false).applyTo(t2); + validatePage(); + return super.createExtendedContentArea(parent); + } + + @Override + protected void handleSelected(StructuredSelection selection) { + super.handleSelected(selection); + validatePage(); + } + + protected void validatePage() { + + if(getSelectedItems().size() == 0) { + updateStatus(new Status(Status.ERROR, PlatformUI.PLUGIN_ID, "Please select some variable(s)")); + return; + } + + String error = validateSheet(sheetName); + if (error != null) { + updateStatus(new Status(Status.ERROR, PlatformUI.PLUGIN_ID, error)); + return; + } + + error = validateLocation(sheetLocation); + if (error != null) { + updateStatus(new Status(Status.ERROR, PlatformUI.PLUGIN_ID, error)); + return; + } + + updateStatus(new Status(Status.OK, Activator.PLUGIN_ID, "")); + + } + + protected String validateSheet(String name) { + if (name.trim().isEmpty()) + return "Sheet name cannot be empty"; + return null; + } + + protected String validateLocation(String location) { + try { + if(location.isEmpty()) + return "Empty location"; + SpreadsheetUtils.decodeCellAbsolute(location); + return null; + } catch (Exception e) { + return e.getMessage(); + } + } + + public String getSheetName() { + return sheetName; + } + + public String getSheetLocation() { + return sheetLocation; + } + +} \ No newline at end of file diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryHandler.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryHandler.java new file mode 100644 index 00000000..054beef5 --- /dev/null +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryHandler.java @@ -0,0 +1,142 @@ +/******************************************************************************* + * Copyright (c) 2010 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.ui.handlers; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.PlatformUI; +import org.simantics.Simantics; +import org.simantics.databoard.Bindings; +import org.simantics.databoard.binding.mutable.Variant; +import org.simantics.db.Resource; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.request.PossibleModel; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.db.layer0.variable.Variables; +import org.simantics.layer0.Layer0; +import org.simantics.modelica.data.DataSet; +import org.simantics.modelica.data.SimulationResult; +import org.simantics.modeling.ModelingUtils; +import org.simantics.simulation.experiment.IExperiment; +import org.simantics.simulation.project.IExperimentManager; +import org.simantics.spreadsheet.Range; +import org.simantics.spreadsheet.resource.SpreadsheetResource; +import org.simantics.spreadsheet.util.SpreadsheetUtils; +import org.simantics.sysdyn.manager.MemoryResult; +import org.simantics.sysdyn.manager.SysdynGameExperimentBase; +import org.simantics.sysdyn.manager.SysdynResult; +import org.simantics.sysdyn.ui.utils.HandlerUtils; +import org.simantics.ui.SimanticsUI; +import org.simantics.utils.datastructures.Pair; + +public class SaveHistoryHandler extends AbstractHandler { + + @Override + public Object execute(ExecutionEvent event) throws ExecutionException { + HandlerUtils.saveBeforeExperimentRun(event); + + IExperimentManager manager = + SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); + IExperiment experiment = manager.getActiveExperiment(); + if(experiment instanceof SysdynGameExperimentBase) { + final SysdynGameExperimentBase exp = (SysdynGameExperimentBase)experiment; + try { + + Map> map = new HashMap>(); + + SysdynResult r = exp.getCurrentResult(); + if(r instanceof MemoryResult) { + MemoryResult gr = (MemoryResult)r; + SimulationResult sr = gr.getSimulationResult(); + for(DataSet ds : sr.getVariableDataSets()) { + map.put(ds, new Pair(ds.name, null)); + } + } + + Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); + SaveHistoryDialog dialog = new SaveHistoryDialog(shell, map, "Select variables"); + if (dialog.open() == Window.OK) { + final Object[] result = dialog.getResult(); + final String sheetName = dialog.getSheetName(); + final String sheetLocation = dialog.getSheetLocation(); + Simantics.getSession().syncRequest(new WriteRequest() { + + public void writeCell(WriteGraph graph, Variable sheet, String cellName, String value) throws DatabaseException { + SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph); + Variable child = sheet.getPossibleChild(graph, cellName); + if(child != null) { + child.setPropertyValue(graph, SHEET.Cell_content, Variant.ofInstance(value), Bindings.VARIANT); + } else { + Layer0 L0 = Layer0.getInstance(graph); + Resource container = sheet.getRepresents(graph); + Resource cell = graph.newResource(); + graph.claim(cell, L0.InstanceOf, null, SHEET.TextCell); + graph.addLiteral(cell, L0.HasName, L0.NameOf, L0.String, cellName, Bindings.STRING); + graph.addLiteral(cell, SHEET.Cell_content, SHEET.Cell_content_Inverse, L0.Variant, Variant.ofInstance(value), Bindings.VARIANT); + graph.claim(cell, L0.PartOf, container); + } + } + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + + SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph); + Resource modelResource = graph.syncRequest(new PossibleModel(exp.getResource())); + if(modelResource == null) return; + List sheets = ModelingUtils.searchByTypeAndName(graph, modelResource, SHEET.Spreadsheet, sheetName); + if(sheets.size() != 1) return; + Variable sheet = Variables.getVariable(graph, sheets.get(0)); + + Range base = SpreadsheetUtils.decodeCellAbsolute(sheetLocation); + + DataSet first = (DataSet)result[0]; + writeCell(graph, sheet, sheetLocation, "times"); + for(int i=0;i data) { IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); IExperiment experiment = manager.getActiveExperiment(); - if(experiment == null || !(experiment instanceof SysdynGameExperiment)) { + if(experiment == null || !(experiment instanceof SysdynGameExperimentBase)) { super.readData(expression, data); } else { Double value; - ExperimentState state = ((SysdynGameExperiment)experiment).getSysdynExperimentState(); + ExperimentState state = ((SysdynGameExperimentBase)experiment).getSysdynExperimentState(); if(ExperimentState.RUNNING.equals(state) || ExperimentState.STOPPED.equals(state)) { try { value = SimanticsUI.getSession().syncRequest(new Read() { @@ -114,7 +114,7 @@ public class ParameterExpression extends BasicExpression { IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); IExperiment experiment = manager.getActiveExperiment(); - if(experiment != null && experiment instanceof SysdynGameExperiment) { + if(experiment != null && experiment instanceof SysdynGameExperimentBase) { final String currentText = this.expression.getExpression(); final String oldEquation = (String)data.get("equation"); if(oldEquation == null || @@ -122,7 +122,7 @@ public class ParameterExpression extends BasicExpression { if(ExpressionUtils.isParameter(currentText)) { Boolean savedIntoFMU = false; - ExperimentState state = ((SysdynGameExperiment)experiment).getSysdynExperimentState(); + ExperimentState state = ((SysdynGameExperimentBase)experiment).getSysdynExperimentState(); // Set value to control only if the simulation is running or stopped, not before initialization if(ExperimentState.RUNNING.equals(state) || ExperimentState.STOPPED.equals(state)) { try { diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimeIndexVariable.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimeIndexVariable.java index 65c34770..9a44eacf 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimeIndexVariable.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimeIndexVariable.java @@ -4,7 +4,7 @@ import org.simantics.db.ReadGraph; import org.simantics.db.WriteGraph; import org.simantics.db.exception.DatabaseException; import org.simantics.db.layer0.variable.Variable; -import org.simantics.sysdyn.manager.SysdynGameExperiment; +import org.simantics.sysdyn.manager.SysdynGameExperimentBase; import org.simantics.sysdyn.manager.SysdynPlaybackExperiment; public class TimeIndexVariable extends IndexVariable { @@ -18,8 +18,8 @@ public class TimeIndexVariable extends IndexVariable { public Double getValue() { if(experiment != null && experiment instanceof SysdynPlaybackExperiment) return ((SysdynPlaybackExperiment)experiment).getTime(); - if(experiment != null && experiment instanceof SysdynGameExperiment) - return ((SysdynGameExperiment)experiment).getTime(); + if(experiment != null && experiment instanceof SysdynGameExperimentBase) + return ((SysdynGameExperimentBase)experiment).getSolver().getTime(); return null; } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableBase.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableBase.java index 83bfbba8..567b1874 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableBase.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableBase.java @@ -6,16 +6,16 @@ import java.util.Collection; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; +import org.simantics.db.common.utils.Logger; import org.simantics.db.common.utils.NameUtils; import org.simantics.db.exception.DatabaseException; import org.simantics.db.layer0.variable.Variable; -import org.simantics.fmu.FMUControlJNI; -import org.simantics.fmu.FMUJNIException; import org.simantics.simulation.experiment.ExperimentState; import org.simantics.sysdyn.SysdynResource; import org.simantics.sysdyn.manager.SysdynDataSet; -import org.simantics.sysdyn.manager.SysdynGameExperiment; +import org.simantics.sysdyn.manager.SysdynGameExperimentBase; import org.simantics.sysdyn.manager.SysdynResult; +import org.simantics.sysdyn.solver.ISolver; abstract public class ValueIndexVariableBase extends IndexVariable { @@ -36,8 +36,8 @@ abstract public class ValueIndexVariableBase extends IndexVariable { double[] result = new double[variableNames.size()]; for(int i = 0; i < variableNames.size(); i++) { for(SysdynResult r : results) { - if(experiment instanceof SysdynGameExperiment) { - Double d = ((SysdynGameExperiment)experiment).getCurrentValue(variableNames.get(i)); + if(experiment instanceof SysdynGameExperimentBase) { + Double d = ((SysdynGameExperimentBase)experiment).getCurrentValue(variableNames.get(i)); result[i] = d != null ? d : 0; } else { SysdynDataSet ds = r.getDataSet(variableNames.get(i)); @@ -63,30 +63,32 @@ abstract public class ValueIndexVariableBase extends IndexVariable { double[] values = (double[]) value; - FMUControlJNI control = null; - if(experiment instanceof SysdynGameExperiment) { // Support only game experiments for now.. +// FMUControlJNI control = null; + if(experiment instanceof SysdynGameExperimentBase) { // Support only game experiments for now.. - SysdynGameExperiment exp = (SysdynGameExperiment)experiment; + SysdynGameExperimentBase exp = (SysdynGameExperimentBase)experiment; ExperimentState state = exp.getSysdynExperimentState(); // Set value to control only if the simulation is running or stopped, not before initialization if(!(ExperimentState.RUNNING.equals(state) || ExperimentState.STOPPED.equals(state))) return; - control = ((SysdynGameExperiment)this.experiment).getFMUControl(); - if(control == null) - return; +// control = ((SysdynGameExperimentBase)this.experiment).getFMUControl(); +// if(control == null) +// return; + ISolver solver = exp.getSolver(); + + try { + ArrayList variableNames = getVariableNamesWithIndexNumbers(); + for(int i = 0; i < variableNames.size() && i < values.length; i++) { + + if(values[i] == Double.NaN) + continue; - ArrayList variableNames = getVariableNamesWithIndexNumbers(); - for(int i = 0; i < variableNames.size() && i < values.length; i++) { - if(values[i] == Double.NaN) - continue; - - try { String name = variableNames.get(i); - control.setRealValue(name, values[i]); - + solver.setRealValue(name, values[i]); + // Set value for all referred variables in modules SysdynResource sr = SysdynResource.getInstance(graph); for(Resource dependency : graph.getObjects(resource, sr.Variable_isTailOf)) { @@ -97,13 +99,19 @@ abstract public class ValueIndexVariableBase extends IndexVariable { if(name.indexOf(".") > 0) module = name.substring(0, name.lastIndexOf(".") + 1); String refName = module + NameUtils.getSafeName(graph, head) + "." + NameUtils.getSafeName(graph, ref); - control.setRealValue(refName, values[i]); + solver.setRealValue(refName, values[i]); } } - } catch (FMUJNIException e) { + } + exp.updateSubscriptions(); + + } catch (Exception e) { + + Logger.defaultLogError(e); + } - exp.updateSubscriptions(); + } } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValuesIndexVariable.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValuesIndexVariable.java index 17f31520..d0eb2032 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValuesIndexVariable.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValuesIndexVariable.java @@ -8,7 +8,7 @@ import org.simantics.db.WriteGraph; import org.simantics.db.exception.DatabaseException; import org.simantics.db.layer0.variable.Variable; import org.simantics.sysdyn.manager.SysdynDataSet; -import org.simantics.sysdyn.manager.SysdynGameExperiment; +import org.simantics.sysdyn.manager.SysdynGameExperimentBase; import org.simantics.sysdyn.manager.SysdynResult; public class ValuesIndexVariable extends IndexVariable { @@ -39,8 +39,8 @@ public class ValuesIndexVariable extends IndexVariable { * get the last value from experiment. It might be different from the result * file, if it has been modified in current time step */ - if(experiment instanceof SysdynGameExperiment && ds.result == null) { - double d = ((SysdynGameExperiment)experiment).getCurrentValue(variableNames.get(i)); + if(experiment instanceof SysdynGameExperimentBase && ds.result == null) { + double d = ((SysdynGameExperimentBase)experiment).getCurrentValue(variableNames.get(i)); result[i][ds.values.length - 1] = d; } break; // Show the first result found. (i.e. do not show history datasets) diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/GameResult.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/GameResult.java new file mode 100644 index 00000000..dc08d760 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/GameResult.java @@ -0,0 +1,45 @@ +package org.simantics.sysdyn.manager; + +import java.util.ArrayList; +import java.util.HashMap; + +import org.simantics.modelica.data.DataSet; +import org.simantics.modelica.data.SimulationResult; + +/** + * Game results + * @author Teemu Lempinen + * + */ +public class GameResult extends SimulationResult { + + private final SysdynGameExperimentBase base; + + public GameResult(SysdynGameExperimentBase sysdynGameExperiment, HashMap> results, String[] subscription) { + + base = sysdynGameExperiment; + // Get times + ArrayList timeList = results.get("time"); + double[] times = new double[timeList.size()]; + for(int i = 0; i < timeList.size(); i++) { + times[i] = timeList.get(i); + } + + String name; + double[] values; + ArrayList valueList; + for(int k = 0; k < subscription.length; k++) { + name = subscription[k]; + values = new double[timeList.size()]; + valueList = results.get(name); + if(valueList.size() == timeList.size()) { + for(int i = 0; i < valueList.size(); i++) { + values[i] = valueList.get(i); + } + this.variables.add(new DataSet(name, times, values)); + } else { + System.err.println("wrong amount of values " + name); + } + } + } +} \ No newline at end of file diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/MemoryResult.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/MemoryResult.java index ded4dd63..f6ef5bb5 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/MemoryResult.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/MemoryResult.java @@ -108,7 +108,7 @@ public class MemoryResult extends SysdynResult { addAllInitialValues(result); // For legacy reasons } - private SimulationResult getSimulationResult() { + public SimulationResult getSimulationResult() { return this.simulationResult; } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java index 1338ecd5..326e8cbe 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java @@ -36,6 +36,7 @@ import org.simantics.db.VirtualGraph; import org.simantics.db.WriteGraph; import org.simantics.db.common.request.ReadRequest; import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.utils.Logger; import org.simantics.db.common.utils.NameUtils; import org.simantics.db.exception.DatabaseException; import org.simantics.db.service.VirtualGraphSupport; @@ -125,15 +126,19 @@ public class OldSysdynExperiment extends SysdynExperiment { for(IExperimentListener listener : listeners.getListeners()) listener.stateChanged(state); - session.asyncRequest(new ReadRequest() { - - @Override - public void run(ReadGraph graph) throws DatabaseException { - final Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration); - sysdynModel = SysdynModelManager.getInstance(session).getModel(graph, configuration); - toggleActivation(graph, true); - } - }); + try { + g.syncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + final Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration); + sysdynModel = SysdynModelManager.getInstance(session).getModel(graph, configuration); + toggleActivation(graph, true); + } + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } setSysdynExperimentState(ExperimentState.INITIALIZING); } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SimulateDurationJob.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SimulateDurationJob.java new file mode 100644 index 00000000..6f03e6e8 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SimulateDurationJob.java @@ -0,0 +1,96 @@ +package org.simantics.sysdyn.manager; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.simantics.simulation.experiment.ExperimentState; +import org.simantics.sysdyn.solver.ISolver; + +class SimulateDurationJob extends Job { + + private boolean canceled = false; + private double duration; + private final SysdynGameExperimentBase base; + private final ISolver solver; + + public SimulateDurationJob(SysdynGameExperimentBase base, String name, double duration) { + super(name); + this.base = base; + this.solver = base.getSolver(); + this.duration = duration; + } + + @Override + protected void canceling() { + canceled = true; + } + + @Override + protected IStatus run(IProgressMonitor monitor) { + if(base == null || base.getState() != ExperimentState.STOPPED) + return Status.OK_STATUS; + + base.changeState(ExperimentState.RUNNING); + int nSteps = (int)(duration / base.stepLength); + int work = 1 + nSteps * 3 + 2; // initialization + number of steps * number of phases per step + set result + call result listeners + + monitor.beginTask("Simulating " + duration + " time steps", work); + monitor.subTask("Initialize step simulation"); + + if(base.subscription == null || base.results == null) + return Status.OK_STATUS; + + if(duration <= 0.0) + duration = base.stepDuration; + + + try { + + solver.prepareToStep(); + + double time = solver.getTime(); + double eTime = time + duration; + + monitor.worked(1); + + base.setSubscribedResults(monitor, time); + + int stepNumber = 1; + while(time < eTime && !canceled) { + + if(eTime - time < base.stepLength) + solver.setStepLength(eTime - time); + + monitor.subTask("Simulate step (time = " + time + ")"); + solver.simulateStep(); + monitor.worked(1); + + time = solver.getTime(); + + if(stepNumber % base.savePer == 0) { + base.setSubscribedResults(monitor, time); + } else { + monitor.worked(1); + } + stepNumber++; + monitor.worked(1); + + } + + monitor.subTask("Display results"); + ((MemoryResult)base.getCurrentResult()).setResult(new GameResult(base, base.results, base.subscription)); + monitor.worked(1); + + base.resultsChanged(true); + monitor.worked(1); + base.changeState(ExperimentState.STOPPED); + + } catch (Exception e) { + e.printStackTrace(); + System.err.println("SysdynGameExperiment simulateDuration failed: \n\t" + e.getMessage()); + } + return Status.OK_STATUS; + + } +} \ No newline at end of file diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java index ced8ad76..bf07d3d0 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java @@ -21,9 +21,7 @@ import java.util.ArrayList; import java.util.HashMap; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.core.runtime.NullProgressMonitor; import org.simantics.databoard.Bindings; import org.simantics.db.AsyncReadGraph; import org.simantics.db.ReadGraph; @@ -31,6 +29,7 @@ import org.simantics.db.Resource; import org.simantics.db.Session; import org.simantics.db.WriteGraph; import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.utils.Logger; import org.simantics.db.exception.DatabaseException; import org.simantics.db.layer0.util.Layer0Utils; import org.simantics.db.layer0.util.Simantics; @@ -43,11 +42,12 @@ import org.simantics.fmu.FMUJNIException; import org.simantics.modelica.IModelicaMonitor; import org.simantics.modelica.ModelicaManager; import org.simantics.modelica.SimulationLocation; -import org.simantics.modelica.data.DataSet; -import org.simantics.modelica.data.SimulationResult; import org.simantics.modeling.PartialIC; import org.simantics.simulation.experiment.ExperimentState; import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.simulation.SimulationJob.HeadlessModelicaMonitor; +import org.simantics.sysdyn.solver.ISolver; +import org.simantics.sysdyn.solver.ModelicaSolver; import org.simantics.utils.datastructures.Quad; /** @@ -55,69 +55,23 @@ import org.simantics.utils.datastructures.Quad; * @author Teemu Lempinen * */ -public class SysdynGameExperiment extends OldSysdynExperiment { - - private FMUControlJNI control; - private String[] subscription; - private HashMap subscriptionIndexes; - private HashMap> results; - private double stepLength = DEFAULT_STEP_LENGTH; - private double startTime = DEFAULT_START_TIME; - private double stepDuration = DEFAULT_STEP_DURATION; - private int savePer = 1; - private static boolean fortranLibrariesLoaded = false; +public class SysdynGameExperiment extends SysdynGameExperimentBase { + + private ModelicaSolver solver; + public FMUControlJNI control; + private boolean loaded = false; - public static double DEFAULT_STEP_DURATION = 1.0; - public static double DEFAULT_STEP_LENGTH = 0.1; - public static double DEFAULT_START_TIME = 0.0; - public static int DEFAULT_OUTPUT_INTERVAL = 1; + private static boolean fortranLibrariesLoaded = false; - double[] currentValues; // Current values from FMU. Updated with updateSubscriptions - public SysdynGameExperiment(Resource experiment, Resource model) { super(experiment, model); + this.solver = new ModelicaSolver(this); } - - public double getStepDuration() { - return stepDuration; - } - - public void setStepDuration(double duration) { - this.stepDuration = duration; - } - - public double getStepLength() { - return stepLength; - } - - public void setStepLength(double stepLength) { - this.stepLength = stepLength; - } - - public void setStartTime(double startTime) { - this.startTime = startTime; - } - - public void setOutputInterval(int interval) { - this.savePer = interval; - } - public FMUControlJNI getFMUControl() { return control; } - public double getTime() { - if(control != null) { - try { - return control.getTime(); - } catch (FMUJNIException e) { - } - } - return 0.0; - } - - @Override public void init(ReadGraph g) { super.init(g); @@ -178,6 +132,7 @@ public class SysdynGameExperiment extends OldSysdynExperiment { if(control!=null) { try { control.unloadFMU(); + loaded = false; } catch (FMUJNIException e) { e.printStackTrace(); } @@ -268,6 +223,7 @@ public class SysdynGameExperiment extends OldSysdynExperiment { } control.loadFMUFile(simulationLocation.executableFile.getAbsolutePath()); // unzip and load fmu + loaded = true; instantiate(); } catch (FMUJNIException e) { @@ -368,178 +324,18 @@ public class SysdynGameExperiment extends OldSysdynExperiment { @Override - public void simulateDuration(double duration) { - Job job = new simulateDurationJob("Simulate steps", this, duration); - // Start the Job - job.schedule(); - } - - private double lastResultTime = Double.NaN; - - public void setSubscribedResults(IProgressMonitor monitor, double time) throws FMUJNIException { - -// System.err.println("setSubscribedResults " + time); - - monitor.subTask("Get results (time = " + time + ")"); - currentValues = control.getSubscribedResults(currentValues); - monitor.worked(1); - - monitor.subTask("Save results (time = " + time + ")"); - for(int k = 0; k < subscription.length; k++) { - setResults(time, subscription[k], currentValues[k]); - } - - lastResultTime = time; - - } - - public void setResults(double time, String key, Double value) { - ArrayList list = results.get(key); - if(list == null) { - list = new ArrayList(); - results.put(key, list); - } - if(time == lastResultTime) { - list.set(list.size()-1, value); - } else { - list.add(value); - } -// System.err.println("setResults " + time + " " + key + " = " + list); - } - - public void clearResults() { - lastResultTime = Double.NaN; - results.clear(); - } - - private class simulateDurationJob extends Job { - - private boolean canceled = false; - private double duration; - private final SysdynGameExperiment experiment; - public simulateDurationJob(String name, SysdynGameExperiment experiment, double duration) { - super(name); - this.duration = duration; - this.experiment = experiment; - } - - @Override - protected void canceling() { - canceled = true; - } - - @Override - protected IStatus run(IProgressMonitor monitor) { - if(experiment == null || experiment.getState() != ExperimentState.STOPPED) - return Status.OK_STATUS; - - changeState(ExperimentState.RUNNING); - 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 - - monitor.beginTask("Simulating " + duration + " time steps", work); - monitor.subTask("Initialize step simulation"); - - if(subscription == null || SysdynGameExperiment.this.results == null || control == null) - return Status.OK_STATUS; - - if(duration <= 0.0) - duration = stepDuration; - - - try { - - // initialize if not initialized - if(!control.isInitialized()) { - control.setTime(startTime); - control.initializeSimulation(); - clearResults(); -// getInitialResultValues(); - } - - control.setStepLength(stepLength); // Set step length each time in case there has been changes - - double time = control.getTime(); - double eTime = time + duration; - - monitor.worked(1); - - setSubscribedResults(monitor, time); - - int stepNumber = 1; - while(time < eTime && !canceled) { - if(eTime - time < stepLength) - control.setStepLength(eTime - time); - - monitor.subTask("Simulate step (time = " + time + ")"); - control.simulateStep(); - monitor.worked(1); - - time = control.getTime(); - - if(stepNumber % savePer == 0) { - setSubscribedResults(monitor, time); - } else { - monitor.worked(1); - } - stepNumber++; - monitor.worked(1); - - } - - monitor.subTask("Display results"); - ((MemoryResult)getCurrentResult()).setResult(new GameResult(SysdynGameExperiment.this.results, SysdynGameExperiment.this.subscription)); - monitor.worked(1); - - resultsChanged(true); - monitor.worked(1); - changeState(ExperimentState.STOPPED); - - } catch (FMUJNIException e) { - System.err.println("SysdynGameExperiment simulateDuration failed: \n\t" + e.getMessage()); - } - return Status.OK_STATUS; - } - } - - /** - * Game results - * @author Teemu Lempinen - * - */ - public class GameResult extends SimulationResult { - - public GameResult(HashMap> results, String[] subscription) { - - // Get times - ArrayList timeList = results.get("time"); - double[] times = new double[timeList.size()]; - for(int i = 0; i < timeList.size(); i++) { - times[i] = timeList.get(i); - } - - String name; - double[] values; - ArrayList valueList; - for(int k = 0; k < subscription.length; k++) { - name = subscription[k]; - values = new double[timeList.size()]; - valueList = results.get(name); - for(int i = 0; i < valueList.size(); i++) { - values[i] = valueList.get(i); - } - this.variables.add(new DataSet(name, times, values)); - } - } - } - - @Override public void rewindTo(double time) { + if(control == null) return; if(time >-0.001 && time < 0.001) { - instantiate(); + try { + simulate(new HeadlessModelicaMonitor(), new NullProgressMonitor(), sysdynModel.getConfiguration().getLabel()); + //instantiate(); + } catch (IOException e) { + Logger.defaultLogError(e); + } } else { System.out.println("rewindTo"); } @@ -564,11 +360,11 @@ public class SysdynGameExperiment extends OldSysdynExperiment { control.setStepLength(stepLength); // FIXME: fixed step lenghth control.setTime(startTime); control.instantiateSimulation(); // instantiate simulation - - if(!control.isInitialized()) { + + if(!control.isInitialized()) { control.initializeSimulation(); } - + if(inits.get("variableFilter") == null || inits.get("variableFilter").equals(".*")) subscription = control.getAllVariables(); else @@ -644,6 +440,9 @@ public class SysdynGameExperiment extends OldSysdynExperiment { @Override public void updateSubscriptions() { + + if(!loaded) return; + try { if(control.isInitialized()) currentValues = control.getSubscribedResults(currentValues); @@ -652,14 +451,10 @@ public class SysdynGameExperiment extends OldSysdynExperiment { } super.updateSubscriptions(); } + + @Override + public ISolver getSolver() { + return solver; + } - public Double getCurrentValue(String name) { - if(subscriptionIndexes != null && name != null) { - Integer index = subscriptionIndexes.get(name); - if(index != null) { - return currentValues[index]; - } - } - return null; - } } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentBase.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentBase.java new file mode 100644 index 00000000..16ab3a52 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentBase.java @@ -0,0 +1,132 @@ +/******************************************************************************* + * Copyright (c) 2007, 2012 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import java.util.ArrayList; +import java.util.HashMap; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.jobs.Job; +import org.simantics.db.Resource; +import org.simantics.fmu.FMUJNIException; +import org.simantics.sysdyn.solver.ISolver; + +/** + * Game experiment + * @author Teemu Lempinen + * + */ +abstract public class SysdynGameExperimentBase extends OldSysdynExperiment { + + public double stepLength = DEFAULT_STEP_LENGTH; + public double startTime = DEFAULT_START_TIME; + protected double stepDuration = DEFAULT_STEP_DURATION; + protected int savePer = 1; + + protected HashMap subscriptionIndexes; + protected double[] currentValues; // Current values from FMU. Updated with updateSubscriptions + + HashMap> results; + + protected String[] subscription; + + public static double DEFAULT_STEP_DURATION = 1.0; + public static double DEFAULT_STEP_LENGTH = 0.1; + public static double DEFAULT_START_TIME = 0.0; + public static int DEFAULT_OUTPUT_INTERVAL = 1; + + public SysdynGameExperimentBase(Resource experiment, Resource model) { + super(experiment, model); + } + + public double getStepDuration() { + return stepDuration; + } + + public void setStepDuration(double duration) { + this.stepDuration = duration; + } + + public double getStepLength() { + return stepLength; + } + + public void setStepLength(double stepLength) { + this.stepLength = stepLength; + } + + public void setStartTime(double startTime) { + this.startTime = startTime; + } + + public void setOutputInterval(int interval) { + this.savePer = interval; + } + + public Double getCurrentValue(String name) { + if(subscriptionIndexes != null && name != null) { + Integer index = subscriptionIndexes.get(name); + if(index != null) { + return currentValues[index]; + } + } + return null; + } + + public void setSubscribedResults(IProgressMonitor monitor, double time) throws FMUJNIException { + +// System.err.println("setSubscribedResults " + time); + + monitor.subTask("Get results (time = " + time + ")"); + currentValues = getSolver().getSubscribedResults(currentValues); + monitor.worked(1); + + monitor.subTask("Save results (time = " + time + ")"); + for(int k = 0; k < subscription.length; k++) { + setResults(time, subscription[k], currentValues[k]); + } + + lastResultTime = time; + + } + + private double lastResultTime = Double.NaN; + + public void setResults(double time, String key, Double value) { + ArrayList list = results.get(key); + if(list == null) { + list = new ArrayList(); + results.put(key, list); + } + if(time == lastResultTime) { + list.set(list.size()-1, value); + } else { + list.add(value); + } +// System.err.println("setResults " + time + " " + key + " = " + list); + } + + public void clearResults() { + lastResultTime = Double.NaN; + results.clear(); + } + + @Override + public void simulateDuration(double duration) { + Job job = new SimulateDurationJob(this, "Simulate steps", duration); + // Start the Job + job.schedule(); + } + + public abstract ISolver getSolver(); + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentInternal.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentInternal.java new file mode 100644 index 00000000..c67ba488 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentInternal.java @@ -0,0 +1,170 @@ +/******************************************************************************* + * Copyright (c) 2007, 2012 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.utils.Logger; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.util.Layer0Utils; +import org.simantics.db.layer0.util.Simantics; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.db.layer0.variable.Variables; +import org.simantics.modelica.IModelicaMonitor; +import org.simantics.modeling.PartialIC; +import org.simantics.simulation.experiment.ExperimentState; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.simulation.SimulationJob.HeadlessModelicaMonitor; +import org.simantics.sysdyn.solver.ISolver; +import org.simantics.sysdyn.solver.ISolverMonitor; +import org.simantics.sysdyn.solver.InternalSolver; + + +public class SysdynGameExperimentInternal extends SysdynGameExperimentBase { + + public InternalSolver solver; + + public SysdynGameExperimentInternal(Resource experiment, Resource model) { + super(experiment, model); + } + + @Override + public ISolver getSolver() { + return solver; + } + + @Override + public void init(ReadGraph g) { + + super.init(g); + + results = new HashMap>(); + + solver = new InternalSolver(this, sysdynModel, true, new ISolverMonitor() { + + @Override + public void showConsole() { + // TODO Auto-generated method stub + + } + + @Override + public void message(String message) { + System.err.println("Internal solver:" + message); + } + + @Override + public void clearConsole() { + // TODO Auto-generated method stub + + } + }); + + } + + @Override + public synchronized void simulate(final IModelicaMonitor monitor, final IProgressMonitor progressMonitor, String modelName) throws IOException { + + new Exception().printStackTrace(); + + try { + + solver.initialize(); + solver.buildModel(); + + solver.setStepLength(stepLength); // FIXME: fixed step length + + //solver.setTime(startTime); + + subscription = solver.solver.keys(); + + // Initialize subscription indexes map for fast result reading in getValue() + if(subscriptionIndexes == null) + subscriptionIndexes = new HashMap(); + + subscriptionIndexes.clear(); + for(int i = 0; i < subscription.length; i++) { + subscriptionIndexes.put(subscription[i], i); + } + + // Initialize container for current simulation results + currentValues = new double[subscription.length]; + + // subscribe all variables + //solver.subscribe(subscription); + + clearResults(); + //getInitialResultValues(); + + Simantics.getSession().syncRequest(new WriteRequest() { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + + Resource run = Layer0Utils.getPossibleChild(graph, SysdynGameExperimentInternal.this.experiment, getIdentifier()); + if(run == null) { + System.err.println("No run"); + return; + } + + Variable base = Variables.getVariable(graph, run); + + SysdynResource SYSDYN = SysdynResource.getInstance(graph); + + Resource ic = graph.getPossibleObject(SysdynGameExperimentInternal.this.experiment, SYSDYN.Experiment_ic); + if(ic == null) return; + + PartialIC data = graph.getPossibleRelatedValue(ic, SYSDYN.InitialCondition_HasInitialValues, PartialIC.BINDING); + data.apply(graph, base); + + } + + }); + + + setSubscribedResults(new NullProgressMonitor(), solver.getTime()); + + ((MemoryResult)getCurrentResult()).setResult(new GameResult(this, this.results, this.subscription)); + + resultsChanged(true); + + changeState(ExperimentState.STOPPED); + + } catch (Exception e) { + Logger.defaultLogError(e); + } + } + + @Override + public void rewindTo(double time) { + + if(time >-0.001 && time < 0.001) { + try { + simulate(new HeadlessModelicaMonitor(), new NullProgressMonitor(), sysdynModel.getConfiguration().getLabel()); + //instantiate(); + } catch (IOException e) { + Logger.defaultLogError(e); + } + } else { + System.out.println("rewindTo"); + } + } + + } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java index feb07341..ab040550 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java @@ -427,7 +427,12 @@ public class SysdynModel implements IModel, IMappingListener, VariableSubscripti if(g.isInstanceOf(experiment, sr.PlaybackExperiment)) { exp = new SysdynPlaybackExperiment(experiment, modelResource); } else if(g.isInstanceOf(experiment, sr.GameExperiment)) { - exp = new SysdynGameExperiment(experiment, modelResource); + if (SolverType.INTERNAL.equals(SolverSettings.getSelectedSolverType())) { + exp = new SysdynGameExperimentInternal(experiment, modelResource); + } + else { + exp = new SysdynGameExperiment(experiment, modelResource); + } } else if(g.isInstanceOf(experiment, sr.SensitivityAnalysisExperiment)) { exp = new SysdynSensitivityAnalysisExperiment(experiment, modelResource); } else if(g.isInstanceOf(experiment, sr.BasicExperiment)) { diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/RepresentationUtils.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/RepresentationUtils.java index 6c5e3542..cac1aea8 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/RepresentationUtils.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/RepresentationUtils.java @@ -20,7 +20,7 @@ import org.simantics.simulation.experiment.IExperiment; import org.simantics.simulation.project.IExperimentManager; import org.simantics.sysdyn.expressionParser.ExpressionParser; import org.simantics.sysdyn.expressionParser.ParseException; -import org.simantics.sysdyn.manager.SysdynGameExperiment; +import org.simantics.sysdyn.manager.SysdynGameExperimentBase; import org.simantics.sysdyn.representation.Configuration; import org.simantics.sysdyn.representation.IElement; import org.simantics.sysdyn.representation.IndependentVariable; @@ -46,7 +46,7 @@ public class RepresentationUtils { IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); IExperiment active = manager.getActiveExperiment(); - if (active instanceof SysdynGameExperiment) + if (active instanceof SysdynGameExperimentBase) return true; else return false; diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java index 92e8c99e..75e177f2 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java @@ -69,7 +69,7 @@ public class SimulationJob extends Job { return "SimulationJob".equals(family); } - private class HeadlessModelicaMonitor implements IModelicaMonitor { + public static class HeadlessModelicaMonitor implements IModelicaMonitor { public HeadlessModelicaMonitor() { } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolver.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolver.java index d52a67c7..a2a14fbc 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolver.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolver.java @@ -10,4 +10,14 @@ public interface ISolver { public void updateResults() throws Exception; public SolverType getType(); + public double[] getSubscribedResults(double[] array); + + public void prepareToStep() throws Exception; + public void simulateStep() throws Exception ; + + public void setStepLength(double length) throws Exception ; + public double getTime(); + + public void setRealValue(String name, double value) throws Exception ; + } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolver.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolver.java index 7cf327b9..6835e191 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolver.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolver.java @@ -23,21 +23,24 @@ public class InternalSolver implements ISolver { private SysdynExperiment experiment; private SysdynModel model; private ISolverMonitor monitor; - private Solver solver; + public Solver solver; private double start; private double stop; private double step; private double interval; + private final boolean isGame; + private SimulationLocation location; private HashMap results; - public InternalSolver(SysdynExperiment experiment, SysdynModel model, ISolverMonitor monitor) { + public InternalSolver(SysdynExperiment experiment, SysdynModel model, boolean isGame, ISolverMonitor monitor) { this.experiment = experiment; this.model = model; this.monitor = monitor; + this.isGame = isGame; solver = new Solver(); @@ -61,7 +64,7 @@ public class InternalSolver implements ISolver { stop = representation.getStopTime(); // String omVersion = ModelicaManager.getDefaultOMVersion(); - String modelContent = ModelicaWriter.write(model.getModules(), start, false, "1.9"); + String modelContent = ModelicaWriter.write(model.getModules(), start, isGame, "1.9"); // update some stuff FunctionUtils.updateFunctionFilesForExperiment(experiment); @@ -181,5 +184,34 @@ public class InternalSolver implements ISolver { public SolverType getType() { return SolverType.INTERNAL; } + + @Override + public double[] getSubscribedResults(double[] array) { + return solver.values(); + } + + @Override + public double getTime() { + return solver.getTime(); + } + + @Override + public void prepareToStep() throws Exception { + } + + @Override + public void setRealValue(String name, double value) throws Exception { + solver.setValue(name, value); + } + + @Override + public void simulateStep() throws Exception { + solver.step(); + } + + @Override + public void setStepLength(double length) throws Exception { + solver.setStep(length); + } } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ModelicaSolver.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ModelicaSolver.java new file mode 100644 index 00000000..25380681 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ModelicaSolver.java @@ -0,0 +1,93 @@ +package org.simantics.sysdyn.solver; + +import org.simantics.fmu.FMUJNIException; +import org.simantics.sysdyn.manager.SysdynGameExperiment; +import org.simantics.sysdyn.solver.SolverSettings.SolverType; + +public class ModelicaSolver implements ISolver { + + SysdynGameExperiment exp; + + public ModelicaSolver(SysdynGameExperiment exp) { + this.exp = exp; + } + + @Override + public void initialize() throws Exception { + // TODO Auto-generated method stub + + } + + @Override + public void buildModel() throws Exception { + // TODO Auto-generated method stub + + } + + @Override + public void runSolver() throws Exception { + // TODO Auto-generated method stub + + } + + @Override + public void updateResults() throws Exception { + // TODO Auto-generated method stub + + } + + @Override + public SolverType getType() { + // TODO Auto-generated method stub + return null; + } + + @Override + public double[] getSubscribedResults(double[] array) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void prepareToStep() throws Exception { + + // initialize if not initialized + if(!exp.control.isInitialized()) { + exp.control.setTime(exp.startTime); + exp.control.initializeSimulation(); + exp.clearResults(); + // getInitialResultValues(); + } + + exp.control.setStepLength(exp.stepLength); // Set step length each time in case there has been changes + + } + + @Override + public void simulateStep() throws Exception { + exp.control.simulateStep(); + } + + @Override + public void setStepLength(double length) throws Exception { + exp.control.setStepLength(length); + } + + @Override + public double getTime() { + if(exp.control != null) { + try { + return exp.control.getTime(); + } catch (FMUJNIException e) { + } + } + return 0.0; + } + + @Override + public void setRealValue(String name, double value) throws Exception { + exp.control.setRealValue(name, value); + } + + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SysdynSimulationJob.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SysdynSimulationJob.java index e12c6e3d..eed1f064 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SysdynSimulationJob.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SysdynSimulationJob.java @@ -62,7 +62,7 @@ public class SysdynSimulationJob extends Job { // has changed, a new solver must be created if (solver == null || !solver.getType().equals(type)) { if (SolverType.INTERNAL.equals(type)) { - solver = new InternalSolver(experiment, experiment.sysdynModel, solverMonitor); + solver = new InternalSolver(experiment, experiment.sysdynModel, false, solverMonitor); } else if (SolverType.OPENMODELICA.equals(type)) { return new Status(Status.ERROR, pluginId, "The experiment should be reloaded");