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.differentiation;
24  
25  import org.hipparchus.UnitTestUtils;
26  import org.hipparchus.analysis.QuinticFunction;
27  import org.hipparchus.analysis.UnivariateFunction;
28  import org.hipparchus.analysis.UnivariateMatrixFunction;
29  import org.hipparchus.analysis.UnivariateVectorFunction;
30  import org.hipparchus.analysis.function.Gaussian;
31  import org.hipparchus.analysis.function.Sin;
32  import org.hipparchus.exception.LocalizedCoreFormats;
33  import org.hipparchus.exception.MathIllegalArgumentException;
34  import org.hipparchus.exception.MathRuntimeException;
35  import org.hipparchus.util.FastMath;
36  import org.junit.jupiter.api.Test;
37  
38  import static org.junit.jupiter.api.Assertions.assertEquals;
39  import static org.junit.jupiter.api.Assertions.assertThrows;
40  import static org.junit.jupiter.api.Assertions.fail;
41  
42  /**
43   * Test for class {@link FiniteDifferencesDifferentiator}.
44   */
45  class FiniteDifferencesDifferentiatorTest {
46  
47      @Test
48      void testWrongNumberOfPoints() {
49          assertThrows(MathIllegalArgumentException.class, () -> new FiniteDifferencesDifferentiator(1, 1.0));
50      }
51  
52      @Test
53      void testWrongStepSize() {
54          assertThrows(MathIllegalArgumentException.class, () -> new FiniteDifferencesDifferentiator(3, 0.0));
55      }
56  
57      @Test
58      void testSerialization() {
59          FiniteDifferencesDifferentiator differentiator =
60                  new FiniteDifferencesDifferentiator(3, 1.0e-3);
61          FiniteDifferencesDifferentiator recovered =
62                  (FiniteDifferencesDifferentiator) UnitTestUtils.serializeAndRecover(differentiator);
63          assertEquals(differentiator.getNbPoints(), recovered.getNbPoints());
64          assertEquals(differentiator.getStepSize(), recovered.getStepSize(), 1.0e-15);
65      }
66  
67      @Test
68      void testConstant() {
69          FiniteDifferencesDifferentiator differentiator =
70                  new FiniteDifferencesDifferentiator(5, 0.01);
71          UnivariateDifferentiableFunction f =
72                  differentiator.differentiate((UnivariateFunction) x -> 42.0);
73          DSFactory factory = new DSFactory(1, 2);
74          for (double x = -10; x < 10; x += 0.1) {
75              DerivativeStructure y = f.value(factory.variable(0, x));
76              assertEquals(42.0, y.getValue(), 1.0e-15);
77              assertEquals( 0.0, y.getPartialDerivative(1), 1.0e-15);
78              assertEquals( 0.0, y.getPartialDerivative(2), 1.0e-15);
79          }
80      }
81  
82      @Test
83      void testLinear() {
84          FiniteDifferencesDifferentiator differentiator =
85                  new FiniteDifferencesDifferentiator(5, 0.01);
86          UnivariateDifferentiableFunction f =
87                  differentiator.differentiate((UnivariateFunction) x -> 2 - 3 * x);
88          DSFactory factory = new DSFactory(1, 2);
89          for (double x = -10; x < 10; x += 0.1) {
90              DerivativeStructure y = f.value(factory.variable(0, x));
91              assertEquals(2 - 3 * x, y.getValue(), 2.0e-15, "" + (2 - 3 * x - y.getValue()));
92              assertEquals(-3.0, y.getPartialDerivative(1), 4.0e-13);
93              assertEquals( 0.0, y.getPartialDerivative(2), 9.0e-11);
94          }
95      }
96  
97      @Test
98      void testGaussian() {
99          FiniteDifferencesDifferentiator differentiator =
100                 new FiniteDifferencesDifferentiator(9, 0.02);
101         UnivariateDifferentiableFunction gaussian = new Gaussian(1.0, 2.0);
102         UnivariateDifferentiableFunction f =
103                 differentiator.differentiate(gaussian);
104         double[] expectedError = new double[] {
105             6.939e-18, 1.284e-15, 2.477e-13, 1.168e-11, 2.840e-9, 7.971e-8
106         };
107         double[] maxError = new double[expectedError.length];
108         DSFactory factory = new DSFactory(1, maxError.length - 1);
109         for (double x = -10; x < 10; x += 0.1) {
110             DerivativeStructure dsX  = factory.variable(0, x);
111             DerivativeStructure yRef = gaussian.value(dsX);
112             DerivativeStructure y    = f.value(dsX);
113             assertEquals(f.value(dsX.getValue()), f.value(dsX).getValue(), 1.0e-15);
114             for (int order = 0; order <= yRef.getOrder(); ++order) {
115                 maxError[order] = FastMath.max(maxError[order],
116                                         FastMath.abs(yRef.getPartialDerivative(order) -
117                                                      y.getPartialDerivative(order)));
118             }
119         }
120         for (int i = 0; i < maxError.length; ++i) {
121             assertEquals(expectedError[i], maxError[i], 0.01 * expectedError[i]);
122         }
123     }
124 
125     @Test
126     void testStepSizeUnstability() {
127         UnivariateDifferentiableFunction quintic = new QuinticFunction();
128         UnivariateDifferentiableFunction goodStep =
129                 new FiniteDifferencesDifferentiator(7, 0.25).differentiate(quintic);
130         UnivariateDifferentiableFunction badStep =
131                 new FiniteDifferencesDifferentiator(7, 1.0e-6).differentiate(quintic);
132         double[] maxErrorGood = new double[7];
133         double[] maxErrorBad  = new double[7];
134         DSFactory factory = new DSFactory(1, maxErrorGood.length - 1);
135         for (double x = -10; x < 10; x += 0.1) {
136             DerivativeStructure dsX  = factory.variable(0, x);
137             DerivativeStructure yRef  = quintic.value(dsX);
138             DerivativeStructure yGood = goodStep.value(dsX);
139             DerivativeStructure yBad  = badStep.value(dsX);
140             for (int order = 0; order <= 6; ++order) {
141                 maxErrorGood[order] = FastMath.max(maxErrorGood[order],
142                                                    FastMath.abs(yRef.getPartialDerivative(order) -
143                                                                 yGood.getPartialDerivative(order)));
144                 maxErrorBad[order]  = FastMath.max(maxErrorBad[order],
145                                                    FastMath.abs(yRef.getPartialDerivative(order) -
146                                                                 yBad.getPartialDerivative(order)));
147             }
148         }
149 
150         // the 0.25 step size is good for finite differences in the quintic on this abscissa range for 7 points
151         // the errors are fair
152         final double[] expectedGood = new double[] {
153             7.276e-12, 7.276e-11, 9.968e-10, 3.092e-9, 5.432e-8, 8.196e-8, 1.818e-6
154         };
155 
156         // the 1.0e-6 step size is far too small for finite differences in the quintic on this abscissa range for 7 points
157         // the errors are huge!
158         final double[] expectedBad = new double[] {
159             2.910e-11, 2.087e-5, 147.7, 3.820e7, 6.354e14, 6.548e19, 1.543e27
160         };
161 
162         for (int i = 0; i < maxErrorGood.length; ++i) {
163             assertEquals(expectedGood[i], maxErrorGood[i], 0.01 * expectedGood[i]);
164             assertEquals(expectedBad[i],  maxErrorBad[i],  0.01 * expectedBad[i]);
165         }
166 
167     }
168 
169     @Test
170     void testWrongOrder() {
171         assertThrows(MathIllegalArgumentException.class, () -> {
172             UnivariateDifferentiableFunction f =
173                 new FiniteDifferencesDifferentiator(3, 0.01).differentiate((UnivariateFunction) x -> {
174                     // this exception should not be thrown because wrong order
175                     // should be detected before function call
176                     throw MathRuntimeException.createInternalError();
177                 });
178             f.value(new DSFactory(1, 3).variable(0, 1.0));
179         });
180     }
181 
182     @Test
183     void testWrongOrderVector() {
184         assertThrows(MathIllegalArgumentException.class, () -> {
185             UnivariateDifferentiableVectorFunction f =
186                 new FiniteDifferencesDifferentiator(3, 0.01).differentiate((UnivariateVectorFunction) x -> {
187                     // this exception should not be thrown because wrong order
188                     // should be detected before function call
189                     throw MathRuntimeException.createInternalError();
190                 });
191             f.value(new DSFactory(1, 3).variable(0, 1.0));
192         });
193     }
194 
195     @Test
196     void testWrongOrderMatrix() {
197         assertThrows(MathIllegalArgumentException.class, () -> {
198             UnivariateDifferentiableMatrixFunction f =
199                 new FiniteDifferencesDifferentiator(3, 0.01).differentiate((UnivariateMatrixFunction) x -> {
200                     // this exception should not be thrown because wrong order
201                     // should be detected before function call
202                     throw MathRuntimeException.createInternalError();
203                 });
204             f.value(new DSFactory(1, 3).variable(0, 1.0));
205         });
206     }
207 
208     @Test
209     void testTooLargeStep() {
210         assertThrows(MathIllegalArgumentException.class, () -> new FiniteDifferencesDifferentiator(3, 2.5, 0.0, 1.0));
211     }
212 
213     @Test
214     void testBounds() {
215 
216         final double slope = 2.5;
217         UnivariateFunction f = x -> {
218             if (x < 0) {
219                 throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_SMALL,
220                                                        x, 0);
221             } else if (x > 1) {
222                 throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE,
223                                                        x, 1);
224             } else {
225                 return slope * x;
226             }
227         };
228 
229         UnivariateDifferentiableFunction missingBounds =
230                 new FiniteDifferencesDifferentiator(3, 0.1).differentiate(f);
231         UnivariateDifferentiableFunction properlyBounded =
232                 new FiniteDifferencesDifferentiator(3, 0.1, 0.0, 1.0).differentiate(f);
233         DSFactory factory = new DSFactory(1, 1);
234         DerivativeStructure tLow  = factory.variable(0, 0.05);
235         DerivativeStructure tHigh = factory.variable(0, 0.95);
236 
237         try {
238             // here, we did not set the bounds, so the differences are evaluated out of domain
239             // using f(-0.05), f(0.05), f(0.15)
240             missingBounds.value(tLow);
241             fail("an exception should have been thrown");
242         } catch (MathIllegalArgumentException nse) {
243             assertEquals(LocalizedCoreFormats.NUMBER_TOO_SMALL, nse.getSpecifier());
244             assertEquals(-0.05, ((Double) nse.getParts()[0]).doubleValue(), 1.0e-10);
245         } catch (Exception e) {
246             fail("wrong exception caught: " + e.getClass().getName());
247         }
248 
249         try {
250             // here, we did not set the bounds, so the differences are evaluated out of domain
251             // using f(0.85), f(0.95), f(1.05)
252             missingBounds.value(tHigh);
253             fail("an exception should have been thrown");
254         } catch (MathIllegalArgumentException nle) {
255             assertEquals(LocalizedCoreFormats.NUMBER_TOO_LARGE, nle.getSpecifier());
256             assertEquals(1.05, ((Double) nle.getParts()[0]).doubleValue(), 1.0e-10);
257         } catch (Exception e) {
258             fail("wrong exception caught: " + e.getClass().getName());
259         }
260 
261         // here, we did set the bounds, so evaluations are done within domain
262         // using f(0.0), f(0.1), f(0.2)
263         assertEquals(slope, properlyBounded.value(tLow).getPartialDerivative(1), 1.0e-10);
264 
265         // here, we did set the bounds, so evaluations are done within domain
266         // using f(0.8), f(0.9), f(1.0)
267         assertEquals(slope, properlyBounded.value(tHigh).getPartialDerivative(1), 1.0e-10);
268 
269     }
270 
271     @Test
272     void testBoundedSqrt() {
273 
274         UnivariateFunctionDifferentiator differentiator =
275                 new FiniteDifferencesDifferentiator(9, 1.0 / 32, 0.0, Double.POSITIVE_INFINITY);
276         UnivariateDifferentiableFunction sqrt = differentiator.differentiate(FastMath::sqrt);
277 
278         // we are able to compute derivative near 0, but the accuracy is much poorer there
279         DSFactory factory = new DSFactory(1, 1);
280         DerivativeStructure t001 = factory.variable(0, 0.01);
281         assertEquals(0.5 / FastMath.sqrt(t001.getValue()), sqrt.value(t001).getPartialDerivative(1), 1.6);
282         DerivativeStructure t01 = factory.variable(0, 0.1);
283         assertEquals(0.5 / FastMath.sqrt(t01.getValue()), sqrt.value(t01).getPartialDerivative(1), 7.0e-3);
284         DerivativeStructure t03 = factory.variable(0, 0.3);
285         assertEquals(0.5 / FastMath.sqrt(t03.getValue()), sqrt.value(t03).getPartialDerivative(1), 2.1e-7);
286 
287     }
288 
289     @Test
290     void testVectorFunction() {
291 
292         FiniteDifferencesDifferentiator differentiator =
293                 new FiniteDifferencesDifferentiator(7, 0.01);
294         UnivariateDifferentiableVectorFunction f =
295                 differentiator.differentiate((UnivariateVectorFunction) x -> new double[] { FastMath.cos(x), FastMath.sin(x) });
296 
297         DSFactory factory = new DSFactory(1, 2);
298         for (double x = -10; x < 10; x += 0.1) {
299             DerivativeStructure dsX = factory.variable(0, x);
300             DerivativeStructure[] y = f.value(dsX);
301             double cos = FastMath.cos(x);
302             double sin = FastMath.sin(x);
303             double[] f1 = f.value(dsX.getValue());
304             DerivativeStructure[] f2 = f.value(dsX);
305             assertEquals(f1.length, f2.length);
306             for (int i = 0; i < f1.length; ++i) {
307                 assertEquals(f1[i], f2[i].getValue(), 1.0e-15);
308             }
309             assertEquals( cos, y[0].getValue(), 7.0e-16);
310             assertEquals( sin, y[1].getValue(), 7.0e-16);
311             assertEquals(-sin, y[0].getPartialDerivative(1), 6.0e-14);
312             assertEquals( cos, y[1].getPartialDerivative(1), 6.0e-14);
313             assertEquals(-cos, y[0].getPartialDerivative(2), 2.0e-11);
314             assertEquals(-sin, y[1].getPartialDerivative(2), 2.0e-11);
315         }
316 
317     }
318 
319     @Test
320     void testMatrixFunction() {
321 
322         FiniteDifferencesDifferentiator differentiator =
323                 new FiniteDifferencesDifferentiator(7, 0.01);
324         UnivariateDifferentiableMatrixFunction f =
325                 differentiator.differentiate((UnivariateMatrixFunction) x -> new double[][] {
326                     { FastMath.cos(x),  FastMath.sin(x)  },
327                     { FastMath.cosh(x), FastMath.sinh(x) }
328                 });
329 
330         DSFactory factory = new DSFactory(1, 2);
331         for (double x = -1; x < 1; x += 0.02) {
332             DerivativeStructure dsX = factory.variable(0, x);
333             DerivativeStructure[][] y = f.value(dsX);
334             double cos = FastMath.cos(x);
335             double sin = FastMath.sin(x);
336             double cosh = FastMath.cosh(x);
337             double sinh = FastMath.sinh(x);
338             double[][] f1 = f.value(dsX.getValue());
339             DerivativeStructure[][] f2 = f.value(dsX);
340             assertEquals(f1.length, f2.length);
341             for (int i = 0; i < f1.length; ++i) {
342                 assertEquals(f1[i].length, f2[i].length);
343                 for (int j = 0; j < f1[i].length; ++j) {
344                     assertEquals(f1[i][j], f2[i][j].getValue(), 1.0e-15);
345                 }
346             }
347             assertEquals(cos,   y[0][0].getValue(), 7.0e-18);
348             assertEquals(sin,   y[0][1].getValue(), 6.0e-17);
349             assertEquals(cosh,  y[1][0].getValue(), 3.0e-16);
350             assertEquals(sinh,  y[1][1].getValue(), 3.0e-16);
351             assertEquals(-sin,  y[0][0].getPartialDerivative(1), 2.0e-14);
352             assertEquals( cos,  y[0][1].getPartialDerivative(1), 2.0e-14);
353             assertEquals( sinh, y[1][0].getPartialDerivative(1), 3.0e-14);
354             assertEquals( cosh, y[1][1].getPartialDerivative(1), 3.0e-14);
355             assertEquals(-cos,  y[0][0].getPartialDerivative(2), 3.0e-12);
356             assertEquals(-sin,  y[0][1].getPartialDerivative(2), 3.0e-12);
357             assertEquals( cosh, y[1][0].getPartialDerivative(2), 6.0e-12);
358             assertEquals( sinh, y[1][1].getPartialDerivative(2), 6.0e-12);
359         }
360 
361     }
362 
363     @Test
364     void testSeveralFreeParameters() {
365         FiniteDifferencesDifferentiator differentiator =
366                 new FiniteDifferencesDifferentiator(5, 0.001);
367         UnivariateDifferentiableFunction sine = new Sin();
368         UnivariateDifferentiableFunction f =
369                 differentiator.differentiate(sine);
370         double[] expectedError = new double[] {
371             6.696e-16, 1.371e-12, 2.007e-8, 1.754e-5
372         };
373         double[] maxError = new double[expectedError.length];
374         DSFactory factory = new DSFactory(2, maxError.length - 1);
375         for (double x = -2; x < 2; x += 0.1) {
376            for (double y = -2; y < 2; y += 0.1) {
377                DerivativeStructure dsX  = factory.variable(0, x);
378                DerivativeStructure dsY  = factory.variable(1, y);
379                DerivativeStructure dsT  = dsX.multiply(3).subtract(dsY.twice());
380                DerivativeStructure sRef = sine.value(dsT);
381                DerivativeStructure s    = f.value(dsT);
382                for (int xOrder = 0; xOrder <= sRef.getOrder(); ++xOrder) {
383                    for (int yOrder = 0; yOrder <= sRef.getOrder(); ++yOrder) {
384                        if (xOrder + yOrder <= sRef.getOrder()) {
385                            maxError[xOrder +yOrder] = FastMath.max(maxError[xOrder + yOrder],
386                                                                     FastMath.abs(sRef.getPartialDerivative(xOrder, yOrder) -
387                                                                                  s.getPartialDerivative(xOrder, yOrder)));
388                        }
389                    }
390                }
391            }
392        }
393        for (int i = 0; i < maxError.length; ++i) {
394            assertEquals(expectedError[i], maxError[i], 0.01 * expectedError[i]);
395        }
396     }
397 
398 }