ElementDistance.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-5.1.0).
03  * Copyright (c) 2007-2019 Franz Wilhelmstötter
04  *
05  * Licensed under the Apache License, Version 2.0 (the "License");
06  * you may not use this file except in compliance with the License.
07  * You may obtain a copy of the License at
08  *
09  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * Author:
18  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19  */
20 package io.jenetics.ext.moea;
21 
22 import java.util.function.Function;
23 import java.util.function.ToDoubleBiFunction;
24 
25 /**
26  * Defines the distance of two elements of a given <em>vector</em> type {@code V}.
27  * The following example creates an {@code ElementDistance} function for a
28  * {@code double[] array}:
29  <pre>{@code
30  * final ElementDistance<double[]> dist = (u, v, i) -> u[i] - v[i];
31  * }</pre>
32  *
33  @param <V> the vector type
34  *
35  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
36  @version 4.1
37  @since 4.1
38  */
39 @FunctionalInterface
40 public interface ElementDistance<V> {
41 
42     /**
43      * Calculates the distance of two vector elements at the given {@code index}.
44      * E.g.
45      <pre>{@code
46      * final ElementDistance<double[]> dist = (u, v, i) -> u[i] - v[i];
47      * }</pre>
48      *
49      @param u the first vector
50      @param v the second vector
51      @param index the vector index
52      @return the distance of the two element vectors
53      */
54     public double distance(final V u, final V v, final int index);
55 
56     /**
57      * Return an element distance function for the mapped type {@code T}.
58      *
59      @param mapper the mapper function
60      @param <T> the new distance type
61      @return an element distance function for the mapped type {@code T}
62      */
63     public default <T> ElementDistance<T>
64     map(final Function<? super T, ? extends V> mapper) {
65         return (u, v, i-> distance(mapper.apply(u), mapper.apply(v), i);
66     }
67 
68     /**
69      * Return a function which calculates the distance of two vector elements at
70      * a given {@code index}.
71      *
72      @param index the vector index
73      @return a function which calculates the distance of two vector elements
74      */
75     public default ToDoubleBiFunction<V, V> ofIndex(final int index) {
76         return (u, v-> distance(u, v, index);
77     }
78 
79 }