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

import org.eclipse.viatra.dse.base.ThreadContext
import org.eclipse.viatra.query.runtime.api.IPatternMatch
import org.eclipse.viatra.query.runtime.api.IQuerySpecification
import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher

class QueryBasedObjective extends DirectionalThresholdObjective {
	val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> querySpecification
	ViatraQueryMatcher<? extends IPatternMatch> matcher

	new(IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> querySpecification,
		ObjectiveKind kind, ObjectiveThreshold threshold, int level) {
		super(querySpecification.simpleName + " objective", kind, threshold, level)
		if (querySpecification.parameters.size != 1) {
			throw new IllegalArgumentException("Objective query must have a single parameter")
		}
		this.querySpecification = querySpecification
	}

	override createNew() {
		new QueryBasedObjective(querySpecification, kind, threshold, level)
	}

	override init(ThreadContext context) {
		matcher = querySpecification.getMatcher(context.queryEngine)
	}

	override protected getRawFitness(ThreadContext context) {
		val iterator = matcher.allMatches.iterator
		if (!iterator.hasNext) {
			return invalidValue
		}
		val value = iterator.next.get(0)
		if (iterator.hasNext) {
			throw new IllegalStateException("Multiple matches for objective query")
		}
		if (value instanceof Number) {
			value.doubleValue
		} else {
			throw new IllegalStateException("Objective value is not an instance of Number")
		}
	}

	private def getInvalidValue() {
		kind.invalidValue
	}
}