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  package org.hipparchus.analysis.differentiation;
23  
24  import java.io.Serializable;
25  
26  import org.hipparchus.Field;
27  import org.hipparchus.exception.LocalizedCoreFormats;
28  import org.hipparchus.exception.MathIllegalArgumentException;
29  import org.hipparchus.exception.MathRuntimeException;
30  import org.hipparchus.util.FastMath;
31  import org.hipparchus.util.FieldSinCos;
32  import org.hipparchus.util.FieldSinhCosh;
33  import org.hipparchus.util.MathArrays;
34  import org.hipparchus.util.MathUtils;
35  
36  /** Class representing both the value and the differentials of a function.
37   * <p>This class is the workhorse of the differentiation package.</p>
38   * <p>This class is an implementation of the extension to Rall's
39   * numbers described in Dan Kalman's paper <a
40   * href="http://www.dankalman.net/AUhome/pdffiles/mmgautodiff.pdf">Doubly
41   * Recursive Multivariate Automatic Differentiation</a>, Mathematics Magazine, vol. 75,
42   * no. 3, June 2002. Rall's numbers are an extension to the real numbers used
43   * throughout mathematical expressions; they hold the derivative together with the
44   * value of a function. Dan Kalman's derivative structures hold all partial derivatives
45   * up to any specified order, with respect to any number of free parameters. Rall's
46   * numbers therefore can be seen as derivative structures for order one derivative and
47   * one free parameter, and real numbers can be seen as derivative structures with zero
48   * order derivative and no free parameters.</p>
49   * <p>{@link DerivativeStructure} instances can be used directly thanks to
50   * the arithmetic operators to the mathematical functions provided as
51   * methods by this class (+, -, *, /, %, sin, cos ...).</p>
52   * <p>Implementing complex expressions by hand using {@link Derivative}-based
53   * classes (or in fact any {@link org.hipparchus.CalculusFieldElement} class) is
54   * a tedious and error-prone task but has the advantage of not requiring users
55   * to compute the derivatives by themselves and allowing to switch for one
56   * derivative implementation to another as they all share the same filed API.</p>
57   * <p>Implementing complex expression can also be done by developing computation
58   * code using standard primitive double values and to use {@link
59   * UnivariateFunctionDifferentiator differentiators} to create the {@link
60   * DerivativeStructure}-based instances. This method is simpler but may be limited in
61   * the accuracy and derivation orders and may be computationally intensive (this is
62   * typically the case for {@link FiniteDifferencesDifferentiator finite differences
63   * differentiator}.</p>
64   * <p>Instances of this class are guaranteed to be immutable.</p>
65   * @see DSCompiler
66   * @see FieldDerivativeStructure
67   */
68  public class DerivativeStructure implements Derivative<DerivativeStructure>, Serializable {
69  
70      /** Serializable UID. */
71      private static final long serialVersionUID = 20161220L;
72  
73      /** Factory that built the instance. */
74      private final DSFactory factory;
75  
76      /** Combined array holding all values. */
77      private final double[] data;
78  
79      /** Build an instance with all values and derivatives set to 0.
80       * @param factory factory that built the instance
81       * @param data combined array holding all values
82       */
83      DerivativeStructure(final DSFactory factory, final double[] data) {
84          this.factory = factory;
85          this.data    = data.clone();
86      }
87  
88      /** Build an instance with all values and derivatives set to 0.
89       * @param factory factory that built the instance
90       * @since 1.4
91       */
92      DerivativeStructure(final DSFactory factory) {
93          this.factory = factory;
94          this.data    = new double[factory.getCompiler().getSize()];
95      }
96  
97      /** {@inheritDoc} */
98      @Override
99      public DerivativeStructure newInstance(final double value) {
100         return factory.constant(value);
101     }
102 
103     /** {@inheritDoc} */
104     @Override
105     public DerivativeStructure withValue(final double value) {
106         final DerivativeStructure ds = factory.build();
107         System.arraycopy(data, 1, ds.data, 1, data.length - 1);
108         ds.data[0] = value;
109         return ds;
110     }
111 
112     /** Get the factory that built the instance.
113      * @return factory that built the instance
114      */
115     public DSFactory getFactory() {
116         return factory;
117     }
118 
119     /** {@inheritDoc} */
120     @Override
121     public int getFreeParameters() {
122         return getFactory().getCompiler().getFreeParameters();
123     }
124 
125     /** {@inheritDoc} */
126     @Override
127     public int getOrder() {
128         return getFactory().getCompiler().getOrder();
129     }
130 
131     /** Set a derivative component.
132      * <p>
133      * This method is package-private (no modifier specified), as it is intended
134      * to be used only by Hipparchus classes since it relied on the ordering of
135      * derivatives within the class. This allows avoiding checks on the index,
136      * for performance reasons.
137      * </p>
138      * @param index index of the derivative
139      * @param value of the derivative to set
140      * @since 1.4
141      */
142     void setDerivativeComponent(final int index, final double value) {
143         data[index] = value;
144     }
145 
146     /** Get a derivative component.
147      * <p>
148      * This method is package-private (no modifier specified), as it is intended
149      * to be used only by Hipparchus classes since it relied on the ordering of
150      * derivatives within the class. This allows avoiding checks on the index,
151      * for performance reasons.
152      * </p>
153      * @param index index of the derivative
154      * @return value of the derivative
155      * @since 2.2
156      */
157     double getDerivativeComponent(final int index) {
158         return data[index];
159     }
160 
161     /** {@inheritDoc} */
162     @Override
163     public DerivativeStructure getAddendum() {
164         final double[] addendum = data.clone();
165         addendum[0] = 0;
166         return new DerivativeStructure(factory, addendum);
167     }
168 
169     /** Get the value part of the derivative structure.
170      * @return value part of the derivative structure
171      * @see #getPartialDerivative(int...)
172      */
173     @Override
174     public double getValue() {
175         return data[0];
176     }
177 
178     /** {@inheritDoc} */
179     @Override
180     public double getPartialDerivative(final int ... orders)
181         throws MathIllegalArgumentException {
182         return data[getFactory().getCompiler().getPartialDerivativeIndex(orders)];
183     }
184 
185     /** Get all partial derivatives.
186      * @return a fresh copy of partial derivatives, in an array sorted according to
187      * {@link DSCompiler#getPartialDerivativeIndex(int...)}
188      */
189     public double[] getAllDerivatives() {
190         return data.clone();
191     }
192 
193     /** {@inheritDoc}
194      * @exception MathIllegalArgumentException if number of free parameters
195      * or orders do not match
196      */
197     @Override
198     public DerivativeStructure add(final DerivativeStructure a)
199         throws MathIllegalArgumentException {
200         factory.checkCompatibility(a.factory);
201         final DerivativeStructure ds = factory.build();
202         factory.getCompiler().add(data, 0, a.data, 0, ds.data, 0);
203         return ds;
204     }
205 
206     /** {@inheritDoc}
207      * @exception MathIllegalArgumentException if number of free parameters
208      * or orders do not match
209      */
210     @Override
211     public DerivativeStructure subtract(final DerivativeStructure a)
212         throws MathIllegalArgumentException {
213         factory.checkCompatibility(a.factory);
214         final DerivativeStructure ds = factory.build();
215         factory.getCompiler().subtract(data, 0, a.data, 0, ds.data, 0);
216         return ds;
217     }
218 
219     /** {@inheritDoc}
220      */
221     @Override
222     public DerivativeStructure multiply(final double a) {
223         final DerivativeStructure ds = factory.build();
224         for (int i = 0; i < ds.data.length; ++i) {
225             ds.data[i] = data[i] * a;
226         }
227         return ds;
228     }
229 
230     /** {@inheritDoc}
231      * @exception MathIllegalArgumentException if number of free parameters
232      * or orders do not match
233      */
234     @Override
235     public DerivativeStructure multiply(final DerivativeStructure a)
236         throws MathIllegalArgumentException {
237         factory.checkCompatibility(a.factory);
238         final DerivativeStructure result = factory.build();
239         factory.getCompiler().multiply(data, 0, a.data, 0, result.data, 0);
240         return result;
241     }
242 
243     /** {@inheritDoc} */
244     @Override
245     public DerivativeStructure square() {
246         return multiply(this);
247     }
248 
249     /** {@inheritDoc}
250      */
251     @Override
252     public DerivativeStructure divide(final double a) {
253         final DerivativeStructure ds = factory.build();
254         final double inv = 1.0 / a;
255         for (int i = 0; i < ds.data.length; ++i) {
256             ds.data[i] = data[i] * inv;
257         }
258         return ds;
259     }
260 
261     /** {@inheritDoc}
262      * @exception MathIllegalArgumentException if number of free parameters
263      * or orders do not match
264      */
265     @Override
266     public DerivativeStructure divide(final DerivativeStructure a)
267         throws MathIllegalArgumentException {
268         factory.checkCompatibility(a.factory);
269         final DerivativeStructure result = factory.build();
270         factory.getCompiler().divide(data, 0, a.data, 0, result.data, 0);
271         return result;
272     }
273 
274     /** {@inheritDoc}
275      * @exception MathIllegalArgumentException if number of free parameters
276      * or orders do not match
277      */
278     @Override
279     public DerivativeStructure remainder(final DerivativeStructure a)
280         throws MathIllegalArgumentException {
281         factory.checkCompatibility(a.factory);
282         final DerivativeStructure result = factory.build();
283         factory.getCompiler().remainder(data, 0, a.data, 0, result.data, 0);
284         return result;
285     }
286 
287     /** {@inheritDoc} */
288     @Override
289     public DerivativeStructure negate() {
290         final DerivativeStructure ds = factory.build();
291         for (int i = 0; i < ds.data.length; ++i) {
292             ds.data[i] = -data[i];
293         }
294         return ds;
295     }
296 
297     /** {@inheritDoc}
298      */
299     @Override
300     public DerivativeStructure abs() {
301         if (Double.doubleToLongBits(data[0]) < 0) {
302             // we use the bits representation to also handle -0.0
303             return negate();
304         } else {
305             return this;
306         }
307     }
308 
309     /** {@inheritDoc}
310      */
311     @Override
312     public DerivativeStructure copySign(final DerivativeStructure sign) {
313         long m = Double.doubleToLongBits(data[0]);
314         long s = Double.doubleToLongBits(sign.data[0]);
315         if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK
316             return this;
317         }
318         return negate(); // flip sign
319     }
320 
321     /** {@inheritDoc}
322      */
323     @Override
324     public DerivativeStructure copySign(final double sign) {
325         long m = Double.doubleToLongBits(data[0]);
326         long s = Double.doubleToLongBits(sign);
327         if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK
328             return this;
329         }
330         return negate(); // flip sign
331     }
332 
333     /** {@inheritDoc}
334      */
335     @Override
336     public DerivativeStructure scalb(final int n) {
337         final DerivativeStructure ds = factory.build();
338         for (int i = 0; i < ds.data.length; ++i) {
339             ds.data[i] = FastMath.scalb(data[i], n);
340         }
341         return ds;
342     }
343 
344     /** {@inheritDoc}
345      * @exception MathIllegalArgumentException if number of free parameters
346      * or orders do not match
347      */
348     @Override
349     public DerivativeStructure hypot(final DerivativeStructure y)
350         throws MathIllegalArgumentException {
351 
352         factory.checkCompatibility(y.factory);
353 
354         if (Double.isInfinite(data[0]) || Double.isInfinite(y.data[0])) {
355             return factory.constant(Double.POSITIVE_INFINITY);
356         } else if (Double.isNaN(data[0]) || Double.isNaN(y.data[0])) {
357             return factory.constant(Double.NaN);
358         } else {
359 
360             final int expX = getExponent();
361             final int expY = y.getExponent();
362             if (expX > expY + 27) {
363                 // y is negligible with respect to x
364                 return abs();
365             } else if (expY > expX + 27) {
366                 // x is negligible with respect to y
367                 return y.abs();
368             } else {
369 
370                 // find an intermediate scale to avoid both overflow and underflow
371                 final int middleExp = (expX + expY) / 2;
372 
373                 // scale parameters without losing precision
374                 final DerivativeStructure scaledX = scalb(-middleExp);
375                 final DerivativeStructure scaledY = y.scalb(-middleExp);
376 
377                 // compute scaled hypotenuse
378                 final DerivativeStructure scaledH =
379                         scaledX.multiply(scaledX).add(scaledY.multiply(scaledY)).sqrt();
380 
381                 // remove scaling
382                 return scaledH.scalb(middleExp);
383 
384             }
385 
386         }
387     }
388 
389     /**
390      * Returns the hypotenuse of a triangle with sides {@code x} and {@code y}
391      * - sqrt(<i>x</i><sup>2</sup>&nbsp;+<i>y</i><sup>2</sup>)
392      * avoiding intermediate overflow or underflow.
393      *
394      * <ul>
395      * <li> If either argument is infinite, then the result is positive infinity.</li>
396      * <li> else, if either argument is NaN then the result is NaN.</li>
397      * </ul>
398      *
399      * @param x a value
400      * @param y a value
401      * @return sqrt(<i>x</i><sup>2</sup>&nbsp;+<i>y</i><sup>2</sup>)
402      * @exception MathIllegalArgumentException if number of free parameters
403      * or orders do not match
404      */
405     public static DerivativeStructure hypot(final DerivativeStructure x, final DerivativeStructure y)
406         throws MathIllegalArgumentException {
407         return x.hypot(y);
408     }
409 
410     /** Compute composition of the instance by a univariate function.
411      * @param f array of value and derivatives of the function at
412      * the current point (i.e. [f({@link #getValue()}),
413      * f'({@link #getValue()}), f''({@link #getValue()})...]).
414      * @return f(this)
415      * @exception MathIllegalArgumentException if the number of derivatives
416      * in the array is not equal to {@link #getOrder() order} + 1
417      */
418     @Override
419     public DerivativeStructure compose(final double ... f)
420         throws MathIllegalArgumentException {
421 
422         MathUtils.checkDimension(f.length, getOrder() + 1);
423         final DerivativeStructure result = factory.build();
424         factory.getCompiler().compose(data, 0, f, result.data, 0);
425         return result;
426     }
427 
428     /** {@inheritDoc} */
429     @Override
430     public DerivativeStructure reciprocal() {
431         final DerivativeStructure result = factory.build();
432         factory.getCompiler().reciprocal(data, 0, result.data, 0);
433         return result;
434     }
435 
436     /** {@inheritDoc}
437      */
438     @Override
439     public DerivativeStructure sqrt() {
440         final DerivativeStructure result = factory.build();
441         factory.getCompiler().sqrt(data, 0, result.data, 0);
442         return result;
443     }
444 
445     /** {@inheritDoc}
446      */
447     @Override
448     public DerivativeStructure rootN(final int n) {
449         final DerivativeStructure result = factory.build();
450         factory.getCompiler().rootN(data, 0, n, result.data, 0);
451         return result;
452     }
453 
454     /** {@inheritDoc} */
455     @Override
456     public Field<DerivativeStructure> getField() {
457         return factory.getDerivativeField();
458     }
459 
460     /** Compute a<sup>x</sup> where a is a double and x a {@link DerivativeStructure}
461      * @param a number to exponentiate
462      * @param x power to apply
463      * @return a<sup>x</sup>
464      */
465     public static DerivativeStructure pow(final double a, final DerivativeStructure x) {
466         final DerivativeStructure result = x.factory.build();
467         x.factory.getCompiler().pow(a, x.data, 0, result.data, 0);
468         return result;
469     }
470 
471     /** {@inheritDoc}
472      */
473     @Override
474     public DerivativeStructure pow(final double p) {
475         final DerivativeStructure result = factory.build();
476         factory.getCompiler().pow(data, 0, p, result.data, 0);
477         return result;
478     }
479 
480     /** {@inheritDoc}
481      */
482     @Override
483     public DerivativeStructure pow(final int n) {
484         final DerivativeStructure result = factory.build();
485         factory.getCompiler().pow(data, 0, n, result.data, 0);
486         return result;
487     }
488 
489     /** {@inheritDoc}
490      * @exception MathIllegalArgumentException if number of free parameters
491      * or orders do not match
492      */
493     @Override
494     public DerivativeStructure pow(final DerivativeStructure e)
495         throws MathIllegalArgumentException {
496         factory.checkCompatibility(e.factory);
497         final DerivativeStructure result = factory.build();
498         factory.getCompiler().pow(data, 0, e.data, 0, result.data, 0);
499         return result;
500     }
501 
502     /** {@inheritDoc}
503      */
504     @Override
505     public DerivativeStructure exp() {
506         final DerivativeStructure result = factory.build();
507         factory.getCompiler().exp(data, 0, result.data, 0);
508         return result;
509     }
510 
511     /** {@inheritDoc}
512      */
513     @Override
514     public DerivativeStructure expm1() {
515         final DerivativeStructure result = factory.build();
516         factory.getCompiler().expm1(data, 0, result.data, 0);
517         return result;
518     }
519 
520     /** {@inheritDoc}
521      */
522     @Override
523     public DerivativeStructure log() {
524         final DerivativeStructure result = factory.build();
525         factory.getCompiler().log(data, 0, result.data, 0);
526         return result;
527     }
528 
529     /** {@inheritDoc}
530      */
531     @Override
532     public DerivativeStructure log1p() {
533         final DerivativeStructure result = factory.build();
534         factory.getCompiler().log1p(data, 0, result.data, 0);
535         return result;
536     }
537 
538     /** Base 10 logarithm.
539      * @return base 10 logarithm of the instance
540      */
541     @Override
542     public DerivativeStructure log10() {
543         final DerivativeStructure result = factory.build();
544         factory.getCompiler().log10(data, 0, result.data, 0);
545         return result;
546     }
547 
548     /** {@inheritDoc}
549      */
550     @Override
551     public DerivativeStructure cos() {
552         final DerivativeStructure result = factory.build();
553         factory.getCompiler().cos(data, 0, result.data, 0);
554         return result;
555     }
556 
557     /** {@inheritDoc}
558      */
559     @Override
560     public DerivativeStructure sin() {
561         final DerivativeStructure result = factory.build();
562         factory.getCompiler().sin(data, 0, result.data, 0);
563         return result;
564     }
565 
566     /** {@inheritDoc}
567      */
568     @Override
569     public FieldSinCos<DerivativeStructure> sinCos() {
570         final DerivativeStructure sin = factory.build();
571         final DerivativeStructure cos = factory.build();
572         factory.getCompiler().sinCos(data, 0, sin.data, 0, cos.data, 0);
573         return new FieldSinCos<>(sin, cos);
574     }
575 
576     /** {@inheritDoc}
577      */
578     @Override
579     public DerivativeStructure tan() {
580         final DerivativeStructure result = factory.build();
581         factory.getCompiler().tan(data, 0, result.data, 0);
582         return result;
583     }
584 
585     /** {@inheritDoc}
586      */
587     @Override
588     public DerivativeStructure acos() {
589         final DerivativeStructure result = factory.build();
590         factory.getCompiler().acos(data, 0, result.data, 0);
591         return result;
592     }
593 
594     /** {@inheritDoc}
595      */
596     @Override
597     public DerivativeStructure asin() {
598         final DerivativeStructure result = factory.build();
599         factory.getCompiler().asin(data, 0, result.data, 0);
600         return result;
601     }
602 
603     /** {@inheritDoc}
604      */
605     @Override
606     public DerivativeStructure atan() {
607         final DerivativeStructure result = factory.build();
608         factory.getCompiler().atan(data, 0, result.data, 0);
609         return result;
610     }
611 
612     /** {@inheritDoc}
613      */
614     @Override
615     public DerivativeStructure atan2(final DerivativeStructure x)
616         throws MathIllegalArgumentException {
617         factory.checkCompatibility(x.factory);
618         final DerivativeStructure result = factory.build();
619         factory.getCompiler().atan2(data, 0, x.data, 0, result.data, 0);
620         return result;
621     }
622 
623     /** Two arguments arc tangent operation.
624      * @param y first argument of the arc tangent
625      * @param x second argument of the arc tangent
626      * @return atan2(y, x)
627      * @exception MathIllegalArgumentException if number of free parameters
628      * or orders do not match
629      */
630     public static DerivativeStructure atan2(final DerivativeStructure y, final DerivativeStructure x)
631         throws MathIllegalArgumentException {
632         return y.atan2(x);
633     }
634 
635     /** {@inheritDoc}
636      */
637     @Override
638     public DerivativeStructure cosh() {
639         final DerivativeStructure result = factory.build();
640         factory.getCompiler().cosh(data, 0, result.data, 0);
641         return result;
642     }
643 
644     /** {@inheritDoc}
645      */
646     @Override
647     public DerivativeStructure sinh() {
648         final DerivativeStructure result = factory.build();
649         factory.getCompiler().sinh(data, 0, result.data, 0);
650         return result;
651     }
652 
653     /** {@inheritDoc}
654      */
655     @Override
656     public FieldSinhCosh<DerivativeStructure> sinhCosh() {
657         final DerivativeStructure sinh = factory.build();
658         final DerivativeStructure cosh = factory.build();
659         factory.getCompiler().sinhCosh(data, 0, sinh.data, 0, cosh.data, 0);
660         return new FieldSinhCosh<>(sinh, cosh);
661     }
662 
663     /** {@inheritDoc}
664      */
665     @Override
666     public DerivativeStructure tanh() {
667         final DerivativeStructure result = factory.build();
668         factory.getCompiler().tanh(data, 0, result.data, 0);
669         return result;
670     }
671 
672     /** {@inheritDoc}
673      */
674     @Override
675     public DerivativeStructure acosh() {
676         final DerivativeStructure result = factory.build();
677         factory.getCompiler().acosh(data, 0, result.data, 0);
678         return result;
679     }
680 
681     /** {@inheritDoc}
682      */
683     @Override
684     public DerivativeStructure asinh() {
685         final DerivativeStructure result = factory.build();
686         factory.getCompiler().asinh(data, 0, result.data, 0);
687         return result;
688     }
689 
690     /** {@inheritDoc}
691      */
692     @Override
693     public DerivativeStructure atanh() {
694         final DerivativeStructure result = factory.build();
695         factory.getCompiler().atanh(data, 0, result.data, 0);
696         return result;
697     }
698 
699     /** {@inheritDoc} */
700     @Override
701     public DerivativeStructure toDegrees() {
702         final DerivativeStructure ds = factory.build();
703         for (int i = 0; i < ds.data.length; ++i) {
704             ds.data[i] = FastMath.toDegrees(data[i]);
705         }
706         return ds;
707     }
708 
709     /** {@inheritDoc} */
710     @Override
711     public DerivativeStructure toRadians() {
712         final DerivativeStructure ds = factory.build();
713         for (int i = 0; i < ds.data.length; ++i) {
714             ds.data[i] = FastMath.toRadians(data[i]);
715         }
716         return ds;
717     }
718 
719     /** Integrate w.r.t. one independent variable.
720      * <p>
721      * Rigorously, if the derivatives of a function are known up to
722      * order N, the ones of its M-th integral w.r.t. a given variable
723      * (seen as a function itself) are actually known up to order N+M.
724      * However, this method still casts the output as a DerivativeStructure
725      * of order N. The integration constants are systematically set to zero.
726      * </p>
727      * @param varIndex Index of independent variable w.r.t. which integration is done.
728      * @param integrationOrder Number of times the integration operator must be applied. If non-positive, call the
729      *                         differentiation operator.
730      * @return DerivativeStructure on which integration operator has been applied a certain number of times.
731      * @since 2.2
732      */
733     public DerivativeStructure integrate(final int varIndex, final int integrationOrder) {
734 
735         // Deal first with trivial case
736         if (integrationOrder > getOrder()) {
737             return factory.constant(0.);
738         } else if (integrationOrder == 0) {
739             return factory.build(data);
740         }
741 
742         // Call 'inverse' (not rigorously) operation if necessary
743         if (integrationOrder < 0) {
744             return differentiate(varIndex, -integrationOrder);
745         }
746 
747         final double[] newData = new double[data.length];
748         final DSCompiler dsCompiler = factory.getCompiler();
749         for (int i = 0; i < newData.length; i++) {
750             if (data[i] != 0.) {
751                 final int[] orders = dsCompiler.getPartialDerivativeOrders(i);
752                 int sum = 0;
753                 for (int order : orders) {
754                     sum += order;
755                 }
756                 if (sum + integrationOrder <= getOrder()) {
757                     final int saved = orders[varIndex];
758                     orders[varIndex] += integrationOrder;
759                     final int index = dsCompiler.getPartialDerivativeIndex(orders);
760                     orders[varIndex] = saved;
761                     newData[index] = data[i];
762                 }
763             }
764         }
765 
766         return factory.build(newData);
767     }
768 
769     /** Differentiate w.r.t. one independent variable.
770      * <p>
771      * Rigorously, if the derivatives of a function are known up to
772      * order N, the ones of its M-th derivative w.r.t. a given variable
773      * (seen as a function itself) are only known up to order N-M.
774      * However, this method still casts the output as a DerivativeStructure
775      * of order N with zeroes for the higher order terms.
776      * </p>
777      * @param varIndex Index of independent variable w.r.t. which differentiation is done.
778      * @param differentiationOrder Number of times the differentiation operator must be applied. If non-positive, call
779      *                             the integration operator instead.
780      * @return DerivativeStructure on which differentiation operator has been applied a certain number of times
781      * @since 2.2
782      */
783     public DerivativeStructure differentiate(final int varIndex, final int differentiationOrder) {
784 
785         // Deal first with trivial case
786         if (differentiationOrder > getOrder()) {
787             return factory.constant(0.);
788         } else if (differentiationOrder == 0) {
789             return factory.build(data);
790         }
791 
792         // Call 'inverse' (not rigorously) operation if necessary
793         if (differentiationOrder < 0) {
794             return integrate(varIndex, -differentiationOrder);
795         }
796 
797         final double[] newData = new double[data.length];
798         final DSCompiler dsCompiler = factory.getCompiler();
799         for (int i = 0; i < newData.length; i++) {
800             if (data[i] != 0.) {
801                 final int[] orders = dsCompiler.getPartialDerivativeOrders(i);
802                 if (orders[varIndex] - differentiationOrder >= 0) {
803                     final int saved = orders[varIndex];
804                     orders[varIndex] -= differentiationOrder;
805                     final int index = dsCompiler.getPartialDerivativeIndex(orders);
806                     orders[varIndex] = saved;
807                     newData[index] = data[i];
808                 }
809             }
810         }
811 
812         return factory.build(newData);
813     }
814 
815     /** Evaluate Taylor expansion a derivative structure.
816      * @param delta parameters offsets (&Delta;x, &Delta;y, ...)
817      * @return value of the Taylor expansion at x + &Delta;x, y + &Delta;y, ...
818      * @throws MathRuntimeException if factorials becomes too large
819      */
820     public double taylor(final double ... delta) throws MathRuntimeException {
821         return factory.getCompiler().taylor(data, 0, delta);
822     }
823 
824     /** Rebase instance with respect to low level parameter functions.
825      * <p>
826      * The instance is considered to be a function of {@link #getFreeParameters()
827      * n free parameters} up to order {@link #getOrder() o} \(f(p_0, p_1, \ldots p_{n-1})\).
828      * Its {@link #getPartialDerivative(int...) partial derivatives} are therefore
829      * \(f, \frac{\partial f}{\partial p_0}, \frac{\partial f}{\partial p_1}, \ldots
830      * \frac{\partial^2 f}{\partial p_0^2}, \frac{\partial^2 f}{\partial p_0 p_1},
831      * \ldots \frac{\partial^o f}{\partial p_{n-1}^o}\). The free parameters
832      * \(p_0, p_1, \ldots p_{n-1}\) are considered to be functions of \(m\) lower
833      * level other parameters \(q_0, q_1, \ldots q_{m-1}\).
834      * </p>
835      * \( \begin{align}
836      * p_0 &amp; = p_0(q_0, q_1, \ldots q_{m-1})\\
837      * p_1 &amp; = p_1(q_0, q_1, \ldots q_{m-1})\\
838      * p_{n-1} &amp; = p_{n-1}(q_0, q_1, \ldots q_{m-1})
839      * \end{align}\)
840      * <p>
841      * This method compute the composition of the partial derivatives of \(f\)
842      * and the partial derivatives of \(p_0, p_1, \ldots p_{n-1}\), i.e. the
843      * {@link #getPartialDerivative(int...) partial derivatives} of the value
844      * returned will be
845      * \(f, \frac{\partial f}{\partial q_0}, \frac{\partial f}{\partial q_1}, \ldots
846      * \frac{\partial^2 f}{\partial q_0^2}, \frac{\partial^2 f}{\partial q_0 q_1},
847      * \ldots \frac{\partial^o f}{\partial q_{m-1}^o}\).
848      * </p>
849      * <p>
850      * The number of parameters must match {@link #getFreeParameters()} and the
851      * derivation orders of the instance and parameters must also match.
852      * </p>
853      * @param p base parameters with respect to which partial derivatives
854      * were computed in the instance
855      * @return derivative structure with partial derivatives computed
856      * with respect to the lower level parameters used in the \(p_i\)
857      * @since 2.2
858      */
859     public DerivativeStructure rebase(final DerivativeStructure... p) {
860 
861         MathUtils.checkDimension(getFreeParameters(), p.length);
862 
863         // handle special case of no variables at all
864         if (p.length == 0) {
865             return this;
866         }
867 
868         final int pSize = p[0].getFactory().getCompiler().getSize();
869         final double[] pData = new double[p.length * pSize];
870         for (int i = 0; i < p.length; ++i) {
871             MathUtils.checkDimension(getOrder(), p[i].getOrder());
872             MathUtils.checkDimension(p[0].getFreeParameters(), p[i].getFreeParameters());
873             System.arraycopy(p[i].data, 0, pData, i * pSize, pSize);
874         }
875 
876         final DerivativeStructure result = p[0].factory.build();
877         factory.getCompiler().rebase(data, 0, p[0].factory.getCompiler(), pData, result.data, 0);
878         return result;
879 
880     }
881 
882     /** {@inheritDoc}
883      * @exception MathIllegalArgumentException if number of free parameters
884      * or orders do not match
885      */
886     @Override
887     public DerivativeStructure linearCombination(final DerivativeStructure[] a, final DerivativeStructure[] b)
888         throws MathIllegalArgumentException {
889 
890         // compute an accurate value, taking care of cancellations
891         final double[] aDouble = new double[a.length];
892         for (int i = 0; i < a.length; ++i) {
893             aDouble[i] = a[i].getValue();
894         }
895         final double[] bDouble = new double[b.length];
896         for (int i = 0; i < b.length; ++i) {
897             bDouble[i] = b[i].getValue();
898         }
899         final double accurateValue = MathArrays.linearCombination(aDouble, bDouble);
900 
901         // compute a simple value, with all partial derivatives
902         DerivativeStructure simpleValue = a[0].getField().getZero();
903         for (int i = 0; i < a.length; ++i) {
904             simpleValue = simpleValue.add(a[i].multiply(b[i]));
905         }
906 
907         // create a result with accurate value and all derivatives (not necessarily as accurate as the value)
908         final double[] all = simpleValue.getAllDerivatives();
909         all[0] = accurateValue;
910         return factory.build(all);
911 
912     }
913 
914     /** {@inheritDoc}
915      * @exception MathIllegalArgumentException if number of free parameters
916      * or orders do not match
917      */
918     @Override
919     public DerivativeStructure linearCombination(final double[] a, final DerivativeStructure[] b)
920         throws MathIllegalArgumentException {
921 
922         // compute an accurate value, taking care of cancellations
923         final double[] bDouble = new double[b.length];
924         for (int i = 0; i < b.length; ++i) {
925             bDouble[i] = b[i].getValue();
926         }
927         final double accurateValue = MathArrays.linearCombination(a, bDouble);
928 
929         // compute a simple value, with all partial derivatives
930         DerivativeStructure simpleValue = b[0].getField().getZero();
931         for (int i = 0; i < a.length; ++i) {
932             simpleValue = simpleValue.add(b[i].multiply(a[i]));
933         }
934 
935         // create a result with accurate value and all derivatives (not necessarily as accurate as the value)
936         final double[] all = simpleValue.getAllDerivatives();
937         all[0] = accurateValue;
938         return factory.build(all);
939 
940     }
941 
942     /** {@inheritDoc}
943      * @exception MathIllegalArgumentException if number of free parameters
944      * or orders do not match
945      */
946     @Override
947     public DerivativeStructure linearCombination(final DerivativeStructure a1, final DerivativeStructure b1,
948                                                  final DerivativeStructure a2, final DerivativeStructure b2)
949         throws MathIllegalArgumentException {
950 
951         // compute an accurate value, taking care of cancellations
952         final double accurateValue = MathArrays.linearCombination(a1.getValue(), b1.getValue(),
953                                                                   a2.getValue(), b2.getValue());
954 
955         // compute a simple value, with all partial derivatives
956         final DerivativeStructure simpleValue = a1.multiply(b1).add(a2.multiply(b2));
957 
958         // create a result with accurate value and all derivatives (not necessarily as accurate as the value)
959         final double[] all = simpleValue.getAllDerivatives();
960         all[0] = accurateValue;
961         return factory.build(all);
962 
963     }
964 
965     /** {@inheritDoc}
966      * @exception MathIllegalArgumentException if number of free parameters
967      * or orders do not match
968      */
969     @Override
970     public DerivativeStructure linearCombination(final double a1, final DerivativeStructure b1,
971                                                  final double a2, final DerivativeStructure b2)
972         throws MathIllegalArgumentException {
973 
974         factory.checkCompatibility(b1.factory);
975         factory.checkCompatibility(b2.factory);
976 
977         final DerivativeStructure ds = factory.build();
978         factory.getCompiler().linearCombination(a1, b1.data, 0,
979                                                 a2, b2.data, 0,
980                                                 ds.data, 0);
981 
982         return ds;
983 
984     }
985 
986     /** {@inheritDoc}
987      * @exception MathIllegalArgumentException if number of free parameters
988      * or orders do not match
989      */
990     @Override
991     public DerivativeStructure linearCombination(final DerivativeStructure a1, final DerivativeStructure b1,
992                                                  final DerivativeStructure a2, final DerivativeStructure b2,
993                                                  final DerivativeStructure a3, final DerivativeStructure b3)
994         throws MathIllegalArgumentException {
995 
996         // compute an accurate value, taking care of cancellations
997         final double accurateValue = MathArrays.linearCombination(a1.getValue(), b1.getValue(),
998                                                                   a2.getValue(), b2.getValue(),
999                                                                   a3.getValue(), b3.getValue());
1000 
1001         // compute a simple value, with all partial derivatives
1002         final DerivativeStructure simpleValue = a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3));
1003 
1004         // create a result with accurate value and all derivatives (not necessarily as accurate as the value)
1005         final double[] all = simpleValue.getAllDerivatives();
1006         all[0] = accurateValue;
1007         return factory.build(all);
1008 
1009     }
1010 
1011     /** {@inheritDoc}
1012      * @exception MathIllegalArgumentException if number of free parameters
1013      * or orders do not match
1014      */
1015     @Override
1016     public DerivativeStructure linearCombination(final double a1, final DerivativeStructure b1,
1017                                                  final double a2, final DerivativeStructure b2,
1018                                                  final double a3, final DerivativeStructure b3)
1019         throws MathIllegalArgumentException {
1020 
1021         factory.checkCompatibility(b1.factory);
1022         factory.checkCompatibility(b2.factory);
1023         factory.checkCompatibility(b3.factory);
1024 
1025         final DerivativeStructure ds = factory.build();
1026         factory.getCompiler().linearCombination(a1, b1.data, 0,
1027                                                 a2, b2.data, 0,
1028                                                 a3, b3.data, 0,
1029                                                 ds.data, 0);
1030 
1031         return ds;
1032 
1033     }
1034 
1035     /** {@inheritDoc}
1036      * @exception MathIllegalArgumentException if number of free parameters
1037      * or orders do not match
1038      */
1039     @Override
1040     public DerivativeStructure linearCombination(final DerivativeStructure a1, final DerivativeStructure b1,
1041                                                  final DerivativeStructure a2, final DerivativeStructure b2,
1042                                                  final DerivativeStructure a3, final DerivativeStructure b3,
1043                                                  final DerivativeStructure a4, final DerivativeStructure b4)
1044         throws MathIllegalArgumentException {
1045 
1046         // compute an accurate value, taking care of cancellations
1047         final double accurateValue = MathArrays.linearCombination(a1.getValue(), b1.getValue(),
1048                                                                   a2.getValue(), b2.getValue(),
1049                                                                   a3.getValue(), b3.getValue(),
1050                                                                   a4.getValue(), b4.getValue());
1051 
1052         // compute a simple value, with all partial derivatives
1053         final DerivativeStructure simpleValue = a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3)).add(a4.multiply(b4));
1054 
1055         // create a result with accurate value and all derivatives (not necessarily as accurate as the value)
1056         final double[] all = simpleValue.getAllDerivatives();
1057         all[0] = accurateValue;
1058         return factory.build(all);
1059 
1060     }
1061 
1062     /** {@inheritDoc}
1063      * @exception MathIllegalArgumentException if number of free parameters
1064      * or orders do not match
1065      */
1066     @Override
1067     public DerivativeStructure linearCombination(final double a1, final DerivativeStructure b1,
1068                                                  final double a2, final DerivativeStructure b2,
1069                                                  final double a3, final DerivativeStructure b3,
1070                                                  final double a4, final DerivativeStructure b4)
1071         throws MathIllegalArgumentException {
1072 
1073         factory.checkCompatibility(b1.factory);
1074         factory.checkCompatibility(b2.factory);
1075         factory.checkCompatibility(b3.factory);
1076         factory.checkCompatibility(b4.factory);
1077 
1078         final DerivativeStructure ds = factory.build();
1079         factory.getCompiler().linearCombination(a1, b1.data, 0,
1080                                                 a2, b2.data, 0,
1081                                                 a3, b3.data, 0,
1082                                                 a4, b4.data, 0,
1083                                                 ds.data, 0);
1084 
1085         return ds;
1086 
1087     }
1088 
1089     /** {@inheritDoc} */
1090     @Override
1091     public double norm() {
1092         double sum = 0;
1093         for (final double derivative: data) {
1094             sum += FastMath.abs(derivative);
1095         }
1096         return sum;
1097     }
1098 
1099     /** {@inheritDoc}
1100      */
1101     @Override
1102     public DerivativeStructure getPi() {
1103         return factory.getDerivativeField().getPi();
1104     }
1105 
1106     /** {@inheritDoc} */
1107     @Override
1108     public boolean isSmall(final DerivativeStructure base, final double relativeThreshold) {
1109         if (data.length != base.data.length) {
1110             throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
1111                                                    data.length, base.data.length);
1112         }
1113         boolean ok = true;
1114         for (int i = 0; i < data.length && ok; ++i) {
1115             ok = FastMath.abs(data[i]) <= FastMath.abs(base.data[i] * relativeThreshold);
1116         }
1117         return ok;
1118     }
1119 
1120     /**
1121      * Test for the equality of two derivative structures.
1122      * <p>
1123      * Derivative structures are considered equal if they have the same number
1124      * of free parameters, the same derivation order, and the same derivatives.
1125      * </p>
1126      * @param other Object to test for equality to this
1127      * @return true if two derivative structures are equal
1128      */
1129     @Override
1130     public boolean equals(Object other) {
1131 
1132         if (this == other) {
1133             return true;
1134         }
1135 
1136         if (other instanceof DerivativeStructure) {
1137             final DerivativeStructure rhs = (DerivativeStructure)other;
1138             return (getFreeParameters() == rhs.getFreeParameters()) &&
1139                    (getOrder() == rhs.getOrder()) &&
1140                    MathArrays.equals(data, rhs.data);
1141         }
1142 
1143         return false;
1144 
1145     }
1146 
1147     /**
1148      * Get a hashCode for the derivative structure.
1149      * @return a hash code value for this object
1150      */
1151     @Override
1152     public int hashCode() {
1153         return 227 + 229 * getFreeParameters() + 233 * getOrder() + 239 * MathUtils.hash(data);
1154     }
1155 
1156 }