From f3d8dc0d9befe0a241fe8fbd32315856fc960588 Mon Sep 17 00:00:00 2001 From: lempinen Date: Wed, 1 Sep 2010 09:11:28 +0000 Subject: [PATCH] Better (error) messages for simulation, simulation buttons react to running simulations git-svn-id: https://www.simantics.org/svn/simantics/sysdyn/trunk@17742 ac1ea38d-2e2b-0410-8846-a27921b304fc --- .../simantics/modelica/ModelicaManager.java | 8 +- .../ui/handlers/RunBasicExperiment.java | 25 +- .../sysdyn/manager/SysdynExperiment.java | 447 +++++------ .../simantics/sysdyn/manager/SysdynModel.java | 698 +++++++++--------- .../sysdyn/simulation/SimulationJob.java | 36 +- .../simulation/SimulationScheduler.java | 23 +- 6 files changed, 602 insertions(+), 635 deletions(-) diff --git a/org.simantics.modelica/src/org/simantics/modelica/ModelicaManager.java b/org.simantics.modelica/src/org/simantics/modelica/ModelicaManager.java index 1bddcf45..3723a30e 100644 --- a/org.simantics.modelica/src/org/simantics/modelica/ModelicaManager.java +++ b/org.simantics.modelica/src/org/simantics/modelica/ModelicaManager.java @@ -73,7 +73,11 @@ public class ModelicaManager { b.append((char)c); else { System.out.println("OMC output: " + b.toString()); - monitor.message(b.toString()); + String message = b.toString(); + message = message.trim(); + if(message.startsWith("\"")) + message = message.substring(1); + monitor.message(message); b.delete(0, b.length()); } } catch (IOException e) { @@ -141,7 +145,7 @@ public class ModelicaManager { printProcessOutput(process, monitor); if(!simulationLocation.exeFile.isFile()) - throw new ModelicaException("exe file not created"); + throw new ModelicaException(".exe file not created"); } catch(IOException e) { e.printStackTrace(); diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RunBasicExperiment.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RunBasicExperiment.java index 5780d4ae..d5f48ebf 100644 --- a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RunBasicExperiment.java +++ b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RunBasicExperiment.java @@ -4,16 +4,15 @@ package org.simantics.sysdyn.ui.handlers; import java.util.Map; import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.Command; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.commands.IElementUpdater; import org.eclipse.ui.menus.UIElement; +import org.simantics.simulation.experiment.ExperimentState; import org.simantics.simulation.experiment.IDynamicExperiment; import org.simantics.simulation.experiment.IExperiment; import org.simantics.simulation.project.IExperimentManager; +import org.simantics.sysdyn.manager.SysdynExperiment; import org.simantics.ui.SimanticsUI; public class RunBasicExperiment extends AbstractHandler implements IElementUpdater { @@ -33,14 +32,16 @@ public class RunBasicExperiment extends AbstractHandler implements IElementUpdat @SuppressWarnings("rawtypes") @Override public void updateElement(UIElement element, Map parameters) { - ICommandService commandService = - (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); - Command command = commandService.getCommand(ToggleSimulation.COMMAND); - boolean checked = (Boolean) command.getState(ToggleSimulation.STATE).getValue(); - if(checked) - this.setBaseEnabled(false); - else - this.setBaseEnabled(true); - + IExperimentManager manager = + SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); + IExperiment experiment = manager.getActiveExperiment(); + if(experiment instanceof SysdynExperiment) { + ExperimentState state = experiment.getState(); + if(state == ExperimentState.RUNNING) { + this.setBaseEnabled(false); + } else { + this.setBaseEnabled(true); + } + } } } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java index b810ba47..b3b9855f 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java @@ -1,14 +1,10 @@ package org.simantics.sysdyn.manager; import java.io.File; -import java.util.ArrayList; -import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.locks.Lock; import org.eclipse.core.runtime.Platform; -import org.simantics.databoard.annotations.Optional; -import org.simantics.databoard.binding.mutable.Variant; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.Session; @@ -29,259 +25,196 @@ import org.simantics.sysdyn.simulation.SimulationScheduler; public class SysdynExperiment extends Experiment implements IDynamicExperiment { - Session session; - Runnable modificationListener; - Runnable modificationListener2; - Resource experiment; - SysdynModel sysdynModel; - - public SysdynExperiment(Resource experiment, Resource model) { - super(model); - this.experiment = experiment; - // TODO Auto-generated constructor stub - } - - public Resource getResource() { - return this.experiment; - } - - @Override - public void rewindTo(double time) { - // TODO Auto-generated method stub - System.out.println("rewindTo"); - } - - @Override - public void saveState() { - // TODO Auto-generated method stub - System.out.println("saveState"); - if(sysdynModel.getSysdynResult() == null) return; - - try { - session.syncRequest(new WriteRequest() { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - Layer0 l0 = Layer0.getInstance(graph); - Resource model = graph.getSingleObject(experiment, l0.PartOf); - Resource project = graph.getSingleObject(model, l0.PartOf); - String projectName = graph.getPossibleRelatedValue(project, l0.HasName); - File root = new File(Platform.getLocation().toOSString(), "www.simantics.org"); - if(!root.isDirectory()) root.mkdir(); - File projectRoot = new File(root, projectName); - if(!projectRoot.isDirectory()) projectRoot.mkdir(); - File file = new File( projectRoot, UUID.randomUUID().toString() + ".dbb"); - - String name = GraphUtils.findFreshName(graph, "Result", model, l0.ConsistsOf, "%s%d"); - - SysdynResource sr = SysdynResource.getInstance(graph); - Resource res = GraphUtils.create2(graph, sr.Result, - l0.HasLabel, name, - l0.HasName, name, - l0.PartOf, model, - sr.HasResultFile, file.getAbsolutePath()); - graph.claim(experiment, sr.HasResult, res); - sysdynModel.getSysdynResult().saveToFile(file); - } - }); - } catch (DatabaseException e) { - e.printStackTrace(); - } - } - - - @Override - public void simulate(boolean enabled) { - System.out.println("simulate"); - if(enabled) { - changeState(ExperimentState.STOPPED); - startSimulation(); - } - } - - - private void startSimulation() { - try { - session.syncRequest(new ReadRequest() { - - @Override - public void run(ReadGraph graph) throws DatabaseException { - SimulationScheduler.start(sysdynModel); - } - }); - } catch (DatabaseException e) { - e.printStackTrace(); - } - } - - public void toggleSimulation(boolean enabled) { - if(enabled) { - changeState(ExperimentState.RUNNING); - if(modificationListener == null) { - - modificationListener = new Runnable() { - - @Override - public void run() { - session.asyncRequest(new ReadRequest() { - - @Override - public void run(ReadGraph graph) throws DatabaseException { - if(getState() == ExperimentState.RUNNING) { - SimulationScheduler.start(sysdynModel); - } - - } - }); - - }; - }; - sysdynModel.addModificationListener(modificationListener); - } - } - else { - changeState(ExperimentState.STOPPED); - } - - } - - @Override - public void simulateDuration(double duration) { - // TODO Auto-generated method stub - System.out.println("simulateDuartion"); - } - - @Override - public void refresh(Session session) { - System.out.println("refresh"); - session.asyncRequest(new ReadRequest() { - - @Override - public void run(ReadGraph graph) throws DatabaseException { - init(graph); - } - - }); - } - - public void init(ReadGraph g) { - System.out.println("init"); - changeState(ExperimentState.STOPPED); - this.session = g.getSession(); - - 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); - - if (modificationListener2 == null) { - modificationListener2 = new Runnable() { - - @Override - public void run() { - refresh(session); - }; - }; - sysdynModel.addModificationListener(modificationListener2); - } - } - }); - - } - - @Override - protected void localStateChange() { - ExperimentState state = getState(); - switch(state) { - case DISPOSED: - System.out.println("disposed"); - session.asyncRequest(new ReadRequest() { - - @Override - public void run(ReadGraph graph) throws DatabaseException { - sysdynModel.removeModificationListener(modificationListener); - sysdynModel.removeModificationListener(modificationListener2); - modificationListener = null; - toggleActivation(graph, false); - } - }); - break; - } - } - - private void toggleActivation(ReadGraph graph, final boolean activate) { - VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class); - final Session session = graph.getSession(); - session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) { - @Override - public void perform(WriteGraph graph) throws DatabaseException { - VirtualGraph runtime = graph.getService(VirtualGraph.class); - - session.asyncRequest(new WriteRequest(runtime) { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - SimulationResource SIMU = SimulationResource.getInstance(graph); - if(activate) - graph.claim(experiment, SIMU.IsActive, experiment); - else - graph.denyStatement(experiment, SIMU.IsActive, experiment); - } - - }); - } - }); - } - - public static class Sample { - public double value; - - @Override - public String toString() { - return ""+value; - } - } - - public static class Segment { - public int startTime, endTime; - public ArrayList samples; - - @Override - public String toString() { - return "[startTime="+startTime+", endTime="+endTime+", samples="+samples+"]"; - } - - } - - public static class Recording { - public String id; - public TreeMap labels; - public ArrayList segments; - - @Override - public String toString() { - return "id="+id+", labels="+labels+", segments="+segments; - } - - } - - public static class RecordingSession { - public @Optional Variant datasource; - public Variant timeVarialbeId; - public TreeMap recordings; - - @Override - public String toString() { - return recordings.toString(); - } - } - - public static class NodeId { - public String nodeId; - } + Session session; + Runnable modificationListener; + Resource experiment; + SysdynModel sysdynModel; + boolean toggled = false; + + public SysdynExperiment(Resource experiment, Resource model) { + super(model); + this.experiment = experiment; + // TODO Auto-generated constructor stub + } + + public Resource getResource() { + return this.experiment; + } + + @Override + public void rewindTo(double time) { + // TODO Auto-generated method stub + System.out.println("rewindTo"); + } + + @Override + public void saveState() { + if(sysdynModel.getSysdynResult() == null) return; + + try { + session.syncRequest(new WriteRequest() { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + Resource model = graph.getSingleObject(experiment, l0.PartOf); + Resource project = graph.getSingleObject(model, l0.PartOf); + String projectName = graph.getPossibleRelatedValue(project, l0.HasName); + File root = new File(Platform.getLocation().toOSString(), "www.simantics.org"); + if(!root.isDirectory()) root.mkdir(); + File projectRoot = new File(root, projectName); + if(!projectRoot.isDirectory()) projectRoot.mkdir(); + File file = new File( projectRoot, UUID.randomUUID().toString() + ".dbb"); + + String name = GraphUtils.findFreshName(graph, "Result", model, l0.ConsistsOf, "%s%d"); + + SysdynResource sr = SysdynResource.getInstance(graph); + Resource res = GraphUtils.create2(graph, sr.Result, + l0.HasLabel, name, + l0.HasName, name, + l0.PartOf, model, + sr.HasResultFile, file.getAbsolutePath()); + graph.claim(experiment, sr.HasResult, res); + sysdynModel.getSysdynResult().saveToFile(file); + } + }); + } catch (DatabaseException e) { + e.printStackTrace(); + } + } + + + @Override + public void simulate(boolean enabled) { + if(enabled) { + changeState(ExperimentState.RUNNING); + startSimulation(); + } else if (!toggled){ + changeState(ExperimentState.STOPPED); + } + } + + + private void startSimulation() { + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + SimulationScheduler.start(sysdynModel, SysdynExperiment.this); + } + }); + } + + public void toggleSimulation(boolean enabled) { + if(enabled) { + this.toggled = true; + changeState(ExperimentState.RUNNING); + if(modificationListener == null) { + + modificationListener = new Runnable() { + + @Override + public void run() { + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + if(getState() == ExperimentState.RUNNING) { + SimulationScheduler.start(sysdynModel, SysdynExperiment.this); + } + + } + }); + + }; + }; + sysdynModel.addModificationListener(modificationListener); + } + } + else { + changeState(ExperimentState.STOPPED); + this.toggled = false; + } + + } + + @Override + public void simulateDuration(double duration) { + // TODO Auto-generated method stub + System.out.println("simulateDuartion"); + } + + @Override + public void refresh(Session session) { + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + init(graph); + } + + }); + } + + public void init(ReadGraph g) { + changeState(ExperimentState.STOPPED); + this.session = g.getSession(); + + 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); + } + }); + + } + + @Override + protected void localStateChange() { + ExperimentState state = getState(); + switch(state) { + case DISPOSED: + System.out.println("disposed"); + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + sysdynModel.cancelSimulation(); + sysdynModel.removeModificationListener(modificationListener); + modificationListener = null; + toggleActivation(graph, false); + } + }); + break; + } + } + + private void toggleActivation(ReadGraph graph, final boolean activate) { + VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class); + final Session session = graph.getSession(); + session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) { + @Override + public void perform(WriteGraph graph) throws DatabaseException { + VirtualGraph runtime = graph.getService(VirtualGraph.class); + + session.asyncRequest(new WriteRequest(runtime) { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + SimulationResource SIMU = SimulationResource.getInstance(graph); + if(activate) + graph.claim(experiment, SIMU.IsActive, experiment); + else + graph.denyStatement(experiment, SIMU.IsActive, experiment); + } + + }); + } + }); + } @Override public Lock getDatasourceLock() { 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 c7a7e88e..5d81e0df 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java @@ -39,6 +39,8 @@ import org.simantics.modelica.data.SimulationResult; import org.simantics.objmap.IMapping; import org.simantics.objmap.IMappingListener; import org.simantics.objmap.Mappings; +import org.simantics.simulation.experiment.Experiment; +import org.simantics.simulation.experiment.ExperimentState; import org.simantics.simulation.experiment.IExperiment; import org.simantics.simulation.model.IModel; import org.simantics.simulation.ontology.SimulationResource; @@ -61,361 +63,373 @@ import org.simantics.sysdyn.representation.expressions.ParameterExpression; */ public class SysdynModel implements IMappingListener, IModel { - Session session; + Session session; - IMapping mapping; + IMapping mapping; - Resource configurationResource; - Configuration configuration; + Resource configurationResource; + Configuration configuration; - Set modules = new HashSet(); + Set modules = new HashSet(); - Process process; - boolean canceled; - SimulationResult result; - SysdynResult sysdynResult; + Process process; + boolean canceled; + SimulationResult result; + SysdynResult sysdynResult; - CopyOnWriteArrayList modificationListeners = - new CopyOnWriteArrayList(); - CopyOnWriteArrayList resultListeners = - new CopyOnWriteArrayList(); + CopyOnWriteArrayList modificationListeners = + new CopyOnWriteArrayList(); + CopyOnWriteArrayList resultListeners = + new CopyOnWriteArrayList(); - @SuppressWarnings("rawtypes") + @SuppressWarnings("rawtypes") Map services = new HashMap(); - String previousModelStructure; - HashMap previousImportantInits = new HashMap(); - - File simulationDir; - - void readModules(ReadGraph graph, Resource configResource, Set result) throws DatabaseException { - - if(!result.add(configResource)) return; - - Layer0 l0 = Layer0.getInstance(graph); - SysdynResource sr = SysdynResource.getInstance(graph); - StructuralResource2 str = StructuralResource2.getInstance(graph); - - for(Resource part : graph.getObjects(configResource, l0.ConsistsOf)) { - if(graph.isInstanceOf(part, sr.Module)) { - Resource type = graph.getPossibleType(part, sr.Module); - Resource config = graph.getPossibleObject(type, str.IsDefinedBy); - readModules(graph, config, result); - } - } - - } - - Set readModules(ReadGraph graph, Resource configResource) throws DatabaseException { - HashSet result = new HashSet(); - readModules(graph, configResource, result); - return result; - } - - private void createMapping(ReadGraph g) throws DatabaseException { - SysdynSchema schema = new SysdynSchema(g); - mapping = Mappings.createWithListening(schema); - mapping.addMappingListener(SysdynModel.this); - configuration = (Configuration)mapping.map(g, configurationResource); - for(Resource config : readModules(g, configurationResource)) { - modules.add((Configuration)mapping.map(g, config)); - } - System.out.println("Loaded model with " + modules.size() + " modules."); - } - - public SysdynModel(ReadGraph g, Resource configurationResource) { - this.session = g.getSession(); - this.configurationResource = configurationResource; - - try { - createMapping(g); - } catch(DatabaseException e) { - e.printStackTrace(); - } - sysdynResult = new SysdynResult(); - sysdynResult.setResult(new SimulationResult()); - - previousModelStructure = ""; - - File modelsDir = Activator.getBundleContext().getDataFile("models"); - String configName = configuration.getName(); - List files = Arrays.asList(modelsDir.list()); - if (files.contains(configName)) { - int i = 2; - while (files.contains(configName + "_" + i)){ - i++; - } - configName += "_" + i; - } - - simulationDir = Activator.getBundleContext().getDataFile("models/" + configName); - if (!simulationDir.exists()) { - simulationDir.mkdir(); - } - } - - - /* - * some dummy(?) stuff for experiments - */ - public SysdynModel(Resource configurationResource) { - this.configurationResource = configurationResource; - } - - public synchronized void simulate(IModelicaMonitor monitor, final IProgressMonitor progressMonitor) throws IOException { - canceled = false; - - ModelicaWriter writer = new ModelicaWriter(); - //writer.write(configuration); - for(Configuration c : modules) { - writer.write(c); - } - - progressMonitor.worked(20); - - String modelText = writer.toString(); - - HashMap inits = getInits(configuration, ""); - - Model model = configuration.getModel(); - - String startTime = model.getStartTime().toString(); - String stopTime = model.getStopTime().toString(); - inits.put("start value", startTime); - inits.put("stop value", stopTime); - if(model.getSolver() != null) - inits.put("solver", model.getSolver()); - if(model.getTolerance() != null) - inits.put("tolerance", model.getTolerance().toString()); - - final SimulationLocation simulationLocation = ModelicaManager.createInputFiles( - simulationDir, - configuration.getName(), - writer.toString(), - inits); - - progressMonitor.worked(20); - - if (hasStructureChanged(modelText, inits)) { - previousModelStructure = modelText; - System.out.println("== Modelica == "); - System.out.println(writer.toString()); - System.out.println("== Modelica ends == "); - - try { + String previousModelStructure; + HashMap previousImportantInits = new HashMap(); + + File simulationDir; + + void readModules(ReadGraph graph, Resource configResource, Set result) throws DatabaseException { + + if(!result.add(configResource)) return; + + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + StructuralResource2 str = StructuralResource2.getInstance(graph); + + for(Resource part : graph.getObjects(configResource, l0.ConsistsOf)) { + if(graph.isInstanceOf(part, sr.Module)) { + Resource type = graph.getPossibleType(part, sr.Module); + Resource config = graph.getPossibleObject(type, str.IsDefinedBy); + readModules(graph, config, result); + } + } + + } + + Set readModules(ReadGraph graph, Resource configResource) throws DatabaseException { + HashSet result = new HashSet(); + readModules(graph, configResource, result); + return result; + } + + private void createMapping(ReadGraph g) throws DatabaseException { + SysdynSchema schema = new SysdynSchema(g); + mapping = Mappings.createWithListening(schema); + mapping.addMappingListener(SysdynModel.this); + configuration = (Configuration)mapping.map(g, configurationResource); + for(Resource config : readModules(g, configurationResource)) { + modules.add((Configuration)mapping.map(g, config)); + } + System.out.println("Loaded model with " + modules.size() + " modules."); + } + + public SysdynModel(ReadGraph g, Resource configurationResource) { + this.session = g.getSession(); + this.configurationResource = configurationResource; + + try { + createMapping(g); + } catch(DatabaseException e) { + e.printStackTrace(); + } + sysdynResult = new SysdynResult(); + sysdynResult.setResult(new SimulationResult()); + + previousModelStructure = ""; + + File modelsDir = Activator.getBundleContext().getDataFile("models"); + String configName = configuration.getName(); + List files = Arrays.asList(modelsDir.list()); + if (files.contains(configName)) { + int i = 2; + while (files.contains(configName + "_" + i)){ + i++; + } + configName += "_" + i; + } + + simulationDir = Activator.getBundleContext().getDataFile("models/" + configName); + if (!simulationDir.exists()) { + simulationDir.mkdir(); + } + } + + + /* + * some dummy(?) stuff for experiments + */ + public SysdynModel(Resource configurationResource) { + this.configurationResource = configurationResource; + } + + public synchronized void simulate(IModelicaMonitor monitor, final IProgressMonitor progressMonitor, final Experiment experiment) throws IOException { + canceled = false; + progressMonitor.subTask("Write modelica classes"); + ModelicaWriter writer = new ModelicaWriter(); + for(Configuration c : modules) { + writer.write(c); + } + progressMonitor.worked(1); + + progressMonitor.subTask("Write initial files"); + String modelText = writer.toString(); + HashMap inits = getInits(configuration, ""); + Model model = configuration.getModel(); + String startTime = model.getStartTime().toString(); + String stopTime = model.getStopTime().toString(); + inits.put("start value", startTime); + inits.put("stop value", stopTime); + if(model.getSolver() != null) + inits.put("solver", model.getSolver()); + if(model.getTolerance() != null) + inits.put("tolerance", model.getTolerance().toString()); + + final SimulationLocation simulationLocation = ModelicaManager.createInputFiles( + simulationDir, + configuration.getName(), + writer.toString(), + inits); + + progressMonitor.worked(1); + + + if (!simulationLocation.exeFile.isFile() || hasStructureChanged(modelText, inits)) { + progressMonitor.subTask("Build model"); + previousModelStructure = modelText; + System.out.println("== Modelica == "); + System.out.println(writer.toString()); + System.out.println("== Modelica ends == "); + + try { + simulationLocation.exeFile.delete(); ModelicaManager.buildModel(simulationLocation, monitor); - previousImportantInits.clear(); - previousImportantInits.put("start value", startTime); - previousImportantInits.put("stop value", stopTime); + previousImportantInits.clear(); + previousImportantInits.put("start value", startTime); + previousImportantInits.put("stop value", stopTime); } catch (ModelicaException e) { monitor.showConsole(); canceled = true; previousModelStructure = ""; } - } - - progressMonitor.worked(20); - - if(simulationLocation != null && !canceled) { - process = ModelicaManager.runModelica( - simulationLocation, - monitor, - inits - ); - ModelicaManager.printProcessOutput(process, monitor); - - Thread resultThread = new Thread() { - @Override - public void run() { - try { - process.waitFor(); - - if(!canceled) { - result = new SimulationResult(); - result.read(simulationLocation.outputFile); - result.readInits(simulationLocation.initFile); - result.filter(); - progressMonitor.worked(20); - sysdynResult.setResult(result); - progressMonitor.worked(20); - synchronized(resultListeners) { - for(Runnable listener : resultListeners) - listener.run(); - } - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - }; - resultThread.run(); - } - process = null; - } - - private boolean hasStructureChanged(String modelText, Map inits) { - if (!modelText.equals(previousModelStructure)) - return true; - for(String key : previousImportantInits.keySet()) { - if(!inits.containsKey(key) || !previousImportantInits.get(key).equals(inits.get(key))) - return true; - } - return false; - } - - public void cancelSimulation() { - canceled = true; - if(process != null) { - process.destroy(); - } - } - - public synchronized boolean update() throws DatabaseException { - if(mapping.isDomainModified()) { - session.syncRequest(new ReadRequest() { - @Override - public void run(ReadGraph graph) throws DatabaseException { - mapping.updateRange(graph); - } - }); - return true; - } - else - return false; - } - - public SimulationResult getSimulationResult() { - return result; - } - - public SysdynResult getSysdynResult() { - return sysdynResult; - } - - public void addResultListener(Runnable listener) { - synchronized(resultListeners) { - resultListeners.add(listener); - } - } - - public void removeResultListener(Runnable listener) { - synchronized(resultListeners) { - resultListeners.add(listener); - } - } - - public void addModificationListener(Runnable listener) { - synchronized(modificationListeners) { - modificationListeners.add(listener); - } - } - - public void removeModificationListener(Runnable listener) { - synchronized(modificationListeners) { - modificationListeners.remove(listener); - } - } - - @Override - public void domainModified() { - synchronized(modificationListeners) { - for(Runnable listener : modificationListeners) - listener.run(); - } - } - - @Override - public void rangeModified() { - } - - public Configuration getConfiguration() { - return configuration; - } - - public IMapping getMapping() { - return mapping; - } - - public synchronized IElement getElement(Resource resource) { - return (IElement)mapping.get(resource); - } - - public T getService(Class clazz) { - synchronized(services) { - return clazz.cast(services.get(clazz)); - } - } - - public void addService(Class clazz, T service) { - synchronized(services) { - services.put(clazz, service); - } - } - - @Override - public IExperiment loadExperiment(ReadGraph g, Resource experiment, IExperimentActivationListener listener) { - SysdynExperiment exp = new SysdynExperiment(experiment, configurationResource); - try { - exp.init(g); - listener.onExperimentActivated(exp); - return exp; - } catch(Exception e) { - listener.onFailure(e); - return null; - } - } - - public Collection getActiveResults(ReadGraph graph) { - ArrayList results = new ArrayList(); - - try { - Layer0 l0 = Layer0.getInstance(graph); - SysdynResource sr = SysdynResource.getInstance(graph); - SimulationResource SIMU = SimulationResource.getInstance(graph); - Resource model = graph.getSingleObject(configurationResource, SIMU.IsConfigurationOf); - Collection experiments = graph.getObjects(model, l0.ConsistsOf); - for(Resource experiment : experiments) { - Collection experimentResults = graph.getObjects(experiment, sr.HasResult); - for(Resource result : experimentResults) { - if(graph.hasStatement(result, SIMU.IsActive)) { - SysdynResult sysdynResult = new SysdynResult( - (String) graph.getPossibleRelatedValue(result, l0.HasLabel), - (String) graph.getPossibleRelatedValue(result, sr.HasResultFile)); - results.add(sysdynResult); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - - if(getSysdynResult() != null) - results.add(0, getSysdynResult() ); - - - - return results; - } - - private HashMap getInits(Configuration configuration, String prefix) { - HashMap inits = new HashMap(); - for (IElement element : configuration.getElements()) { - if (element instanceof Module) { - Module module = (Module) element; - Configuration conf = module.getType().getConfiguration(); - inits.putAll(getInits(conf, prefix + module.getName() + ".")); - } else if (element instanceof IndependentVariable) { - IndependentVariable variable = (IndependentVariable) element; - if (variable.getExpression() instanceof ParameterExpression) { - inits.put(prefix + variable.getName(), "" + ((ParameterExpression)variable.getExpression()).getValue()); - } - } - } - return inits; - } + } + + progressMonitor.worked(1); + + if(simulationLocation != null && !canceled) { + progressMonitor.subTask("Simulate model"); + process = ModelicaManager.runModelica( + simulationLocation, + monitor, + inits + ); + ModelicaManager.printProcessOutput(process, monitor); + + Thread resultThread = new Thread() { + @Override + public void run() { + try { + process.waitFor(); + + if(!canceled) { + progressMonitor.worked(1); + progressMonitor.subTask("Read results"); + result = new SimulationResult(); + result.read(simulationLocation.outputFile); + result.readInits(simulationLocation.initFile); + result.filter(); + sysdynResult.setResult(result); + progressMonitor.worked(1); + synchronized(resultListeners) { + for(Runnable listener : resultListeners) + listener.run(); + } + setExperimentStopped(experiment); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }; + resultThread.run(); + } + if(canceled) + setExperimentStopped(experiment); + process = null; + } + + private void setExperimentStopped(Experiment experiment) { + if(experiment instanceof SysdynExperiment) { + SysdynExperiment e = (SysdynExperiment)experiment; + if(e.getState() != ExperimentState.DISPOSED) + e.simulate(false); + } + } + + private boolean hasStructureChanged(String modelText, Map inits) { + if (!modelText.equals(previousModelStructure)) + return true; + for(String key : previousImportantInits.keySet()) { + if(!inits.containsKey(key) || !previousImportantInits.get(key).equals(inits.get(key))) + return true; + } + return false; + } + + public void cancelSimulation() { + canceled = true; + if(process != null) { + process.destroy(); + } + } + + public synchronized boolean update() throws DatabaseException { + if(mapping.isDomainModified()) { + session.syncRequest(new ReadRequest() { + @Override + public void run(ReadGraph graph) throws DatabaseException { + mapping.updateRange(graph); + } + }); + return true; + } + else + return false; + } + + public SimulationResult getSimulationResult() { + return result; + } + + public SysdynResult getSysdynResult() { + return sysdynResult; + } + + public void addResultListener(Runnable listener) { + synchronized(resultListeners) { + resultListeners.add(listener); + } + } + + public void removeResultListener(Runnable listener) { + synchronized(resultListeners) { + resultListeners.add(listener); + } + } + + public void addModificationListener(Runnable listener) { + synchronized(modificationListeners) { + modificationListeners.add(listener); + } + } + + public void removeModificationListener(Runnable listener) { + synchronized(modificationListeners) { + modificationListeners.remove(listener); + } + } + + @Override + public void domainModified() { + synchronized(modificationListeners) { + for(Runnable listener : modificationListeners) + listener.run(); + } + } + + @Override + public void rangeModified() { + } + + public Configuration getConfiguration() { + return configuration; + } + + public IMapping getMapping() { + return mapping; + } + + public synchronized IElement getElement(Resource resource) { + return (IElement)mapping.get(resource); + } + + public T getService(Class clazz) { + synchronized(services) { + return clazz.cast(services.get(clazz)); + } + } + + public void addService(Class clazz, T service) { + synchronized(services) { + services.put(clazz, service); + } + } + + @Override + public IExperiment loadExperiment(ReadGraph g, Resource experiment, IExperimentActivationListener listener) { + SysdynExperiment exp = new SysdynExperiment(experiment, configurationResource); + try { + exp.init(g); + listener.onExperimentActivated(exp); + return exp; + } catch(Exception e) { + listener.onFailure(e); + return null; + } + } + + public Collection getActiveResults(ReadGraph graph) { + ArrayList results = new ArrayList(); + + try { + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + SimulationResource SIMU = SimulationResource.getInstance(graph); + Resource model = graph.getSingleObject(configurationResource, SIMU.IsConfigurationOf); + Collection experiments = graph.getObjects(model, l0.ConsistsOf); + for(Resource experiment : experiments) { + Collection experimentResults = graph.getObjects(experiment, sr.HasResult); + for(Resource result : experimentResults) { + if(graph.hasStatement(result, SIMU.IsActive)) { + SysdynResult sysdynResult = new SysdynResult( + (String) graph.getPossibleRelatedValue(result, l0.HasLabel), + (String) graph.getPossibleRelatedValue(result, sr.HasResultFile)); + results.add(sysdynResult); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + if(getSysdynResult() != null) + results.add(0, getSysdynResult() ); + + + + return results; + } + + private HashMap getInits(Configuration configuration, String prefix) { + HashMap inits = new HashMap(); + for (IElement element : configuration.getElements()) { + if (element instanceof Module) { + Module module = (Module) element; + Configuration conf = module.getType().getConfiguration(); + inits.putAll(getInits(conf, prefix + module.getName() + ".")); + } else if (element instanceof IndependentVariable) { + IndependentVariable variable = (IndependentVariable) element; + if (variable.getExpression() instanceof ParameterExpression) { + inits.put(prefix + variable.getName(), "" + ((ParameterExpression)variable.getExpression()).getValue()); + } + } + } + return inits; + } } 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 02166691..8f8a4fb7 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java @@ -11,6 +11,9 @@ *******************************************************************************/ package org.simantics.sysdyn.simulation; +import java.text.SimpleDateFormat; +import java.util.Calendar; + import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; @@ -21,34 +24,38 @@ import org.eclipse.ui.console.IConsoleManager; import org.eclipse.ui.console.MessageConsole; import org.eclipse.ui.console.MessageConsoleStream; import org.simantics.modelica.IModelicaMonitor; +import org.simantics.simulation.experiment.Experiment; import org.simantics.sysdyn.manager.SysdynModel; public class SimulationJob extends Job { SysdynModel model; + Experiment experiment; ModelicaMonitor monitor; - public SimulationJob(SysdynModel model) { + public SimulationJob(SysdynModel model, Experiment experiment) { super("Simulate " + model.getConfiguration().getName()); this.model = model; + this.experiment = experiment; this.monitor = new ModelicaMonitor(); } @Override protected IStatus run(IProgressMonitor monitor) { - monitor.beginTask("Simulate " + model.getConfiguration().getName(), 100); - this.monitor.clearConsole(); + monitor.beginTask("Simulate " + model.getConfiguration().getName(), 5); + this.monitor.message("Simulate " + model.getConfiguration().getName()); try { model.update(); - model.simulate(this.monitor, monitor); - monitor.worked(50); + model.simulate(this.monitor, monitor, experiment); } catch (Exception e) { e.printStackTrace(); + this.monitor.showConsole(); return new Status( Status.ERROR, "org.simantics.sysdyn.ui", "Simulation failed: \n" + e.getMessage()); } + this.monitor.message("\n"); monitor.done(); return Status.OK_STATUS; } @@ -79,8 +86,25 @@ public class SimulationJob extends Job { @Override public void message(String message) { + message(message, "hh:mm:ss"); + } + + /** + * Print message to a console with a specified time stamp format + * + * @param message the message to be printed + * @param timeStampFormat simpledateformat timestamp format. null if no timestamp wanted + */ + public void message(String message, String timeStampFormat) { + Calendar cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat(timeStampFormat); + String time = sdf.format(cal.getTime()); + MessageConsoleStream out = this.console.newMessageStream(); - out.println(message); + if(message.length() > 1) + out.println("[" + time +"] " + message); + if(message.contains("Error:")) + showConsole(); } public void clearConsole() { diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationScheduler.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationScheduler.java index cd048be4..534168f3 100644 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationScheduler.java +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationScheduler.java @@ -11,37 +11,28 @@ *******************************************************************************/ package org.simantics.sysdyn.simulation; +import org.simantics.simulation.experiment.Experiment; import org.simantics.sysdyn.manager.SysdynModel; public class SimulationScheduler { SysdynModel model; - + Experiment experiment; SimulationJob job; - private SimulationScheduler(SysdynModel model) { + private SimulationScheduler(SysdynModel model, Experiment experiment) { this.model = model; - this.job = new SimulationJob(model); + this.experiment = experiment; + this.job = new SimulationJob(model, experiment); } private void start() { job.schedule(); - /* - * Don't want this behavior. Use this in simulate on change or somewhere - model.addModificationListener(new Runnable() { - - @Override - public void run() { - job.schedule(); - } - - }); - */ } - public static synchronized SimulationScheduler start(SysdynModel model) { + public static synchronized SimulationScheduler start(SysdynModel model, Experiment experiment) { SimulationScheduler scheduler = model.getService(SimulationScheduler.class); if(scheduler == null) { - scheduler = new SimulationScheduler(model); + scheduler = new SimulationScheduler(model, experiment); model.addService(SimulationScheduler.class, scheduler); scheduler.start(); } else { -- 2.47.1