001/*
002 * Java Genetic Algorithm Library (jenetics-8.0.0).
003 * Copyright (c) 2007-2024 Franz Wilhelmstötter
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 *
017 * Author:
018 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
019 */
020package io.jenetics.ext.moea;
021
022import java.util.function.Function;
023import java.util.function.ToDoubleBiFunction;
024
025/**
026 * Defines the distance of two elements of a given <em>vector</em> type {@code V}.
027 * The following example creates an {@code ElementDistance} function for a
028 * {@code double[] array}:
029 * {@snippet lang="java":
030 * final ElementDistance<double[]> dist = (u, v, i) -> u[i] - v[i];
031 * }
032 *
033 * @param <V> the vector type
034 *
035 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
036 * @version 4.1
037 * @since 4.1
038 */
039@FunctionalInterface
040public interface ElementDistance<V> {
041
042        /**
043         * Calculates the distance of two vector elements at the given {@code index}.
044         * E.g.
045         * {@snippet lang="java":
046         * final ElementDistance<double[]> dist = (u, v, i) -> u[i] - v[i];
047         * }
048         *
049         * @param u the first vector
050         * @param v the second vector
051         * @param index the vector index
052         * @return the distance of the two element vectors
053         */
054        double distance(final V u, final V v, final int index);
055
056        /**
057         * Return an element distance function for the mapped type {@code T}.
058         *
059         * @param mapper the mapper function
060         * @param <T> the new distance type
061         * @return an element distance function for the mapped type {@code T}
062         */
063        default <T> ElementDistance<T>
064        map(final Function<? super T, ? extends V> mapper) {
065                return (u, v, i) -> distance(mapper.apply(u), mapper.apply(v), i);
066        }
067
068        /**
069         * Return a function which calculates the distance of two vector elements at
070         * a given {@code index}.
071         *
072         * @param index the vector index
073         * @return a function which calculates the distance of two vector elements
074         */
075        default ToDoubleBiFunction<V, V> ofIndex(final int index) {
076                return (u, v) -> distance(u, v, index);
077        }
078
079}