using System; using System.Collections.Generic; using System.Linq; using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; namespace HeuristicLab.Problems.DataAnalysis.Symbolic { public static class IntervalUtil { public static double IntervalConstraintViolation( IntervalConstraint constraint, IBoundsEstimator estimator, IntervalCollection intervalCollection, ISymbolicExpressionTree solution) { var variableRanges = intervalCollection.GetReadonlyDictionary(); if (constraint.Variable != null && !variableRanges.ContainsKey(constraint.Variable)) { throw new ArgumentException( $"The given variable {constraint.Variable} in the constraint does not exist in the model.", nameof(IntervalConstraintsParser)); } //Create new variable ranges for defined regions var regionRanges = new IntervalCollection(); foreach (var kvp in variableRanges) { if (kvp.Key != constraint.Target && constraint.Regions.GetReadonlyDictionary().TryGetValue(kvp.Key, out var val)) { regionRanges.AddInterval(kvp.Key, val); } else { regionRanges.AddInterval(kvp.Key, kvp.Value); } } var error = 0.0; if (!constraint.IsDerivative) { error = estimator.CheckConstraint(solution, regionRanges, constraint); } else { var tree = solution; for (var i = 0; i < constraint.NumberOfDerivations; ++i) { if (!estimator.IsCompatible(tree) || !DerivativeCalculator.IsCompatible(tree)) { throw new ArgumentException("Cube, Root, Power symbols are not supported."); } tree = DerivativeCalculator.Derive(tree, constraint.Variable); } error = estimator.CheckConstraint(tree, regionRanges, constraint); } return error; } public static IEnumerable IntervalConstraintsViolation( IEnumerable constraints, IBoundsEstimator estimator, IntervalCollection intervalCollection, ISymbolicExpressionTree solution) { return constraints.Select(constraint => IntervalConstraintViolation(constraint, estimator, intervalCollection, solution)).ToList(); } } }