aboutsummaryrefslogtreecommitdiffstats
path: root/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/solutionstore/SolutionStore.java
blob: 578ae27748570ecb98995ed7d02801632b9a9890 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*******************************************************************************
 * Copyright (c) 2010-2016, Andras Szabolcs Nagy, Zoltan Ujhelyi and Daniel Varro
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-v20.html.
 * 
 * SPDX-License-Identifier: EPL-2.0
 *******************************************************************************/
package org.eclipse.viatra.dse.solutionstore;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.viatra.dse.api.DSEException;
import org.eclipse.viatra.dse.api.Solution;
import org.eclipse.viatra.dse.api.SolutionTrajectory;
import org.eclipse.viatra.dse.base.DesignSpaceManager;
import org.eclipse.viatra.dse.base.ThreadContext;
import org.eclipse.viatra.dse.objectives.Fitness;
import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper;
import org.eclipse.viatra.dse.statecode.IStateCoderFactory;
import org.eclipse.viatra.dse.util.EMFHelper;
import org.eclipse.viatra.query.runtime.exception.ViatraQueryException;

/**
 * 
 * @author Andras Szabolcs Nagy
 *
 */
public class SolutionStore {

    public interface ISolutionSaver {
        void setSolutionsCollection(Map<Object, Solution> solutions);
        boolean saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory);
    }

    public interface IEnoughSolutions extends ISolutionFoundHandler {
        boolean enoughSolutions();
    }

    public static class ANumberOfEnoughSolutions implements IEnoughSolutions {

        private final AtomicInteger foundSolutions;
        private final AtomicBoolean foundEnoughSolutions;

        public ANumberOfEnoughSolutions(int number) {
            foundSolutions = new AtomicInteger(number);
            foundEnoughSolutions = new AtomicBoolean(false);
        }

        @Override
        public boolean enoughSolutions() {
            return foundEnoughSolutions.get();
        }

        @Override
        public void solutionFound(ThreadContext context, SolutionTrajectory trajectory) {
            int solutionsToFind = foundSolutions.decrementAndGet();
            if (solutionsToFind == 0) {
                foundEnoughSolutions.set(true);
            }
        }

        @Override
        public void solutionTriedToSave(ThreadContext context, SolutionTrajectory trajectory) {
        }
    }

    public static class SimpleSolutionSaver implements ISolutionSaver {

        private Map<Object, Solution> solutions;

        @Override
        public void setSolutionsCollection(Map<Object, Solution> solutions) {
            this.solutions = solutions;
        }

        @Override
        public boolean saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) {
            Solution solution = solutions.get(id);
            if (solution != null) {
                if (solution.getTrajectories().contains(solutionTrajectory)) {
                    return false;
                } else {
                    solution.addTrajectory(solutionTrajectory);
                    solutionTrajectory.setSolution(solution);
                }
            } else {
                solution = new Solution(id, solutionTrajectory);
                solutions.put(id, solution);
                solutionTrajectory.setSolution(solution);
            }
            return true;
        }
    }

    public static class BestSolutionSaver implements ISolutionSaver {

        private Map<Object, Solution> solutions;
        private Map<SolutionTrajectory, Fitness> trajectories = new HashMap<>();

        @Override
        public void setSolutionsCollection(Map<Object, Solution> solutions) {
            this.solutions = solutions;
        }

        @Override
        public boolean saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) {

            Fitness lastFitness = context.getLastFitness();
            ObjectiveComparatorHelper comparatorHelper = context.getObjectiveComparatorHelper();

            List<SolutionTrajectory> dominatedTrajectories = new ArrayList<>();

            for (Entry<SolutionTrajectory, Fitness> entry : trajectories.entrySet()) {
                int isLastFitnessBetter = comparatorHelper.compare(lastFitness, entry.getValue());
                if (isLastFitnessBetter < 0) {
                    return false;
                }
                if (isLastFitnessBetter > 0) {
                    dominatedTrajectories.add(entry.getKey());
                }
            }

            boolean solutionSaved = false;

            Solution solution = solutions.get(id);
            if (solution != null) {
                if (!solution.getTrajectories().contains(solutionTrajectory)) {
                    solution.addTrajectory(solutionTrajectory);
                    solutionTrajectory.setSolution(solution);
                    solutionSaved = true;
                    trajectories.put(solutionTrajectory, lastFitness);
                }
            } else {
                solution = new Solution(id, solutionTrajectory);
                solutions.put(id, solution);
                solutionTrajectory.setSolution(solution);
                solutionSaved = true;
                trajectories.put(solutionTrajectory, lastFitness);
            }

            for (SolutionTrajectory st : dominatedTrajectories) {
                trajectories.remove(st);
                Solution s = st.getSolution();
                if (!s.getTrajectories().remove(st)) {
                    throw new DSEException("Should not happen.");
                }
                if (s.getTrajectories().isEmpty()) {
                    Object stateCode = s.getStateCode();
                    solutions.remove(stateCode);
                }
            }

            return solutionSaved;
        }

    }

    protected boolean acceptOnlyGoalSolutions = true;
    protected final Map<Object, Solution> solutions = new HashMap<Object, Solution>();
    protected ISolutionSaver solutionSaver = new SimpleSolutionSaver();
    protected List<ISolutionFoundHandler> solutionFoundHandlers = new ArrayList<ISolutionFoundHandler>(1);

    protected final IEnoughSolutions enoughSolutions;

    public SolutionStore() {
        this(new IEnoughSolutions() {
            @Override
            public void solutionFound(ThreadContext context, SolutionTrajectory trajectory) {
            }

            @Override
            public boolean enoughSolutions() {
                return false;
            }

            @Override
            public void solutionTriedToSave(ThreadContext context, SolutionTrajectory trajectory) {
            }
        });
    }

    public SolutionStore(int numOfSolutionsToFind) {
        this(new ANumberOfEnoughSolutions(numOfSolutionsToFind));
    }

    public SolutionStore(IEnoughSolutions enoughSolutionsImpl) {
        enoughSolutions = enoughSolutionsImpl;
    }

    public synchronized void newSolution(ThreadContext context) {
        solutionSaver.setSolutionsCollection(solutions);
        Fitness fitness = context.getLastFitness();
        DesignSpaceManager dsm = context.getDesignSpaceManager();
        Object id = dsm.getCurrentState();
        IStateCoderFactory stateCoderFactory = context.getGlobalContext().getStateCoderFactory();
        SolutionTrajectory solutionTrajectory = dsm.getTrajectoryInfo().createSolutionTrajectory(stateCoderFactory, context.getDesignSpaceManager());
        solutionTrajectory.setFitness(fitness);

        if (acceptOnlyGoalSolutions && !fitness.isSatisifiesHardObjectives()) {
            unsavedSolutionCallbacks(context, solutionTrajectory);
            return;
        }

        boolean solutionSaved = solutionSaver.saveSolution(context, id, solutionTrajectory);

        if (solutionSaved) {
            enoughSolutions.solutionFound(context, solutionTrajectory);

            savedSolutionCallbacks(context, solutionTrajectory);

            if (enoughSolutions.enoughSolutions()) {
                context.getGlobalContext().stopAllThreads();
            }
        } else {
            unsavedSolutionCallbacks(context, solutionTrajectory);
        }
    }

    private void unsavedSolutionCallbacks(ThreadContext context, SolutionTrajectory solutionTrajectory) {
        for (ISolutionFoundHandler handler : solutionFoundHandlers) {
            handler.solutionTriedToSave(context, solutionTrajectory);
        }
    }

    private void savedSolutionCallbacks(ThreadContext context, SolutionTrajectory solutionTrajectory) {
        for (ISolutionFoundHandler handler : solutionFoundHandlers) {
            handler.solutionFound(context, solutionTrajectory);
        }
    }

    public synchronized Collection<Solution> getSolutions() {
        return solutions.values();
    }

    public synchronized void registerSolutionFoundHandler(ISolutionFoundHandler handler) {
        if (solutionFoundHandlers == null) {
            solutionFoundHandlers = new ArrayList<ISolutionFoundHandler>(1);
        }
        solutionFoundHandlers.add(handler);
    }

    public SolutionStore logSolutionsWhenFound() {
        registerSolutionFoundHandler(new LogSolutionHandler());
        Logger.getLogger(LogSolutionHandler.class).setLevel(Level.INFO);
        return this;
    }

    public SolutionStore saveModelWhenFound() {
        registerSolutionFoundHandler(new ModelSaverSolutionFoundHandler());
        return this;
    }

    public SolutionStore saveModelWhenFound(String extension) {
        registerSolutionFoundHandler(new ModelSaverSolutionFoundHandler(extension));
        return this;
    }

    public SolutionStore saveModelWhenFound(String prefix, String extension) {
        registerSolutionFoundHandler(new ModelSaverSolutionFoundHandler(prefix, extension));
        return this;
    }

    public SolutionStore saveModelWhenFound(ISolutionNameProvider solutionNameProvider) {
        registerSolutionFoundHandler(new ModelSaverSolutionFoundHandler(solutionNameProvider));
        return this;
    }

    public SolutionStore acceptGoalSolutionsOnly() {
        acceptOnlyGoalSolutions = true;
        return this;
    }

    public SolutionStore acceptAnySolutions() {
        acceptOnlyGoalSolutions = false;
        return this;
    }

    public SolutionStore withSolutionSaver(ISolutionSaver solutionSaver) {
        this.solutionSaver = solutionSaver;
        return this;
    }

    public SolutionStore storeBestSolutionsOnly() {
        this.solutionSaver = new BestSolutionSaver();
        return this;
    }

    public void saveModels(Notifier model, ISolutionNameProvider solutionNameProvider) {
        try {
            for (Solution solution : solutions.values()) {
                SolutionTrajectory trajectory = solution.getArbitraryTrajectory();
                trajectory.doTransformationUndoable(model);
                EMFHelper.saveModel(model, solutionNameProvider.getName());
                trajectory.undoTransformation();
            }
        } catch (ViatraQueryException e) {
            Logger.getLogger(SolutionStore.class).error("Exception happened during model saving.", e);
        }
    }
}