01 /*
02 * Java Genetic Algorithm Library (jenetics-7.1.1).
03 * Copyright (c) 2007-2022 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 static java.lang.String.format;
23 import static java.util.Objects.requireNonNull;
24 import static io.jenetics.ext.moea.Vecs.requireVecLength;
25 import static io.jenetics.ext.moea.Vecs.toFlags;
26
27 import java.util.Comparator;
28 import java.util.List;
29
30 import io.jenetics.Optimize;
31
32 /**
33 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
34 * @version 5.2
35 * @since 5.2
36 */
37 final class GeneralObjectVecFactory<T> implements VecFactory<T[]> {
38 private final boolean[] _maximisations;
39 private final Comparator<? super T> _comp;
40 private final ElementDistance<T[]> _dist;
41
42 private final ElementComparator<T[]> _comparator = this::cmp;
43 private final ElementDistance<T[]> _distance = this::dst;
44 private final Comparator<T[]> _dominance = this::dom;
45
46 GeneralObjectVecFactory(
47 final Comparator<? super T> comparator,
48 final ElementDistance<T[]> distance,
49 final List<Optimize> optimizes
50 ) {
51 Vecs.checkVecLength(optimizes.size());
52 _maximisations = toFlags(optimizes);
53 _comp = requireNonNull(comparator);
54 _dist = requireNonNull(distance);
55 }
56
57 private int cmp(final T[] u, final T[] v, final int i) {
58 return _maximisations[i]
59 ? _comp.compare(u[i], v[i])
60 : _comp.compare(v[i], u[i]);
61 }
62
63 private double dst(final T[] u, final T[] v, final int i) {
64 return _maximisations[i]
65 ? _dist.distance(u, v, i)
66 : _dist.distance(v, u, i);
67 }
68
69 private int dom(final T[] u, final T[] v) {
70 return Pareto.dominance(u, v, _maximisations.length, _comparator);
71 }
72
73 @Override
74 public Vec<T[]> newVec(final T[] array) {
75 requireVecLength(_maximisations.length, array.length);
76 return new GeneralObjectVec<>(array, _comparator, _distance, _dominance);
77 }
78
79 @Override
80 public String toString() {
81 return format("VecFactory<T[%d]>", _maximisations.length);
82 }
83
84 }
|