001 /*
002 * Java Genetic Algorithm Library (jenetics-7.1.1).
003 * Copyright (c) 2007-2022 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 */
020 package io.jenetics.prog.regression;
021
022 import static java.lang.String.format;
023 import static java.util.Objects.requireNonNull;
024
025 import java.io.Serial;
026 import java.io.Serializable;
027 import java.util.Arrays;
028
029 /**
030 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
031 * @version 5.0
032 * @since 5.0
033 */
034 final class DoubleSample implements Sample<Double>, Serializable {
035
036 @Serial
037 private static final long serialVersionUID = 1L;
038
039 private final double[] _sample;
040
041 /**
042 * Create a new sample point with the given argument array and result value.
043 *
044 * @param sample the arguments of the sample point
045 * @throws IllegalArgumentException if the argument array is empty
046 * @throws NullPointerException if the argument array is {@code null}
047 */
048 DoubleSample(final double... sample) {
049 if (sample.length < 2) {
050 throw new IllegalArgumentException(format(
051 "Argument sample must contain at least two values: %s",
052 sample.length
053 ));
054 }
055
056 _sample = requireNonNull(sample);
057 }
058
059 @Override
060 public int arity() {
061 return _sample.length - 1;
062 }
063
064 @Override
065 public Double argAt(final int index) {
066 if (index < 0 || index >= arity()) {
067 throw new ArrayIndexOutOfBoundsException(format(
068 "Argument index out or range [0, %s): %s", arity(), index
069 ));
070 }
071
072 return _sample[index];
073 }
074
075 Double[] args() {
076 final Double[] result = new Double[arity()];
077 for (int i = 0; i < result.length; ++i) {
078 result[i] = _sample[i];
079 }
080 return result;
081 }
082
083 @Override
084 public Double result() {
085 return _sample[_sample.length - 1];
086 }
087
088 @Override
089 public int hashCode() {
090 return Arrays.hashCode(_sample);
091 }
092
093 @Override
094 public boolean equals(final Object obj) {
095 return obj == this ||
096 obj instanceof DoubleSample other &&
097 Arrays.equals(_sample, other._sample);
098 }
099
100 @Override
101 public String toString() {
102 return format("%s -> %s", Arrays.toString(args()), result());
103 }
104 }
|