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

import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.BoundSaturationListener
import java.util.Map
import org.eclipse.viatra.dse.base.ThreadContext
import org.eclipse.xtend.lib.annotations.Accessors

class ThreeValuedCostObjective extends AbstractThreeValuedObjective implements BoundSaturationListener {
	@Accessors val Map<String, CostElementMatchers> matchers
	double lowerBoundHint = Double.NEGATIVE_INFINITY
	double upperBoundHint = Double.POSITIVE_INFINITY

	new(String name, Map<String, CostElementMatchers> matchers, ObjectiveKind kind, ObjectiveThreshold threshold,
		int level) {
		super(name, kind, threshold, level)
		this.matchers = matchers
	}

	override createNew() {
		// new ThreeValuedCostObjective(name, matchers, kind, threshold, level)
		throw new UnsupportedOperationException("ThreeValuedCostObjective can only be used from a single thread")
	}

	override init(ThreadContext context) {
	}

	override getRawFitness(ThreadContext context) {
		var double cost = 0
		for (matcher : matchers.values) {
			cost += matcher.weight * matcher.currentNumberOfMatches
		}
		cost
	}

	override getLowestPossibleFitness(ThreadContext threadContext) {
		var double cost = 0
		for (matcher : matchers.values) {
			if (matcher.weight >= 0) {
				cost += matcher.weight * matcher.minimumNumberOfMatches
			} else {
				cost += matcher.weight * matcher.maximumNumberOfMatches
			}
		}
		val boundWithHint = Math.max(lowerBoundHint, cost)
		if (boundWithHint > upperBoundHint) {
			throw new IllegalStateException("Inconsistent cost bounds")
		}
		boundWithHint
	}

	override getHighestPossibleFitness(ThreadContext threadContext) {
		var double cost = 0
		for (matcher : matchers.values) {
			if (matcher.weight <= 0) {
				cost += matcher.weight * matcher.minimumNumberOfMatches
			} else {
				cost += matcher.weight * matcher.maximumNumberOfMatches
			}
		}
		val boundWithHint = Math.min(upperBoundHint, cost)
		if (boundWithHint < lowerBoundHint) {
			throw new IllegalStateException("Inconsistent cost bounds")
		}
		boundWithHint
	}

	override boundsSaturated(Integer lower, Integer upper) {
		lowerBoundHint = if (lower === null) {
			Double.NEGATIVE_INFINITY
		} else {
			lower
		}
		upperBoundHint = if (upper === null) {
			Double.POSITIVE_INFINITY
		} else {
			upper
		}
		println('''Bounds saturated: «lower»..«upper»''')
	}
}