21fcf2c268847704ad00375f60dcbe525dca309b
[simantics/platform.git] / bundles / org.simantics.simulation / src / org / simantics / simulation / project / ExperimentRuns.java
1 package org.simantics.simulation.project;
2
3 import java.util.concurrent.atomic.AtomicReference;
4 import java.util.function.Consumer;
5
6 import org.simantics.databoard.Bindings;
7 import org.simantics.db.Resource;
8 import org.simantics.db.Session;
9 import org.simantics.db.VirtualGraph;
10 import org.simantics.db.WriteGraph;
11 import org.simantics.db.common.request.WriteRequest;
12 import org.simantics.db.common.request.WriteResultRequest;
13 import org.simantics.db.common.utils.NameUtils;
14 import org.simantics.db.exception.DatabaseException;
15 import org.simantics.db.service.VirtualGraphSupport;
16 import org.simantics.layer0.Layer0;
17 import org.simantics.scl.runtime.function.Function2;
18 import org.simantics.simulation.experiment.ExperimentState;
19 import org.simantics.simulation.experiment.IExperiment;
20 import org.simantics.simulation.experiment.IExperimentListener;
21 import org.simantics.simulation.ontology.SimulationResource;
22 import org.simantics.utils.ui.ErrorLogger;
23
24 /**
25  * Facade for handling experiment run modeling and experiment activation
26  * related tasks.
27  * 
28  * @author Tuukka Lehtonen
29  */
30 public class ExperimentRuns {
31
32     /**
33      * @param session
34      * @param experimentResource
35      * @param experiment
36      * @param listener
37      */
38     public static void createRun(Session session, Resource experimentResource, IExperiment experiment,
39             IExperimentActivationListener listener, Consumer<Resource> successCallback) {
40         VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);
41         createRun(session, support.getWorkspacePersistent("experiments"), experimentResource, experiment, listener, successCallback);
42     }
43
44     /**
45      * Create new experiment run in a selected virtual graph.
46      * 
47      * @param session
48      * @param graph
49      * @param experimentResource
50      * @param experiment
51      * @param listener
52      */
53     public static void createRun(final Session session, VirtualGraph graph, final Resource experimentResource,
54             final IExperiment experiment, final IExperimentActivationListener listener,
55             final Consumer<Resource> successCallback)
56     {
57         createRun(session, graph, experimentResource, experiment, SimulationResource.URIs.Run, listener, successCallback);
58     }
59
60     public static void createRun(final Session session, VirtualGraph vg, final Resource experimentResource,
61             final IExperiment experiment, final String experimentRunTypeURI,
62             final IExperimentActivationListener listener, final Consumer<Resource> successCallback)
63     {
64         createRun(session, vg, experimentResource, experiment, experimentRunTypeURI, listener, null, successCallback);
65     }
66
67     /**
68      * Create new experiment run in a selected virtual graph.
69      * 
70      * @param session
71      * @param vg
72      * @param experimentResource
73      * @param experiment
74      * @param experimentRunTypeURI
75      * @param listener
76      * @param successCallback if non-null invoked with the created run resource
77      *        as an argument, just before invoking
78      *        listener.onExperimentActivated(experiment)
79      */
80     public static void createRun(final Session session, VirtualGraph vg, final Resource experimentResource,
81             final IExperiment experiment, final String experimentRunTypeURI,
82             final IExperimentActivationListener listener,
83             final Function2<WriteGraph, Resource, Object> externalWrite,
84             final Consumer<Resource> successCallback)
85     {
86         final AtomicReference<Resource> run = new AtomicReference<>();
87         session.asyncRequest(new WriteRequest(vg) {
88             @Override
89             public void perform(WriteGraph graph) throws DatabaseException {
90 //                System.out.println("ExperimentActivator " + experimentResource + " " + experiment.getIdentifier());
91                 run.set( createRun(graph, experimentResource, experiment, experimentRunTypeURI, externalWrite) );
92             }
93         }, e -> {
94             if (e != null) {
95                 if (listener != null)
96                     listener.onFailure(e);
97                 else
98                     ErrorLogger.defaultLogError(e);
99             } else {
100                 attachStateListener(session, experiment, run.get());
101                 if (successCallback != null)
102                     successCallback.accept(run.get());
103                 if (listener != null)
104                     listener.onExperimentActivated(experiment);
105             }
106         });
107     }
108
109     /**
110      * Create new experiment run in a selected virtual graph.
111      * 
112      * @param session
113      * @param vg
114      * @param experimentResource
115      * @param experiment
116      * @param experimentRunTypeURI
117      * @param listener
118      * @param successCallback if non-null invoked with the created run resource
119      *        as an argument, just before invoking
120      *        listener.onExperimentActivated(experiment)
121      */
122     public static Resource createRun(WriteGraph graph,
123             VirtualGraph vg, 
124             Resource experimentResource,
125             IExperiment experiment,
126             String experimentRunTypeURI,
127             Function2<WriteGraph, Resource, Object> externalWrite)
128                     throws DatabaseException
129     {
130         return graph.syncRequest(new WriteResultRequest<Resource>(vg) {
131             @Override
132             public Resource perform(WriteGraph graph) throws DatabaseException {
133                 return createRun(graph, experimentResource, experiment, experimentRunTypeURI, externalWrite);
134             }
135         });
136     }
137
138     public static Resource createRun(WriteGraph graph,
139             Resource experimentResource,
140             IExperiment experiment,
141             String experimentRunTypeURI,
142             Function2<WriteGraph, Resource, Object> externalWrite)
143                     throws DatabaseException
144     {
145         Layer0 L0 = Layer0.getInstance(graph);
146         SimulationResource SIMU = SimulationResource.getInstance(graph);
147
148         Resource run = graph.newResource();
149         String label = NameUtils.findFreshLabel(graph, "Experiment", experimentResource);
150         graph.claim(run, L0.InstanceOf, null, graph.getResource(experimentRunTypeURI));
151         graph.addLiteral(run, L0.HasName, L0.NameOf, L0.String, experiment.getIdentifier(), Bindings.STRING);
152         graph.addLiteral(run, L0.HasLabel, L0.HasLabel_Inverse, L0.String, label, Bindings.STRING);
153         graph.addLiteral(run, SIMU.HasActivationTime, SIMU.HasActivationTime_Inverse, L0.Long, System.currentTimeMillis(), Bindings.LONG);
154         graph.claim(experimentResource, L0.ConsistsOf, L0.PartOf, run);
155
156         markRunActive(graph, run, externalWrite);
157
158         return run;
159     }
160
161     /**
162      * Mark the run active in the transient virtual graph.
163      * 
164      * @param graph
165      * @param run
166      * @param externalWrite 
167      * @throws DatabaseException
168      */
169     private static void markRunActive(
170             WriteGraph graph,
171             Resource run,
172             Function2<WriteGraph, Resource, Object> externalWrite)
173                     throws DatabaseException
174     {
175         SimulationResource SIMU = SimulationResource.getInstance(graph);
176         VirtualGraph runtime = graph.getService(VirtualGraph.class);
177         graph.syncRequest(new WriteRequest(runtime) {
178             @Override
179             public void perform(WriteGraph graph) throws DatabaseException {
180                 graph.claim(run, SIMU.IsActive, run);
181                 if(externalWrite != null)
182                     externalWrite.apply(graph, run);
183             }
184         });
185     }
186
187     /**
188      * Add listener for tracking run IsActive state in the graph.
189      * 
190      * @param session
191      * @param experiment
192      * @param run
193      */
194     private static void attachStateListener(final Session session, IExperiment experiment, final Resource run) {
195         experiment.addListener(new IExperimentListener() {
196             @Override
197             public void stateChanged(ExperimentState state) {
198                 if (state == ExperimentState.DISPOSED) {
199                     VirtualGraph runtime = session.getService(VirtualGraph.class);
200                     session.asyncRequest(new WriteRequest(runtime) {
201                         @Override
202                         public void perform(WriteGraph graph) throws DatabaseException {
203                             SimulationResource SIMU = SimulationResource.getInstance(graph);
204                             graph.denyStatement(run, SIMU.IsActive, run);
205                         }
206                     }, e -> {
207                         if (e != null)
208                             ErrorLogger.defaultLogError(e);
209                     });
210                 }
211             }
212         });
213     }
214
215 }