View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) 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 ASF 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  
18  /*
19   * This is not the original file distributed by the Apache Software Foundation
20   * It has been modified by the Hipparchus project
21   */
22  
23  package org.hipparchus.analysis;
24  
25  import org.hipparchus.analysis.differentiation.DSFactory;
26  import org.hipparchus.analysis.differentiation.Derivative;
27  import org.hipparchus.analysis.differentiation.DerivativeStructure;
28  import org.hipparchus.analysis.differentiation.MultivariateDifferentiableFunction;
29  import org.hipparchus.analysis.differentiation.UnivariateDifferentiableFunction;
30  import org.hipparchus.analysis.function.Add;
31  import org.hipparchus.analysis.function.Constant;
32  import org.hipparchus.analysis.function.Cos;
33  import org.hipparchus.analysis.function.Cosh;
34  import org.hipparchus.analysis.function.Divide;
35  import org.hipparchus.analysis.function.Identity;
36  import org.hipparchus.analysis.function.Inverse;
37  import org.hipparchus.analysis.function.Log;
38  import org.hipparchus.analysis.function.Max;
39  import org.hipparchus.analysis.function.Min;
40  import org.hipparchus.analysis.function.Minus;
41  import org.hipparchus.analysis.function.Multiply;
42  import org.hipparchus.analysis.function.Pow;
43  import org.hipparchus.analysis.function.Power;
44  import org.hipparchus.analysis.function.Sin;
45  import org.hipparchus.analysis.function.Sinc;
46  import org.hipparchus.analysis.function.Subtract;
47  import org.hipparchus.exception.LocalizedCoreFormats;
48  import org.hipparchus.exception.MathIllegalArgumentException;
49  import org.hipparchus.util.FastMath;
50  import org.junit.jupiter.api.Test;
51  
52  import static org.junit.jupiter.api.Assertions.assertEquals;
53  import static org.junit.jupiter.api.Assertions.assertThrows;
54  import static org.junit.jupiter.api.Assertions.fail;
55  
56  /**
57   * Test for {@link FunctionUtils}.
58   */
59  class FunctionUtilsTest {
60      private final double EPS = FastMath.ulp(1d);
61  
62      @Test
63      void testCompose() {
64          UnivariateFunction id = new Identity();
65          assertEquals(3, FunctionUtils.compose(id, id, id).value(3), EPS);
66  
67          UnivariateFunction c = new Constant(4);
68          assertEquals(4, FunctionUtils.compose(id, c).value(3), EPS);
69          assertEquals(4, FunctionUtils.compose(c, id).value(3), EPS);
70  
71          UnivariateFunction m = new Minus();
72          assertEquals(-3, FunctionUtils.compose(m).value(3), EPS);
73          assertEquals(3, FunctionUtils.compose(m, m).value(3), EPS);
74  
75          UnivariateFunction inv = new Inverse();
76          assertEquals(-0.25, FunctionUtils.compose(inv, m, c, id).value(3), EPS);
77  
78          UnivariateFunction pow = new Power(2);
79          assertEquals(81, FunctionUtils.compose(pow, pow).value(3), EPS);
80      }
81  
82      @Test
83      void testComposeDifferentiable() {
84          DSFactory factory = new DSFactory(1, 1);
85          UnivariateDifferentiableFunction id = new Identity();
86          assertEquals(1, FunctionUtils.compose(id, id, id).value(factory.variable(0, 3)).getPartialDerivative(1), EPS);
87          assertEquals(1.5, FunctionUtils.compose(id, id, id).value(1.5), EPS);
88  
89          UnivariateDifferentiableFunction c = new Constant(4);
90          assertEquals(0, FunctionUtils.compose(id, c).value(factory.variable(0, 3)).getPartialDerivative(1), EPS);
91          assertEquals(0, FunctionUtils.compose(c, id).value(factory.variable(0, 3)).getPartialDerivative(1), EPS);
92  
93          UnivariateDifferentiableFunction m = new Minus();
94          assertEquals(-1, FunctionUtils.compose(m).value(factory.variable(0, 3)).getPartialDerivative(1), EPS);
95          assertEquals(1, FunctionUtils.compose(m, m).value(factory.variable(0, 3)).getPartialDerivative(1), EPS);
96  
97          UnivariateDifferentiableFunction inv = new Inverse();
98          assertEquals(0.25, FunctionUtils.compose(inv, m, id).value(factory.variable(0, 2)).getPartialDerivative(1), EPS);
99  
100         UnivariateDifferentiableFunction pow = new Power(2);
101         assertEquals(108, FunctionUtils.compose(pow, pow).value(factory.variable(0, 3)).getPartialDerivative(1), EPS);
102 
103         UnivariateDifferentiableFunction log = new Log();
104         double a = 9876.54321;
105         assertEquals(pow.value(factory.variable(0, a)).getPartialDerivative(1) / pow.value(a),
106                             FunctionUtils.compose(log, pow).value(factory.variable(0, a)).getPartialDerivative(1), EPS);
107     }
108 
109     @Test
110     void testAdd() {
111         UnivariateFunction id = new Identity();
112         UnivariateFunction c = new Constant(4);
113         UnivariateFunction m = new Minus();
114         UnivariateFunction inv = new Inverse();
115 
116         assertEquals(4.5, FunctionUtils.add(inv, m, c, id).value(2), EPS);
117         assertEquals(4 + 2, FunctionUtils.add(c, id).value(2), EPS);
118         assertEquals(4 - 2, FunctionUtils.add(c, FunctionUtils.compose(m, id)).value(2), EPS);
119     }
120 
121     @Test
122     void testAddEmpty() {
123         assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
124             FunctionUtils.add(new UnivariateFunction[0]).value(1.0);
125         });
126     }
127 
128     @Test
129     void testAddDifferentiable() {
130         UnivariateDifferentiableFunction sin = new Sin();
131         UnivariateDifferentiableFunction c = new Constant(4);
132         UnivariateDifferentiableFunction m = new Minus();
133         UnivariateDifferentiableFunction inv = new Inverse();
134 
135         final double a = 123.456;
136         DSFactory factory = new DSFactory(1, 1);
137         assertEquals(- 1 / (a * a) -1 + FastMath.cos(a),
138                             FunctionUtils.add(inv, m, c, sin).value(factory.variable(0, a)).getPartialDerivative(1),
139                             EPS);
140         assertEquals(4 + FastMath.sin(1.2), FunctionUtils.add(sin, c).value(1.2), EPS);
141     }
142 
143     @Test
144     void testAddDifferentiableEmpty() {
145         assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
146             FunctionUtils.add(new UnivariateDifferentiableFunction[0]).value(1.0);
147         });
148     }
149 
150     @Test
151     void testMultiply() {
152         UnivariateFunction c = new Constant(4);
153         assertEquals(16, FunctionUtils.multiply(c, c).value(12345), EPS);
154 
155         UnivariateFunction inv = new Inverse();
156         UnivariateFunction pow = new Power(2);
157         assertEquals(1, FunctionUtils.multiply(FunctionUtils.compose(inv, pow), pow).value(3.5), EPS);
158     }
159 
160     @Test
161     void testMultiplyEmpty() {
162         assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
163             FunctionUtils.multiply(new UnivariateFunction[0]).value(1.0);
164         });
165     }
166 
167     @Test
168     void testMultiplyDifferentiable() {
169         UnivariateDifferentiableFunction c = new Constant(4);
170         UnivariateDifferentiableFunction id = new Identity();
171         DSFactory factory = new DSFactory(1, 1);
172         final double a = 1.2345678;
173         assertEquals(8 * a, FunctionUtils.multiply(c, id, id).value(factory.variable(0, a)).getPartialDerivative(1), EPS);
174 
175         UnivariateDifferentiableFunction inv = new Inverse();
176         UnivariateDifferentiableFunction pow = new Power(2.5);
177         UnivariateDifferentiableFunction cos = new Cos();
178         assertEquals(1.5 * FastMath.sqrt(a) * FastMath.cos(a) - FastMath.pow(a, 1.5) * FastMath.sin(a),
179                             FunctionUtils.multiply(inv, pow, cos).value(factory.variable(0, a)).getPartialDerivative(1), EPS);
180 
181         UnivariateDifferentiableFunction cosh = new Cosh();
182         assertEquals(1.5 * FastMath.sqrt(a) * FastMath.cosh(a) + FastMath.pow(a, 1.5) * FastMath.sinh(a),
183                             FunctionUtils.multiply(inv, pow, cosh).value(factory.variable(0, a)).getPartialDerivative(1), 8 * EPS);
184         assertEquals(16, FunctionUtils.multiply(c, c).value(FastMath.PI), EPS);
185     }
186 
187     @Test
188     void testCombine() {
189         BivariateFunction bi = new Subtract();
190         UnivariateFunction id = new Identity();
191         UnivariateFunction m = new Minus();
192         UnivariateFunction c = FunctionUtils.combine(bi, id, m);
193         assertEquals(4.6912, c.value(2.3456), EPS);
194 
195         bi = new Multiply();
196         UnivariateFunction inv = new Inverse();
197         c = FunctionUtils.combine(bi, id, inv);
198         assertEquals(1, c.value(2.3456), EPS);
199     }
200 
201     @Test
202     void testCollector() {
203         BivariateFunction bi = new Add();
204         MultivariateFunction coll = FunctionUtils.collector(bi, 0);
205         assertEquals(10, coll.value(new double[] {1, 2, 3, 4}), EPS);
206 
207         bi = new Multiply();
208         coll = FunctionUtils.collector(bi, 1);
209         assertEquals(24, coll.value(new double[] {1, 2, 3, 4}), EPS);
210 
211         bi = new Max();
212         coll = FunctionUtils.collector(bi, Double.NEGATIVE_INFINITY);
213         assertEquals(10, coll.value(new double[] {1, -2, 7.5, 10, -24, 9.99}), 0);
214 
215         bi = new Min();
216         coll = FunctionUtils.collector(bi, Double.POSITIVE_INFINITY);
217         assertEquals(-24, coll.value(new double[] {1, -2, 7.5, 10, -24, 9.99}), 0);
218     }
219 
220     @Test
221     void testCollectorEmpty() {
222         MultivariateFunction coll = FunctionUtils.collector(new Add(), 0);
223         assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
224             coll.value(new double[0]);
225         });
226     }
227 
228     @Test
229     void testSinc() {
230         BivariateFunction div = new Divide();
231         UnivariateFunction sin = new Sin();
232         UnivariateFunction id = new Identity();
233         UnivariateFunction sinc1 = FunctionUtils.combine(div, sin, id);
234         UnivariateFunction sinc2 = new Sinc();
235 
236         for (int i = 0; i < 10; i++) {
237             double x = FastMath.random();
238             assertEquals(sinc1.value(x), sinc2.value(x), EPS);
239         }
240     }
241 
242     @Test
243     void testFixingArguments() {
244         UnivariateFunction scaler = FunctionUtils.fix1stArgument(new Multiply(), 10);
245         assertEquals(1.23456, scaler.value(0.123456), EPS);
246 
247         UnivariateFunction pow1 = new Power(2);
248         UnivariateFunction pow2 = FunctionUtils.fix2ndArgument(new Pow(), 2);
249 
250         for (int i = 0; i < 10; i++) {
251             double x = FastMath.random() * 10;
252             assertEquals(pow1.value(x), pow2.value(x), 0);
253         }
254     }
255 
256     @Test
257     void testSampleWrongBounds(){
258         assertThrows(MathIllegalArgumentException.class, () -> FunctionUtils.sample(new Sin(), FastMath.PI, 0.0, 10));
259     }
260 
261     @Test
262     void testSampleNegativeNumberOfPoints(){
263         assertThrows(MathIllegalArgumentException.class, () -> FunctionUtils.sample(new Sin(), 0.0, FastMath.PI, -1));
264     }
265 
266     @Test
267     void testSampleNullNumberOfPoints(){
268         assertThrows(MathIllegalArgumentException.class, () -> FunctionUtils.sample(new Sin(), 0.0, FastMath.PI, 0));
269     }
270 
271     @Test
272     void testSample() {
273         final int n = 11;
274         final double min = 0.0;
275         final double max = FastMath.PI;
276         final double[] actual = FunctionUtils.sample(new Sin(), min, max, n);
277         for (int i = 0; i < n; i++) {
278             final double x = min + (max - min) / n * i;
279             assertEquals(FastMath.sin(x), actual[i], 0.0, "x = " + x);
280         }
281     }
282 
283     @Test
284     void testToDifferentiableUnivariate() {
285 
286         final UnivariateFunction f0 = x -> x * x;
287         final UnivariateFunction f1 = x -> 2 * x;
288         final UnivariateFunction f2 = x -> 2;
289         final UnivariateDifferentiableFunction f = FunctionUtils.toDifferentiable(f0, f1, f2);
290 
291         DSFactory factory = new DSFactory(1, 2);
292         for (double t = -1.0; t < 1; t += 0.01) {
293             // x = sin(t)
294             DerivativeStructure dsT = factory.variable(0, t);
295             DerivativeStructure y = f.value(dsT.sin());
296             assertEquals(FastMath.sin(t) * FastMath.sin(t),               f.value(FastMath.sin(t)),  1.0e-15);
297             assertEquals(FastMath.sin(t) * FastMath.sin(t),               y.getValue(),              1.0e-15);
298             assertEquals(2 * FastMath.cos(t) * FastMath.sin(t),           y.getPartialDerivative(1), 1.0e-15);
299             assertEquals(2 * (1 - 2 * FastMath.sin(t) * FastMath.sin(t)), y.getPartialDerivative(2), 1.0e-15);
300         }
301 
302         try {
303             f.value(new DSFactory(1, 3).constant(0.0));
304             fail("an exception should have been thrown");
305         } catch (MathIllegalArgumentException e) {
306             assertEquals(LocalizedCoreFormats.NUMBER_TOO_LARGE, e.getSpecifier());
307             assertEquals(2, ((Integer) e.getParts()[1]).intValue());
308             assertEquals(3, ((Integer) e.getParts()[0]).intValue());
309         }
310 
311         try {
312             FunctionUtils.compose((UnivariateFunction) null).value(1.0);
313             fail("an exception should have been thrown");
314         } catch (NullPointerException e) {
315             // expected
316         }
317     }
318 
319     @Test
320     void testToDifferentiableMultivariate() {
321 
322         final double a = 1.5;
323         final double b = 0.5;
324         final MultivariateFunction f = point -> a * point[0] + b * point[1];
325         final MultivariateVectorFunction gradient = point -> new double[] { a, b };
326         final MultivariateDifferentiableFunction mdf = FunctionUtils.toDifferentiable(f, gradient);
327 
328         DSFactory factory11 = new DSFactory(1, 1);
329         for (double t = -1.0; t < 1; t += 0.01) {
330             // x = sin(t), y = cos(t), hence the method really becomes univariate
331             DerivativeStructure dsT = factory11.variable(0, t);
332             DerivativeStructure y = mdf.value(new DerivativeStructure[] { dsT.sin(), dsT.cos() });
333             assertEquals(a * FastMath.sin(t) + b * FastMath.cos(t), y.getValue(),              1.0e-15);
334             assertEquals(a * FastMath.cos(t) - b * FastMath.sin(t), y.getPartialDerivative(1), 1.0e-15);
335         }
336 
337         DSFactory factory21 = new DSFactory(2, 1);
338         for (double u = -1.0; u < 1; u += 0.01) {
339             DerivativeStructure dsU = factory21.variable(0, u);
340             for (double v = -1.0; v < 1; v += 0.01) {
341                 DerivativeStructure dsV = factory21.variable(1, v);
342                 DerivativeStructure y = mdf.value(new DerivativeStructure[] { dsU, dsV });
343                 assertEquals(a * u + b * v, mdf.value(new double[] { u, v }), 1.0e-15);
344                 assertEquals(a * u + b * v, y.getValue(),                     1.0e-15);
345                 assertEquals(a,             y.getPartialDerivative(1, 0),     1.0e-15);
346                 assertEquals(b,             y.getPartialDerivative(0, 1),     1.0e-15);
347             }
348         }
349 
350         DSFactory factory13 = new DSFactory(1, 3);
351         try {
352             mdf.value(new DerivativeStructure[] { factory13.constant(0.0), factory13.constant(0.0) });
353             fail("an exception should have been thrown");
354         } catch (MathIllegalArgumentException e) {
355             assertEquals(LocalizedCoreFormats.NUMBER_TOO_LARGE, e.getSpecifier());
356             assertEquals(1, ((Integer) e.getParts()[1]).intValue());
357             assertEquals(3, ((Integer) e.getParts()[0]).intValue());
358         }
359     }
360 
361     @Test
362     void testToDifferentiableMultivariateInconsistentGradient() {
363 
364         final double a = 1.5;
365         final double b = 0.5;
366         final MultivariateFunction f = point -> a * point[0] + b * point[1];
367         final MultivariateVectorFunction gradient = point -> new double[] { a, b, 0.0 };
368         final MultivariateDifferentiableFunction mdf = FunctionUtils.toDifferentiable(f, gradient);
369 
370         DSFactory factory = new DSFactory(1, 1);
371         try {
372             DerivativeStructure dsT = factory.variable(0, 0.0);
373             mdf.value(new DerivativeStructure[] { dsT.sin(), dsT.cos() });
374             fail("an exception should have been thrown");
375         } catch (MathIllegalArgumentException e) {
376             assertEquals(3, ((Integer) e.getParts()[0]).intValue());
377             assertEquals(2, ((Integer) e.getParts()[1]).intValue());
378         }
379 
380         try {
381             MultivariateFunction df = FunctionUtils.derivative(mdf, new int[] { 1 });
382             df.value(new double[] { 1.0, 2.0 });
383             fail("an exception should have been thrown");
384         } catch (MathIllegalArgumentException e) {
385             // expected dimension mismatch
386         }
387     }
388 
389     @Test
390     void testDerivativeUnivariate() {
391 
392         final UnivariateDifferentiableFunction f = new UnivariateDifferentiableFunction() {
393 
394             @Override
395             public double value(double x) {
396                 return x * x;
397             }
398 
399             @Override
400             public <T extends Derivative<T>> T value(T x) {
401                 return x.square();
402             }
403 
404         };
405 
406         final UnivariateFunction f0 = FunctionUtils.derivative(f, 0);
407         final UnivariateFunction f1 = FunctionUtils.derivative(f, 1);
408         final UnivariateFunction f2 = FunctionUtils.derivative(f, 2);
409 
410         for (double t = -1.0; t < 1; t += 0.01) {
411             assertEquals(t * t, f0.value(t), 1.0e-15);
412             assertEquals(2 * t, f1.value(t), 1.0e-15);
413             assertEquals(2,     f2.value(t), 1.0e-15);
414         }
415 
416     }
417 
418     @Test
419     void testDerivativeMultivariate() {
420 
421         final double a = 1.5;
422         final double b = 0.5;
423         final double c = 0.25;
424         final MultivariateDifferentiableFunction mdf = new MultivariateDifferentiableFunction() {
425 
426             @Override
427             public double value(double[] point) {
428                 return a * point[0] * point[0] + b * point[1] * point[1] + c * point[0] * point[1];
429             }
430 
431             @Override
432             public DerivativeStructure value(DerivativeStructure[] point) {
433                 DerivativeStructure x  = point[0];
434                 DerivativeStructure y  = point[1];
435                 DerivativeStructure x2 = x.square();
436                 DerivativeStructure y2 = y.square();
437                 DerivativeStructure xy = x.multiply(y);
438                 return x2.multiply(a).add(y2.multiply(b)).add(xy.multiply(c));
439             }
440 
441         };
442 
443         final MultivariateFunction f       = FunctionUtils.derivative(mdf, new int[] { 0, 0 });
444         final MultivariateFunction dfdx    = FunctionUtils.derivative(mdf, new int[] { 1, 0 });
445         final MultivariateFunction dfdy    = FunctionUtils.derivative(mdf, new int[] { 0, 1 });
446         final MultivariateFunction d2fdx2  = FunctionUtils.derivative(mdf, new int[] { 2, 0 });
447         final MultivariateFunction d2fdy2  = FunctionUtils.derivative(mdf, new int[] { 0, 2 });
448         final MultivariateFunction d2fdxdy = FunctionUtils.derivative(mdf, new int[] { 1, 1 });
449 
450         for (double x = -1.0; x < 1; x += 0.01) {
451             for (double y = -1.0; y < 1; y += 0.01) {
452                 assertEquals(a * x * x + b * y * y + c * x * y, f.value(new double[]       { x, y }), 1.0e-15);
453                 assertEquals(2 * a * x + c * y,                 dfdx.value(new double[]    { x, y }), 1.0e-15);
454                 assertEquals(2 * b * y + c * x,                 dfdy.value(new double[]    { x, y }), 1.0e-15);
455                 assertEquals(2 * a,                             d2fdx2.value(new double[]  { x, y }), 1.0e-15);
456                 assertEquals(2 * b,                             d2fdy2.value(new double[]  { x, y }), 1.0e-15);
457                 assertEquals(c,                                 d2fdxdy.value(new double[] { x, y }), 1.0e-15);
458             }
459         }
460 
461     }
462 
463 }