public override IOperation InstrumentedApply() { var trees = SymbolicExpressionTreeParameter.ActualValue; var similarityMatrix = SymbolicExpressionTreeHash.ComputeSimilarityMatrix(trees, false, StrictSimilarity); DoubleValue averageSimilarity(int i) => new DoubleValue(Enumerable.Range(0, trees.Length).Where(j => i != j).Average(j => similarityMatrix[i, j])); AverageSimilarityParameter.ActualValue = new ItemArray <DoubleValue>(Enumerable.Range(0, trees.Length).Select(averageSimilarity)); return(base.InstrumentedApply()); }
protected override IScope[] Select(List <IScope> scopes) { var w = SimilarityWeight; if (w.IsAlmost(0)) { ApplyInnerSelector(); return(CurrentScope.SubScopes[1].SubScopes.ToArray()); // return selected individuals (selectors create two sub-scopes with remaining and selected) } var trees = SymbolicExpressionTreeParameter.ActualValue; var qualities = QualityParameter.ActualValue; // calculate average similarity for each tree var similarityMatrix = SymbolicExpressionTreeHash.ComputeSimilarityMatrix(trees, simplify: false, strict: StrictSimilarity); var similarities = new double[trees.Length]; for (int i = 0; i < trees.Length; ++i) { for (int j = 0; j < trees.Length; ++j) { if (i != j) { similarities[i] += similarityMatrix[i, j]; } } similarities[i] /= (trees.Length - 1); } var v = 1 - w; var maximization = MaximizationParameter.ActualValue.Value; var diversities = new ItemArray <DoubleValue>(trees.Length); for (int i = 0; i < trees.Length; ++i) { var q = qualities[i].Value; var d = 1 - similarities[i]; // average distance // assuming both q and d are in the interval [0, 1] var value = maximization ? (v * q) + (w * d) : (v * q) - (w * d); diversities[i] = new DoubleValue(value); } Selector.QualityParameter.ActualName = "Diversity"; DiversityParameter.ActualValue = diversities; ApplyInnerSelector(); // apply inner selector return(CurrentScope.SubScopes[1].SubScopes.ToArray()); }