1 /*
2 * Licensed to the Hipparchus project under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The Hipparchus project licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * https://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 package org.hipparchus.optim.nonlinear.vector.constrained;
18
19 import org.hipparchus.linear.MatrixUtils;
20 import org.hipparchus.linear.RealVector;
21 import org.hipparchus.util.FastMath;
22 import org.hipparchus.util.MathUtils;
23
24 /** Constraint with lower and upper bounds: \(l \le f(x) \le u\).
25 * @since 3.1
26 */
27 public abstract class BoundedConstraint implements Constraint {
28
29 /** Lower bound. */
30 private final RealVector lower;
31
32 /** Upper bound. */
33 private final RealVector upper;
34
35
36 /** Simple constructor.
37 * <p>
38 * At least one of the bounds must be non-null.
39 * </p>
40 * @param lower lower bound (null if no lower bound)
41 * @param upper upper bound (null if no upper bound)
42 */
43 protected BoundedConstraint(final RealVector lower, final RealVector upper) {
44
45 // ensure lower is always properly set, even when there are no lower bounds
46 if (lower == null) {
47 MathUtils.checkNotNull(upper);
48 this.lower = MatrixUtils.createRealVector(upper.getDimension());
49 this.lower.set(Double.NEGATIVE_INFINITY);
50 } else {
51 this.lower = lower;
52 }
53
54 // ensure upper is always properly set, even when there are no upper bounds
55 if (upper == null) {
56 this.upper = MatrixUtils.createRealVector(lower.getDimension());
57 this.upper.set(Double.POSITIVE_INFINITY);
58 } else {
59 this.upper = upper;
60 }
61
62 // safety check on dimensions
63 MathUtils.checkDimension(this.lower.getDimension(), this.upper.getDimension());
64
65 }
66
67 /** {@inheritDoc} */
68 @Override
69 public int dimY() {
70 return lower.getDimension();
71 }
72
73 /** {@inheritDoc} */
74 @Override
75 public RealVector getLowerBound() {
76 return lower;
77 }
78
79 /** {@inheritDoc} */
80 @Override
81 public RealVector getUpperBound() {
82 return upper;
83 }
84
85 /** {@inheritDoc} */
86 @Override
87 public double overshoot(final RealVector y) {
88
89 double overshoot = 0;
90 for (int i = 0; i < y.getDimension(); ++i) {
91 overshoot += FastMath.max(0, lower.getEntry(i) - y.getEntry(i));
92 overshoot += FastMath.max(0, y.getEntry(i) - upper.getEntry(i));
93 }
94
95 return overshoot;
96
97 }
98
99 }