aboutsummaryrefslogtreecommitdiffstats
path: root/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasoner.xtend
blob: dfd8ca1a81f7d7bfbc14d49964138b9a43890feb (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
package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner

import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel
import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner
import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasonerException
import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicSolverConfiguration
import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LogiclanguagePackage
import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage
import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicresultFactory
import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult
import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethodProvider
import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ScopePropagator
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.PartialInterpretationInitialiser
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.IdentifierBasedStateCoderFactory
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedStateCoderFactory
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BestFirstStrategyForModelGeneration
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ModelGenerationCompositeObjective
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PartialModelAsLogicInterpretation
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ScopeObjective
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.UnfinishedMultiplicityObjective
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.UnfinishedWFObjective
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.WF2ObjectiveConverter
import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace
import java.util.List
import java.util.Map
import org.eclipse.emf.ecore.EObject
import org.eclipse.viatra.dse.api.DesignSpaceExplorer
import org.eclipse.viatra.dse.api.DesignSpaceExplorer.DseLoggingLevel
import org.eclipse.viatra.dse.solutionstore.SolutionStore
import org.eclipse.viatra.dse.statecode.IStateCoderFactory

class ViatraReasoner extends LogicReasoner{
	val PartialInterpretationInitialiser initialiser = new PartialInterpretationInitialiser()
	val ModelGenerationMethodProvider modelGenerationMethodProvider = new ModelGenerationMethodProvider
	val extension LogicresultFactory factory = LogicresultFactory.eINSTANCE	
	val WF2ObjectiveConverter wf2ObjectiveConverter = new WF2ObjectiveConverter
	
	
	override solve(LogicProblem problem, LogicSolverConfiguration configuration, ReasonerWorkspace workspace) throws LogicReasonerException {
		val viatraConfig = configuration.asConfig
		
		if(viatraConfig.debugCongiguration.logging) {
			DesignSpaceExplorer.turnOnLogging(DseLoggingLevel.VERBOSE_FULL)
		} else {
			DesignSpaceExplorer.turnOnLogging(DseLoggingLevel.WARN)
		}
		
		val DesignSpaceExplorer dse = new DesignSpaceExplorer();
		
		dse.addMetaModelPackage(LogiclanguagePackage.eINSTANCE)
		dse.addMetaModelPackage(LogicproblemPackage.eINSTANCE)
		dse.addMetaModelPackage(PartialinterpretationPackage.eINSTANCE)
		
		val transformationStartTime = System.nanoTime
		
		
		
		val emptySolution = initialiser.initialisePartialInterpretation(problem,viatraConfig.typeScopes).output
		if((viatraConfig.documentationLevel == DocumentationLevel::FULL || viatraConfig.documentationLevel == DocumentationLevel::NORMAL) && workspace !== null) {
			workspace.writeModel(emptySolution,"init.partialmodel")
		} 
		emptySolution.problemConainer = problem
		
		val ScopePropagator scopePropagator = new ScopePropagator(emptySolution)
		scopePropagator.propagateAllScopeConstraints		
		
		val method = modelGenerationMethodProvider.createModelGenerationMethod(
			problem,
			emptySolution,
			workspace,
			viatraConfig.nameNewElements,
			viatraConfig.typeInferenceMethod,
			scopePropagator,
			viatraConfig.documentationLevel
		)
		
		dse.addObjective(new ModelGenerationCompositeObjective(
			new ScopeObjective,
			method.unfinishedMultiplicities.map[new UnfinishedMultiplicityObjective(it)],
			new UnfinishedWFObjective(method.unfinishedWF)
		))

		dse.addGlobalConstraint(wf2ObjectiveConverter.createInvalidationObjective(method.invalidWF))
		for(additionalConstraint : viatraConfig.searchSpaceConstraints.additionalGlobalConstraints) {
			dse.addGlobalConstraint(additionalConstraint.apply(method))
		}
		
		dse.setInitialModel(emptySolution,false)
		
		val IStateCoderFactory statecoder = if(viatraConfig.stateCoderStrategy == StateCoderStrategy.Neighbourhood) {
			new NeighbourhoodBasedStateCoderFactory
		} else {
			new IdentifierBasedStateCoderFactory
		}
		dse.stateCoderFactory = statecoder
		
		dse.maxNumberOfThreads = 1
		
		val solutionStore =  new SolutionStore(configuration.solutionScope.numberOfRequiredSolution)
		dse.solutionStore = solutionStore
		
		for(rule : method.relationRefinementRules) {
			dse.addTransformationRule(rule)
		}
		for(rule : method.objectRefinementRules) {
			dse.addTransformationRule(rule)
		}
		
		val strategy = new BestFirstStrategyForModelGeneration(workspace,viatraConfig,method)
		viatraConfig.progressMonitor.workedForwardTransformation
		
		val transformationTime = System.nanoTime - transformationStartTime
		val solverStartTime = System.nanoTime
		
		var boolean stoppedByTimeout
		var boolean stoppedByException
		try{
			stoppedByTimeout = dse.startExplorationWithTimeout(strategy,configuration.runtimeLimit*1000);
			stoppedByException = false
		} catch (NullPointerException npe) {
			stoppedByTimeout = false
			stoppedByException = true
		}
		val solverTime = System.nanoTime - solverStartTime
		viatraConfig.progressMonitor.workedSearchFinished
		
		//additionalMatches = strategy.solutionStoreWithCopy.additionalMatches
		val statistics = createStatistics => [
			//it.solverTime = viatraConfig.runtimeLimit
			it.solverTime = (solverTime/1000000) as int
			it.transformationTime = (transformationTime/1000000) as int
			for(x : 0..<strategy.solutionStoreWithCopy.allRuntimes.size) {
				it.entries += createIntStatisticEntry => [
					it.name = '''_Solution«x»FoundAt'''
					it.value = (strategy.solutionStoreWithCopy.allRuntimes.get(x)/1000000) as int
				]
			}
			it.entries += createIntStatisticEntry => [
				it.name = "TransformationExecutionTime" it.value = (method.statistics.transformationExecutionTime/1000000) as int
			]
			it.entries += createIntStatisticEntry => [
				it.name = "TypeAnalysisTime" it.value = (method.statistics.PreliminaryTypeAnalisisTime/1000000) as int
			]
			it.entries += createIntStatisticEntry => [
				it.name = "StateCoderTime" it.value = (statecoder.runtime/1000000) as int
			]
			it.entries += createIntStatisticEntry => [
				it.name = "StateCoderFailCount" it.value = strategy.numberOfStatecoderFail
			]
			it.entries += createIntStatisticEntry => [
				it.name = "SolutionCopyTime" it.value = (strategy.solutionStoreWithCopy.sumRuntime/1000000) as int
			]
			if(strategy.solutionStoreWithDiversityDescriptor.isActive) {
				it.entries += createIntStatisticEntry => [
					it.name = "SolutionDiversityCheckTime" it.value = (strategy.solutionStoreWithDiversityDescriptor.sumRuntime/1000000) as int
				]
				it.entries += createRealStatisticEntry => [
					it.name = "SolutionDiversitySuccessRate" it.value = strategy.solutionStoreWithDiversityDescriptor.successRate
				]
			}
		]
		
		viatraConfig.progressMonitor.workedBackwardTransformationFinished
		
		if(stoppedByTimeout) {
			return createInsuficientResourcesResult=>[
				it.problem = problem
				it.resourceName="time"
				it.statistics = statistics
			]
		} else {
			if(solutionStore.solutions.empty) {
				return createInconsistencyResult => [
					it.problem = problem
					it.statistics = statistics
				]
			} else {
				return createModelResult => [
					it.problem = problem
					it.trace = strategy.solutionStoreWithCopy.copyTraces
					it.representation += strategy.solutionStoreWithCopy.solutions
					it.statistics = statistics
				]
			}
		}
	}

    private def dispatch long runtime(NeighbourhoodBasedStateCoderFactory sc) {
        sc.sumStatecoderRuntime
    }

    private def dispatch long runtime(IdentifierBasedStateCoderFactory sc) {
        sc.sumStatecoderRuntime
    }

	override getInterpretations(ModelResult modelResult) {
		val indexes = 0..<modelResult.representation.size
		val traces = modelResult.trace as List<Map<EObject, EObject>>;
		val res = indexes.map[i | new PartialModelAsLogicInterpretation(modelResult.representation.get(i) as PartialInterpretation,traces.get(i))].toList
		return res
	}
	
	private def ViatraReasonerConfiguration asConfig(LogicSolverConfiguration configuration) {
		if(configuration instanceof ViatraReasonerConfiguration) {
			return configuration
		} else throw new IllegalArgumentException('''Wrong configuration. Expected: «ViatraReasonerConfiguration.name», but got: «configuration.class.name»"''')
	}
}