View Javadoc
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.analysis.differentiation;
18  
19  import org.hipparchus.CalculusFieldElement;
20  import org.hipparchus.CalculusFieldElementAbstractTest;
21  import org.hipparchus.Field;
22  import org.hipparchus.UnitTestUtils;
23  import org.hipparchus.analysis.FieldUnivariateFunction;
24  import org.hipparchus.exception.LocalizedCoreFormats;
25  import org.hipparchus.exception.MathIllegalArgumentException;
26  import org.hipparchus.util.FastMath;
27  import org.hipparchus.util.FieldSinCos;
28  import org.hipparchus.util.MathArrays;
29  import org.junit.jupiter.api.Assertions;
30  import org.junit.jupiter.api.Test;
31  
32  import java.util.Arrays;
33  
34  import static org.junit.jupiter.api.Assertions.assertEquals;
35  import static org.junit.jupiter.api.Assertions.assertNotEquals;
36  import static org.junit.jupiter.api.Assertions.assertNotSame;
37  import static org.junit.jupiter.api.Assertions.assertSame;
38  import static org.junit.jupiter.api.Assertions.fail;
39  
40  /**
41   * Test for class {@link UnivariateDerivative}.
42   */
43  class GradientTest extends CalculusFieldElementAbstractTest<Gradient> {
44  
45      @Override
46      protected Gradient build(final double x) {
47          // the function is really a two variables function : f(x) = g(x, 0) with g(x, y) = x + y / 1024
48          return new Gradient(x, 1.0, FastMath.scalb(1.0, -10));
49      }
50  
51      @Test
52      void testNorm() {
53          final Gradient x = new Gradient(-1, 2, 3);
54          assertEquals(6., x.norm());
55      }
56  
57      @Test
58      void testGetGradient() {
59          Gradient g = new Gradient(-0.5, 2.5, 10.0, -1.0);
60          assertEquals(-0.5, g.getReal(), 1.0e-15);
61          assertEquals(-0.5, g.getValue(), 1.0e-15);
62          assertEquals(+2.5, g.getGradient()[0], 1.0e-15);
63          assertEquals(10.0, g.getGradient()[1], 1.0e-15);
64          assertEquals(-1.0, g.getGradient()[2], 1.0e-15);
65          assertEquals(+2.5, g.getPartialDerivative(0), 1.0e-15);
66          assertEquals(10.0, g.getPartialDerivative(1), 1.0e-15);
67          assertEquals(-1.0, g.getPartialDerivative(2), 1.0e-15);
68          assertEquals(3, g.getFreeParameters());
69          try {
70              g.getPartialDerivative(-1);
71              fail("an exception should have been thrown");
72          } catch (MathIllegalArgumentException miae) {
73              assertEquals(LocalizedCoreFormats.OUT_OF_RANGE_SIMPLE, miae.getSpecifier());
74          }
75          try {
76              g.getPartialDerivative(+3);
77              fail("an exception should have been thrown");
78          } catch (MathIllegalArgumentException miae) {
79              assertEquals(LocalizedCoreFormats.OUT_OF_RANGE_SIMPLE, miae.getSpecifier());
80          }
81      }
82  
83      @Test
84      void testConstant() {
85          Gradient g = Gradient.constant(5, -4.5);
86          assertEquals(5, g.getFreeParameters());
87          assertEquals(-4.5, g.getValue(), 1.0e-15);
88          for (int i = 0 ; i < g.getFreeParameters(); ++i) {
89              assertEquals(0.0, g.getPartialDerivative(i), 1.0e-15);
90          }
91      }
92  
93      @Test
94      void testVariable() {
95          Gradient g = Gradient.variable(5, 1, -4.5);
96          assertEquals(5, g.getFreeParameters());
97          assertEquals(-4.5, g.getValue(), 1.0e-15);
98          for (int i = 0 ; i < g.getFreeParameters(); ++i) {
99              assertEquals(i == 1 ? 1.0 : 0.0, g.getPartialDerivative(i), 1.0e-15);
100         }
101     }
102 
103     @Test
104     void testStackVariable() {
105         // GIVEN
106         final Gradient gradient = new Gradient(1, 2, 3);
107         // WHEN
108         final Gradient gradientWithMoreVariable = gradient.stackVariable();
109         // THEN
110         Assertions.assertEquals(gradient.getValue(), gradientWithMoreVariable.getValue());
111         Assertions.assertEquals(gradient.getFreeParameters() + 1, gradientWithMoreVariable.getFreeParameters());
112         Assertions.assertEquals(0., gradientWithMoreVariable.getGradient()[gradient.getFreeParameters()]);
113         Assertions.assertArrayEquals(gradient.getGradient(), Arrays.copyOfRange(gradientWithMoreVariable.getGradient(),
114                 0, gradient.getFreeParameters()));
115     }
116 
117     @Test
118     void testDoublePow() {
119         assertSame(build(3).getField().getZero(), Gradient.pow(0.0, build(1.5)));
120         Gradient g = Gradient.pow(2.0, build(1.5));
121         DSFactory factory = new DSFactory(2, 1);
122         DerivativeStructure ds = factory.constant(2.0).pow(factory.build(1.5, 1.0, FastMath.scalb(1.0, -10)));
123         assertEquals(ds.getValue(), g.getValue(), 1.0e-15);
124         final int[] indices = new int[ds.getFreeParameters()];
125         for (int i = 0; i < g.getFreeParameters(); ++i) {
126             indices[i] = 1;
127             assertEquals(ds.getPartialDerivative(indices), g.getPartialDerivative(i), 1.0e-15);
128             indices[i] = 0;
129         }
130     }
131 
132     @Test
133     void testTaylor() {
134         assertEquals(2.75, new Gradient(2, 1, 0.125).taylor(0.5, 2.0), 1.0e-15);
135     }
136 
137     @Test
138     void testOrder() {
139         assertEquals(1, new Gradient(2,  1, 0.125).getOrder());
140     }
141 
142     @Test
143     void testGetPartialDerivative() {
144         final Gradient g = new Gradient(2,  1, 0.125);
145         assertEquals(2.0,   g.getPartialDerivative(0, 0), 1.0e-15); // f(x,y)
146         assertEquals(1.0,   g.getPartialDerivative(1, 0), 1.0e-15); // ∂f/∂x
147         assertEquals(0.125, g.getPartialDerivative(0, 1), 1.0e-15); // ∂f/∂y
148     }
149 
150     @Test
151     void testGetPartialDerivativeErrors() {
152         final Gradient g = new Gradient(2,  1, 0.125);
153         try {
154             g.getPartialDerivative(0, 0, 0);
155             fail("an exception should have been thrown");
156         } catch (MathIllegalArgumentException miae) {
157             assertEquals(LocalizedCoreFormats.DIMENSIONS_MISMATCH, miae.getSpecifier());
158             assertEquals(3, ((Integer) miae.getParts()[0]).intValue());
159             assertEquals(2, ((Integer) miae.getParts()[1]).intValue());
160         }
161         try {
162             g.getPartialDerivative(0, 5);
163             fail("an exception should have been thrown");
164         } catch (MathIllegalArgumentException miae) {
165             assertEquals(LocalizedCoreFormats.DERIVATION_ORDER_NOT_ALLOWED, miae.getSpecifier());
166             assertEquals(5, ((Integer) miae.getParts()[0]).intValue());
167         }
168         try {
169             g.getPartialDerivative(1, 1);
170             fail("an exception should have been thrown");
171         } catch (MathIllegalArgumentException miae) {
172             assertEquals(LocalizedCoreFormats.DERIVATION_ORDER_NOT_ALLOWED, miae.getSpecifier());
173             assertEquals(1, ((Integer) miae.getParts()[0]).intValue());
174         }
175     }
176 
177     @Test
178     void testHashcode() {
179         assertEquals(1608501298, new Gradient(2, 1, -0.25).hashCode());
180     }
181 
182     @Test
183     void testEquals() {
184         Gradient g = new Gradient(12, -34, 56);
185         assertEquals(g, g);
186         assertNotEquals("", g);
187         assertEquals(new Gradient(12, -34, 56), g);
188         assertNotEquals(new Gradient(21, -34, 56), g);
189         assertNotEquals(new Gradient(12, -43, 56), g);
190         assertNotEquals(new Gradient(12, -34, 65), g);
191         assertNotEquals(new Gradient(21, -43, 65), g);
192     }
193 
194     @Test
195     void testRunTimeClass() {
196         Field<Gradient> field = build(0.0).getField();
197         assertEquals(Gradient.class, field.getRuntimeClass());
198     }
199 
200     @Test
201     void testConversion() {
202         Gradient gA = new Gradient(-0.5, 2.5, 4.5);
203         DerivativeStructure ds = gA.toDerivativeStructure();
204         assertEquals(2, ds.getFreeParameters());
205         assertEquals(1, ds.getOrder());
206         assertEquals(-0.5, ds.getValue(), 1.0e-15);
207         assertEquals(-0.5, ds.getPartialDerivative(0, 0), 1.0e-15);
208         assertEquals( 2.5, ds.getPartialDerivative(1, 0), 1.0e-15);
209         assertEquals( 4.5, ds.getPartialDerivative(0, 1), 1.0e-15);
210         Gradient gB = new Gradient(ds);
211         assertNotSame(gA, gB);
212         assertEquals(gA, gB);
213         try {
214             new Gradient(new DSFactory(1, 2).variable(0, 1.0));
215             fail("an exception should have been thrown");
216         } catch (MathIllegalArgumentException miae) {
217             assertEquals(LocalizedCoreFormats.DIMENSIONS_MISMATCH, miae.getSpecifier());
218         }
219     }
220 
221     @Test
222     public void testNewInstance() {
223         Gradient g = build(5.25);
224         assertEquals(5.25, g.getValue(), 1.0e-15);
225         assertEquals(1.0,  g.getPartialDerivative(0), 1.0e-15);
226         assertEquals(0.0009765625,  g.getPartialDerivative(1), 1.0e-15);
227         Gradient newInstance = g.newInstance(7.5);
228         assertEquals(7.5, newInstance.getValue(), 1.0e-15);
229         assertEquals(0.0, newInstance.getPartialDerivative(0), 1.0e-15);
230         assertEquals(0.0, newInstance.getPartialDerivative(1), 1.0e-15);
231     }
232 
233     protected void checkAgainstDS(final double x,
234                                   final FieldUnivariateFunction f) {
235         final Gradient xG = build(x);
236         final Gradient yG = f.value(xG);
237         final DerivativeStructure yDS = f.value(xG.toDerivativeStructure());
238         assertEquals(yDS.getFreeParameters(),
239                                 yG.getFreeParameters());
240 
241         if (Double.isNaN(yDS.getValue())) {
242             assertEquals(yDS.getValue(), yG.getValue());
243         } else {
244             assertEquals(yDS.getValue(), yG.getValue(),
245                                     1.0e-15 * FastMath.abs(yDS.getValue()));
246         }
247         final int[] indices = new int[yDS.getFreeParameters()];
248         for (int i = 0; i < yG.getFreeParameters(); ++i) {
249             indices[i] = 1;
250             if (Double.isNaN(yDS.getPartialDerivative(indices))) {
251                 assertEquals(yDS.getPartialDerivative(indices),
252                                         yG.getPartialDerivative(i));
253             } else {
254                 assertEquals(yDS.getPartialDerivative(indices),
255                                         yG.getPartialDerivative(i),
256                                         4.0e-14 * FastMath.abs(
257                                                         yDS.getPartialDerivative(
258                                                                         indices)));
259 
260             }
261             indices[i] = 0;
262         }
263     }
264 
265     @Test
266     void testArithmeticVsDS() {
267         for (double x = -1.25; x < 1.25; x+= 0.5) {
268             checkAgainstDS(x,
269                            new FieldUnivariateFunction() {
270                                public <S extends CalculusFieldElement<S>> S value(S x) {
271                                    final S y = x.add(3).multiply(x).subtract(5).multiply(0.5);
272                                    return y.negate().divide(4).divide(x).add(y).subtract(x).twice().reciprocal();
273                                }
274                            });
275         }
276     }
277 
278     @Test
279     void testRemainderDoubleVsDS() {
280         for (double x = -1.25; x < 1.25; x+= 0.5) {
281             checkAgainstDS(x,
282                            new FieldUnivariateFunction() {
283                                public <S extends CalculusFieldElement<S>> S value(S x) {
284                                    return x.remainder(0.5);
285                                }
286                            });
287         }
288     }
289 
290     @Test
291     void testRemainderGVsDS() {
292         for (double x = -1.25; x < 1.25; x+= 0.5) {
293             checkAgainstDS(x,
294                            new FieldUnivariateFunction() {
295                               public <S extends CalculusFieldElement<S>> S value(S x) {
296                                   return x.remainder(x.divide(0.7));
297                               }
298                            });
299         }
300     }
301 
302     @Test
303     void testAbsVsDS() {
304         for (double x = -1.25; x < 1.25; x+= 0.5) {
305             checkAgainstDS(x,
306                            new FieldUnivariateFunction() {
307                                public <S extends CalculusFieldElement<S>> S value(S x) {
308                                    return x.abs();
309                                }
310                            });
311         }
312     }
313 
314     @Test
315     void testHypotVsDS() {
316         for (double x = -3.25; x < 3.25; x+= 0.5) {
317             checkAgainstDS(x,
318                            new FieldUnivariateFunction() {
319                                public <S extends CalculusFieldElement<S>> S value(S x) {
320                                    return x.cos().multiply(5).hypot(x.sin().twice());
321                                }
322                            });
323         }
324     }
325 
326     @Test
327     void testAtan2VsDS() {
328         for (double x = -3.25; x < 3.25; x+= 0.5) {
329             checkAgainstDS(x,
330                            new FieldUnivariateFunction() {
331                                public <S extends CalculusFieldElement<S>> S value(S x) {
332                                    return x.cos().multiply(5).atan2(x.sin().twice());
333                                }
334                            });
335         }
336     }
337 
338     @Test
339     void testPowersVsDS() {
340         for (double x = -3.25; x < 3.25; x+= 0.5) {
341             checkAgainstDS(x,
342                            new FieldUnivariateFunction() {
343                                public <S extends CalculusFieldElement<S>> S value(S x) {
344                                    final FieldSinCos<S> sc = x.sinCos();
345                                    return x.pow(3.2).add(x.pow(2)).subtract(sc.cos().abs().pow(sc.sin()));
346                                }
347                            });
348         }
349     }
350 
351     @Test
352     void testRootsVsDS() {
353         for (double x = 0.001; x < 3.25; x+= 0.5) {
354             checkAgainstDS(x,
355                            new FieldUnivariateFunction() {
356                                public <S extends CalculusFieldElement<S>> S value(S x) {
357                                    return x.rootN(5);//x.sqrt().add(x.cbrt()).subtract(x.rootN(5));
358                                }
359                            });
360         }
361     }
362 
363     @Test
364     void testExpsLogsVsDS() {
365         for (double x = 2.5; x < 3.25; x+= 0.125) {
366             checkAgainstDS(x,
367                            new FieldUnivariateFunction() {
368                                public <S extends CalculusFieldElement<S>> S value(S x) {
369                                    return x.exp().add(x.multiply(0.5).expm1()).log().log10().log1p();
370                                }
371                            });
372         }
373     }
374 
375     @Test
376     void testTrigonometryVsDS() {
377         for (double x = -3.25; x < 3.25; x+= 0.5) {
378             checkAgainstDS(x,
379                            new FieldUnivariateFunction() {
380                                public <S extends CalculusFieldElement<S>> S value(S x) {
381                                    return x.cos().multiply(x.sin()).atan().divide(12).asin().multiply(0.1).acos().tan();
382                                }
383                            });
384         }
385     }
386 
387     @Test
388     void testHyperbolicVsDS() {
389         for (double x = -1.25; x < 1.25; x+= 0.5) {
390             checkAgainstDS(x,
391                            new FieldUnivariateFunction() {
392                                public <S extends CalculusFieldElement<S>> S value(S x) {
393                                    return x.cosh().multiply(x.sinh()).multiply(12).abs().acosh().asinh().divide(7).tanh().multiply(0.1).atanh();
394                                }
395                            });
396         }
397     }
398 
399     @Test
400     void testConvertersVsDS() {
401         for (double x = -1.25; x < 1.25; x+= 0.5) {
402             checkAgainstDS(x,
403                            new FieldUnivariateFunction() {
404                                public <S extends CalculusFieldElement<S>> S value(S x) {
405                                    return x.multiply(5).toDegrees().subtract(x).toRadians();
406                                }
407                            });
408         }
409     }
410 
411     @Test
412     void testLinearCombination2D2FVsDS() {
413         for (double x = -1.25; x < 1.25; x+= 0.5) {
414             checkAgainstDS(x,
415                            new FieldUnivariateFunction() {
416                                public <S extends CalculusFieldElement<S>> S value(S x) {
417                                    return x.linearCombination(1.0, x.multiply(0.9),
418                                                               2.0, x.multiply(0.8));
419                                }
420                            });
421         }
422     }
423 
424     @Test
425     void testLinearCombination2F2FVsDS() {
426         for (double x = -1.25; x < 1.25; x+= 0.5) {
427             checkAgainstDS(x,
428                            new FieldUnivariateFunction() {
429                                public <S extends CalculusFieldElement<S>> S value(S x) {
430                                    return x.linearCombination(x.add(1), x.multiply(0.9),
431                                                               x.add(2), x.multiply(0.8));
432                                }
433                            });
434         }
435     }
436 
437     @Test
438     void testLinearCombination3D3FVsDS() {
439         for (double x = -1.25; x < 1.25; x+= 0.5) {
440             checkAgainstDS(x,
441                            new FieldUnivariateFunction() {
442                                public <S extends CalculusFieldElement<S>> S value(S x) {
443                                    return x.linearCombination(1.0, x.multiply(0.9),
444                                                               2.0, x.multiply(0.8),
445                                                               3.0, x.multiply(0.7));
446                                }
447                            });
448         }
449     }
450 
451     @Test
452     void testLinearCombination3F3FVsDS() {
453         for (double x = -1.25; x < 1.25; x+= 0.5) {
454             checkAgainstDS(x,
455                            new FieldUnivariateFunction() {
456                                public <S extends CalculusFieldElement<S>> S value(S x) {
457                                    return x.linearCombination(x.add(1), x.multiply(0.9),
458                                                               x.add(2), x.multiply(0.8),
459                                                               x.add(3), x.multiply(0.7));
460                                }
461                            });
462         }
463     }
464 
465     @Test
466     void testLinearCombination4D4FVsDS() {
467         for (double x = -1.25; x < 1.25; x+= 0.5) {
468             checkAgainstDS(x,
469                            new FieldUnivariateFunction() {
470                                public <S extends CalculusFieldElement<S>> S value(S x) {
471                                    return x.linearCombination(1.0, x.multiply(0.9),
472                                                               2.0, x.multiply(0.8),
473                                                               3.0, x.multiply(0.7),
474                                                               4.0, x.multiply(0.6));
475                                }
476                            });
477         }
478     }
479 
480     @Test
481     void testLinearCombination4F4FVsDS() {
482         for (double x = -1.25; x < 1.25; x+= 0.5) {
483             checkAgainstDS(x,
484                            new FieldUnivariateFunction() {
485                                public <S extends CalculusFieldElement<S>> S value(S x) {
486                                    return x.linearCombination(x.add(1), x.multiply(0.9),
487                                                               x.add(2), x.multiply(0.8),
488                                                               x.add(3), x.multiply(0.7),
489                                                               x.add(4), x.multiply(0.6));
490                                }
491                            });
492         }
493     }
494 
495     @Test
496     void testLinearCombinationnDnFVsDS() {
497         for (double x = -1.25; x < 1.25; x+= 0.5) {
498             checkAgainstDS(x,
499                            new FieldUnivariateFunction() {
500                                public <S extends CalculusFieldElement<S>> S value(S x) {
501                                    final S[] b = MathArrays.buildArray(x.getField(), 4);
502                                    b[0] = x.add(0.9);
503                                    b[1] = x.add(0.8);
504                                    b[2] = x.add(0.7);
505                                    b[3] = x.add(0.6);
506                                    return x.linearCombination(new double[] { 1, 2, 3, 4 }, b);
507                                }
508                            });
509         }
510     }
511 
512     @Test
513     void testLinearCombinationnFnFVsDS() {
514         for (double x = -1.25; x < 1.25; x+= 0.5) {
515             checkAgainstDS(x,
516                            new FieldUnivariateFunction() {
517                                public <S extends CalculusFieldElement<S>> S value(S x) {
518                                    final S[] a = MathArrays.buildArray(x.getField(), 4);
519                                    a[0] = x.add(1);
520                                    a[1] = x.add(2);
521                                    a[2] = x.add(3);
522                                    a[3] = x.add(4);
523                                    final S[] b = MathArrays.buildArray(x.getField(), 4);
524                                    b[0] = x.add(0.9);
525                                    b[1] = x.add(0.8);
526                                    b[2] = x.add(0.7);
527                                    b[3] = x.add(0.6);
528                                    return x.linearCombination(a, b);
529                                }
530                            });
531         }
532     }
533 
534     @Test
535     void testSerialization() {
536         Gradient a = build(1.3);
537         Gradient b = (Gradient) UnitTestUtils.serializeAndRecover(a);
538         assertEquals(a, b);
539         assertNotSame(a, b);
540     }
541 
542     @Test
543     void testZero() {
544         Gradient zero = build(17.0).getField().getZero();
545         assertEquals(0.0, zero.getValue(), 1.0e-15);
546         for (int i = 0; i < zero.getFreeParameters(); ++i) {
547             assertEquals(0.0, zero.getPartialDerivative(i), 1.0e-15);
548         }
549     }
550 
551     @Test
552     void testOne() {
553         Gradient one = build(17.0).getField().getOne();
554         assertEquals(1.0, one.getValue(), 1.0e-15);
555         for (int i = 0; i < one.getFreeParameters(); ++i) {
556             assertEquals(0.0, one.getPartialDerivative(i), 1.0e-15);
557         }
558     }
559 
560 
561     @Test
562     public void testIsSmallDimensionMismatch() {
563         try {
564             new Gradient(0.0, 0.0, 0.0).isSmall(new Gradient(0.0, 0.0), 1.0e-15);
565             Assertions.fail("an exception should have been thrown");
566         } catch (MathIllegalArgumentException e) {
567             Assertions.assertEquals(LocalizedCoreFormats.DIMENSIONS_MISMATCH, e.getSpecifier());
568         }
569     }
570 
571     @Test
572     public void testIsSmall() {
573         Assertions.assertTrue(new Gradient(1.0e-13, 2.5e-13).isSmall(new Gradient(1.0, 1.0), 1.0e-12));
574         Assertions.assertFalse(new Gradient(1.0e-11, 2.5e-13).isSmall(new Gradient(1.0, 1.0), 1.0e-12));
575         Assertions.assertFalse(new Gradient(1.0e-13, 2.5e-11).isSmall(new Gradient(1.0, 1.0), 1.0e-12));
576     }
577 
578 }