1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
5 |
|
---|
6 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
|
---|
7 | public static class IntervalUtil {
|
---|
8 | public static double IntervalConstraintViolation(
|
---|
9 | IntervalConstraint constraint, IBoundsEstimator estimator, IntervalCollection intervalCollection,
|
---|
10 | ISymbolicExpressionTree solution) {
|
---|
11 | var variableRanges = intervalCollection.GetReadonlyDictionary();
|
---|
12 |
|
---|
13 | if (constraint.Variable != null && !variableRanges.ContainsKey(constraint.Variable)) {
|
---|
14 | throw new ArgumentException(
|
---|
15 | $"The given variable {constraint.Variable} in the constraint does not exist in the model.",
|
---|
16 | nameof(IntervalConstraintsParser));
|
---|
17 | }
|
---|
18 |
|
---|
19 | //Create new variable ranges for defined regions
|
---|
20 | var regionRanges = new IntervalCollection();
|
---|
21 | foreach (var kvp in variableRanges) {
|
---|
22 | if (kvp.Key != constraint.Target && constraint.Regions.GetReadonlyDictionary().TryGetValue(kvp.Key, out var val)) {
|
---|
23 | regionRanges.AddInterval(kvp.Key, val);
|
---|
24 | } else {
|
---|
25 | regionRanges.AddInterval(kvp.Key, kvp.Value);
|
---|
26 | }
|
---|
27 | }
|
---|
28 |
|
---|
29 | var error = 0.0;
|
---|
30 | if (!constraint.IsDerivative) {
|
---|
31 | error = estimator.CheckConstraint(solution, regionRanges, constraint);
|
---|
32 | } else {
|
---|
33 | var tree = solution;
|
---|
34 | for (var i = 0; i < constraint.NumberOfDerivations; ++i) {
|
---|
35 | if (!estimator.IsCompatible(tree) || !DerivativeCalculator.IsCompatible(tree)) {
|
---|
36 | throw new ArgumentException("Cube, Root, Power symbols are not supported.");
|
---|
37 | }
|
---|
38 |
|
---|
39 | tree = DerivativeCalculator.Derive(tree, constraint.Variable);
|
---|
40 | }
|
---|
41 |
|
---|
42 | error = estimator.CheckConstraint(tree, regionRanges, constraint);
|
---|
43 | }
|
---|
44 |
|
---|
45 | return error;
|
---|
46 | }
|
---|
47 |
|
---|
48 | public static IEnumerable<double> IntervalConstraintsViolation(
|
---|
49 | IEnumerable<IntervalConstraint> constraints, IBoundsEstimator estimator, IntervalCollection intervalCollection,
|
---|
50 | ISymbolicExpressionTree solution) {
|
---|
51 | return constraints.Select(constraint => IntervalConstraintViolation(constraint, estimator, intervalCollection, solution)).ToList();
|
---|
52 | }
|
---|
53 | }
|
---|
54 | } |
---|