FieldTLE.java

  1. /* Copyright 2002-2022 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS 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.  *   http://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.orekit.propagation.analytical.tle;

  18. import java.io.Serializable;
  19. import java.text.DecimalFormat;
  20. import java.text.DecimalFormatSymbols;
  21. import java.util.Collections;
  22. import java.util.List;
  23. import java.util.Locale;
  24. import java.util.Objects;

  25. import org.hipparchus.CalculusFieldElement;
  26. import org.hipparchus.Field;
  27. import org.hipparchus.geometry.euclidean.threed.Rotation;
  28. import org.hipparchus.util.ArithmeticUtils;
  29. import org.hipparchus.util.FastMath;
  30. import org.hipparchus.util.MathArrays;
  31. import org.hipparchus.util.MathUtils;
  32. import org.orekit.annotation.DefaultDataContext;
  33. import org.orekit.attitudes.InertialProvider;
  34. import org.orekit.data.DataContext;
  35. import org.orekit.errors.OrekitException;
  36. import org.orekit.errors.OrekitInternalError;
  37. import org.orekit.errors.OrekitMessages;
  38. import org.orekit.frames.Frame;
  39. import org.orekit.orbits.FieldEquinoctialOrbit;
  40. import org.orekit.orbits.FieldKeplerianOrbit;
  41. import org.orekit.orbits.FieldOrbit;
  42. import org.orekit.orbits.OrbitType;
  43. import org.orekit.orbits.PositionAngle;
  44. import org.orekit.propagation.FieldSpacecraftState;
  45. import org.orekit.time.DateComponents;
  46. import org.orekit.time.DateTimeComponents;
  47. import org.orekit.time.FieldAbsoluteDate;
  48. import org.orekit.time.FieldTimeStamped;
  49. import org.orekit.time.TimeComponents;
  50. import org.orekit.time.TimeScale;
  51. import org.orekit.utils.ParameterDriver;

  52. /** This class is a container for a single set of TLE data.
  53.  *
  54.  * <p>TLE sets can be built either by providing directly the two lines, in
  55.  * which case parsing is performed internally or by providing the already
  56.  * parsed elements.</p>
  57.  * <p>TLE are not transparently convertible to {@link org.orekit.orbits.Orbit Orbit}
  58.  * instances. They are significant only with respect to their dedicated {@link
  59.  * TLEPropagator propagator}, which also computes position and velocity coordinates.
  60.  * Any attempt to directly use orbital parameters like {@link #getE() eccentricity},
  61.  * {@link #getI() inclination}, etc. without any reference to the {@link TLEPropagator
  62.  * TLE propagator} is prone to errors.</p>
  63.  * <p>More information on the TLE format can be found on the
  64.  * <a href="https://www.celestrak.com/">CelesTrak website.</a></p>
  65.  * @author Fabien Maussion
  66.  * @author Luc Maisonobe
  67.  * @author Thomas Paulet (field translation)
  68.  * @since 11.0
  69.  */
  70. public class FieldTLE<T extends CalculusFieldElement<T>> implements FieldTimeStamped<T>, Serializable {

  71.     /** Identifier for default type of ephemeris (SGP4/SDP4). */
  72.     public static final int DEFAULT = 0;

  73.     /** Identifier for SGP type of ephemeris. */
  74.     public static final int SGP = 1;

  75.     /** Identifier for SGP4 type of ephemeris. */
  76.     public static final int SGP4 = 2;

  77.     /** Identifier for SDP4 type of ephemeris. */
  78.     public static final int SDP4 = 3;

  79.     /** Identifier for SGP8 type of ephemeris. */
  80.     public static final int SGP8 = 4;

  81.     /** Identifier for SDP8 type of ephemeris. */
  82.     public static final int SDP8 = 5;

  83.     /** Parameter name for B* coefficient. */
  84.     public static final String B_STAR = "BSTAR";

  85.     /** Default value for epsilon. */
  86.     private static final double EPSILON_DEFAULT = 1.0e-10;

  87.     /** Default value for maxIterations. */
  88.     private static final int MAX_ITERATIONS_DEFAULT = 100;

  89.     /** B* scaling factor.
  90.      * <p>
  91.      * We use a power of 2 to avoid numeric noise introduction
  92.      * in the multiplications/divisions sequences.
  93.      * </p>
  94.      */
  95.     private static final double B_STAR_SCALE = FastMath.scalb(1.0, -20);

  96.     /** Name of the mean motion parameter. */
  97.     private static final String MEAN_MOTION = "meanMotion";

  98.     /** Name of the inclination parameter. */
  99.     private static final String INCLINATION = "inclination";

  100.     /** Name of the eccentricity parameter. */
  101.     private static final String ECCENTRICITY = "eccentricity";

  102.     /** International symbols for parsing. */
  103.     private static final DecimalFormatSymbols SYMBOLS =
  104.         new DecimalFormatSymbols(Locale.US);

  105.     /** Serializable UID. */
  106.     private static final long serialVersionUID = -1596648022319057689L;

  107.     /** The satellite number. */
  108.     private final int satelliteNumber;

  109.     /** Classification (U for unclassified). */
  110.     private final char classification;

  111.     /** Launch year. */
  112.     private final int launchYear;

  113.     /** Launch number. */
  114.     private final int launchNumber;

  115.     /** Piece of launch (from "A" to "ZZZ"). */
  116.     private final String launchPiece;

  117.     /** Type of ephemeris. */
  118.     private final int ephemerisType;

  119.     /** Element number. */
  120.     private final int elementNumber;

  121.     /** the TLE current date. */
  122.     private final transient FieldAbsoluteDate<T> epoch;

  123.     /** Mean motion (rad/s). */
  124.     private final T meanMotion;

  125.     /** Mean motion first derivative (rad/s²). */
  126.     private final T meanMotionFirstDerivative;

  127.     /** Mean motion second derivative (rad/s³). */
  128.     private final T meanMotionSecondDerivative;

  129.     /** Eccentricity. */
  130.     private final T eccentricity;

  131.     /** Inclination (rad). */
  132.     private final T inclination;

  133.     /** Argument of perigee (rad). */
  134.     private final T pa;

  135.     /** Right Ascension of the Ascending node (rad). */
  136.     private final T raan;

  137.     /** Mean anomaly (rad). */
  138.     private final T meanAnomaly;

  139.     /** Revolution number at epoch. */
  140.     private final int revolutionNumberAtEpoch;

  141.     /** First line. */
  142.     private String line1;

  143.     /** Second line. */
  144.     private String line2;

  145.     /** The UTC scale. */
  146.     private final TimeScale utc;

  147.     /** Driver for ballistic coefficient parameter. */
  148.     private final transient ParameterDriver bStarParameterDriver;

  149.     /** Simple constructor from unparsed two lines. This constructor uses the {@link
  150.      * DataContext#getDefault() default data context}.
  151.      *
  152.      * <p>The static method {@link #isFormatOK(String, String)} should be called
  153.      * before trying to build this object.<p>
  154.      * @param field field utilized by default
  155.      * @param line1 the first element (69 char String)
  156.      * @param line2 the second element (69 char String)
  157.      * @see #FieldTLE(Field, String, String, TimeScale)
  158.      */
  159.     @DefaultDataContext
  160.     public FieldTLE(final Field<T> field, final String line1, final String line2) {
  161.         this(field, line1, line2, DataContext.getDefault().getTimeScales().getUTC());
  162.     }

  163.     /** Simple constructor from unparsed two lines using the given time scale as UTC.
  164.      *
  165.      *<p>This method uses the {@link DataContext#getDefault() default data context}.
  166.      *
  167.      * <p>The static method {@link #isFormatOK(String, String)} should be called
  168.      * before trying to build this object.<p>
  169.      * @param field field utilized by default
  170.      * @param line1 the first element (69 char String)
  171.      * @param line2 the second element (69 char String)
  172.      * @param utc the UTC time scale.
  173.      */
  174.     public FieldTLE(final Field<T> field, final String line1, final String line2, final TimeScale utc) {

  175.         // zero and pi for fields
  176.         final T zero = field.getZero();
  177.         final T pi   = zero.getPi();

  178.         // identification
  179.         satelliteNumber = ParseUtils.parseSatelliteNumber(line1, 2, 5);
  180.         final int satNum2 = ParseUtils.parseSatelliteNumber(line2, 2, 5);
  181.         if (satelliteNumber != satNum2) {
  182.             throw new OrekitException(OrekitMessages.TLE_LINES_DO_NOT_REFER_TO_SAME_OBJECT,
  183.                                       line1, line2);
  184.         }
  185.         classification  = line1.charAt(7);
  186.         launchYear      = ParseUtils.parseYear(line1, 9);
  187.         launchNumber    = ParseUtils.parseInteger(line1, 11, 3);
  188.         launchPiece     = line1.substring(14, 17).trim();
  189.         ephemerisType   = ParseUtils.parseInteger(line1, 62, 1);
  190.         elementNumber   = ParseUtils.parseInteger(line1, 64, 4);

  191.         // Date format transform (nota: 27/31250 == 86400/100000000)
  192.         final int    year      = ParseUtils.parseYear(line1, 18);
  193.         final int    dayInYear = ParseUtils.parseInteger(line1, 20, 3);
  194.         final long   df        = 27l * ParseUtils.parseInteger(line1, 24, 8);
  195.         final int    secondsA  = (int) (df / 31250l);
  196.         final double secondsB  = (df % 31250l) / 31250.0;
  197.         epoch = new FieldAbsoluteDate<>(field, new DateComponents(year, dayInYear),
  198.                                  new TimeComponents(secondsA, secondsB),
  199.                                  utc);

  200.         // mean motion development
  201.         // converted from rev/day, 2 * rev/day^2 and 6 * rev/day^3 to rad/s, rad/s^2 and rad/s^3
  202.         meanMotion                 = pi.multiply(ParseUtils.parseDouble(line2, 52, 11)).divide(43200.0);
  203.         meanMotionFirstDerivative  = pi.multiply(ParseUtils.parseDouble(line1, 33, 10)).divide(1.86624e9);
  204.         meanMotionSecondDerivative = pi.multiply(Double.parseDouble((line1.substring(44, 45) + '.' +
  205.                                                                      line1.substring(45, 50) + 'e' +
  206.                                                                      line1.substring(50, 52)).replace(' ', '0'))).divide(5.3747712e13);

  207.         eccentricity = zero.add(Double.parseDouble("." + line2.substring(26, 33).replace(' ', '0')));
  208.         inclination  = zero.add(FastMath.toRadians(ParseUtils.parseDouble(line2, 8, 8)));
  209.         pa           = zero.add(FastMath.toRadians(ParseUtils.parseDouble(line2, 34, 8)));
  210.         raan         = zero.add(FastMath.toRadians(Double.parseDouble(line2.substring(17, 25).replace(' ', '0'))));
  211.         meanAnomaly  = zero.add(FastMath.toRadians(ParseUtils.parseDouble(line2, 43, 8)));

  212.         revolutionNumberAtEpoch = ParseUtils.parseInteger(line2, 63, 5);
  213.         final double bStarValue = Double.parseDouble((line1.substring(53, 54) + '.' +
  214.                         line1.substring(54, 59) + 'e' +
  215.                         line1.substring(59, 61)).replace(' ', '0'));

  216.         // save the lines
  217.         this.line1 = line1;
  218.         this.line2 = line2;
  219.         this.utc = utc;

  220.         this.bStarParameterDriver = new ParameterDriver(B_STAR, bStarValue, B_STAR_SCALE,
  221.                                                         Double.NEGATIVE_INFINITY,
  222.                                                         Double.POSITIVE_INFINITY);

  223.     }

  224.     /**
  225.      * <p>
  226.      * Simple constructor from already parsed elements. This constructor uses the
  227.      * {@link DataContext#getDefault() default data context}.
  228.      * </p>
  229.      *
  230.      * <p>
  231.      * The mean anomaly, the right ascension of ascending node Ω and the argument of
  232.      * perigee ω are normalized into the [0, 2π] interval as they can be negative.
  233.      * After that, a range check is performed on some of the orbital elements:
  234.      *
  235.      * <pre>
  236.      *     meanMotion &gt;= 0
  237.      *     0 &lt;= i &lt;= π
  238.      *     0 &lt;= Ω &lt;= 2π
  239.      *     0 &lt;= e &lt;= 1
  240.      *     0 &lt;= ω &lt;= 2π
  241.      *     0 &lt;= meanAnomaly &lt;= 2π
  242.      * </pre>
  243.      *
  244.      *
  245.      * @param satelliteNumber satellite number
  246.      * @param classification classification (U for unclassified)
  247.      * @param launchYear launch year (all digits)
  248.      * @param launchNumber launch number
  249.      * @param launchPiece launch piece (3 char String)
  250.      * @param ephemerisType type of ephemeris
  251.      * @param elementNumber element number
  252.      * @param epoch elements epoch
  253.      * @param meanMotion mean motion (rad/s)
  254.      * @param meanMotionFirstDerivative mean motion first derivative (rad/s²)
  255.      * @param meanMotionSecondDerivative mean motion second derivative (rad/s³)
  256.      * @param e eccentricity
  257.      * @param i inclination (rad)
  258.      * @param pa argument of perigee (rad)
  259.      * @param raan right ascension of ascending node (rad)
  260.      * @param meanAnomaly mean anomaly (rad)
  261.      * @param revolutionNumberAtEpoch revolution number at epoch
  262.      * @param bStar ballistic coefficient
  263.      * @see #FieldTLE(int, char, int, int, String, int, int, FieldAbsoluteDate, CalculusFieldElement, CalculusFieldElement,
  264.      * CalculusFieldElement, CalculusFieldElement, CalculusFieldElement, CalculusFieldElement, CalculusFieldElement, CalculusFieldElement, int, double, TimeScale)
  265.      */
  266.     @DefaultDataContext
  267.     public FieldTLE(final int satelliteNumber, final char classification,
  268.                final int launchYear, final int launchNumber, final String launchPiece,
  269.                final int ephemerisType, final int elementNumber, final FieldAbsoluteDate<T> epoch,
  270.                final T meanMotion, final T meanMotionFirstDerivative,
  271.                final T meanMotionSecondDerivative, final T e, final T i,
  272.                final T pa, final T raan, final T meanAnomaly,
  273.                final int revolutionNumberAtEpoch, final double bStar) {
  274.         this(satelliteNumber, classification, launchYear, launchNumber, launchPiece,
  275.                 ephemerisType, elementNumber, epoch, meanMotion,
  276.                 meanMotionFirstDerivative, meanMotionSecondDerivative, e, i, pa, raan,
  277.                 meanAnomaly, revolutionNumberAtEpoch, bStar,
  278.                 DataContext.getDefault().getTimeScales().getUTC());
  279.     }

  280.     /**
  281.      * <p>
  282.      * Simple constructor from already parsed elements using the given time scale as
  283.      * UTC.
  284.      * </p>
  285.      * <p>
  286.      * The mean anomaly, the right ascension of ascending node Ω and the argument of
  287.      * perigee ω are normalized into the [0, 2π] interval as they can be negative.
  288.      * After that, a range check is performed on some of the orbital elements:
  289.      *
  290.      * <pre>
  291.      *     meanMotion &gt;= 0
  292.      *     0 &lt;= i &lt;= π
  293.      *     0 &lt;= Ω &lt;= 2π
  294.      *     0 &lt;= e &lt;= 1
  295.      *     0 &lt;= ω &lt;= 2π
  296.      *     0 &lt;= meanAnomaly &lt;= 2π
  297.      * </pre>
  298.      *
  299.      *
  300.      * @param satelliteNumber satellite number
  301.      * @param classification classification (U for unclassified)
  302.      * @param launchYear launch year (all digits)
  303.      * @param launchNumber launch number
  304.      * @param launchPiece launch piece (3 char String)
  305.      * @param ephemerisType type of ephemeris
  306.      * @param elementNumber element number
  307.      * @param epoch elements epoch
  308.      * @param meanMotion mean motion (rad/s)
  309.      * @param meanMotionFirstDerivative mean motion first derivative (rad/s²)
  310.      * @param meanMotionSecondDerivative mean motion second derivative (rad/s³)
  311.      * @param e eccentricity
  312.      * @param i inclination (rad)
  313.      * @param pa argument of perigee (rad)
  314.      * @param raan right ascension of ascending node (rad)
  315.      * @param meanAnomaly mean anomaly (rad)
  316.      * @param revolutionNumberAtEpoch revolution number at epoch
  317.      * @param bStar ballistic coefficient
  318.      * @param utc the UTC time scale.
  319.      */
  320.     public FieldTLE(final int satelliteNumber, final char classification,
  321.                final int launchYear, final int launchNumber, final String launchPiece,
  322.                final int ephemerisType, final int elementNumber, final FieldAbsoluteDate<T> epoch,
  323.                final T meanMotion, final T meanMotionFirstDerivative,
  324.                final T meanMotionSecondDerivative, final T e, final T i,
  325.                final T pa, final T raan, final T meanAnomaly,
  326.                final int revolutionNumberAtEpoch, final double bStar,
  327.                final TimeScale utc) {

  328.         // pi for fields
  329.         final T pi = e.getPi();

  330.         // identification
  331.         this.satelliteNumber = satelliteNumber;
  332.         this.classification  = classification;
  333.         this.launchYear      = launchYear;
  334.         this.launchNumber    = launchNumber;
  335.         this.launchPiece     = launchPiece;
  336.         this.ephemerisType   = ephemerisType;
  337.         this.elementNumber   = elementNumber;

  338.         // orbital parameters
  339.         this.epoch = epoch;
  340.         // Checking mean motion range
  341.         this.meanMotion = meanMotion;
  342.         this.meanMotionFirstDerivative = meanMotionFirstDerivative;
  343.         this.meanMotionSecondDerivative = meanMotionSecondDerivative;

  344.         // Checking inclination range
  345.         this.inclination = i;

  346.         // Normalizing RAAN in [0,2pi] interval
  347.         this.raan = MathUtils.normalizeAngle(raan, pi);

  348.         // Checking eccentricity range
  349.         this.eccentricity = e;

  350.         // Normalizing PA in [0,2pi] interval
  351.         this.pa = MathUtils.normalizeAngle(pa, pi);

  352.         // Normalizing mean anomaly in [0,2pi] interval
  353.         this.meanAnomaly = MathUtils.normalizeAngle(meanAnomaly, pi);

  354.         this.revolutionNumberAtEpoch = revolutionNumberAtEpoch;
  355.         this.bStarParameterDriver = new ParameterDriver(B_STAR, bStar, B_STAR_SCALE,
  356.                                                        Double.NEGATIVE_INFINITY,
  357.                                                        Double.POSITIVE_INFINITY);

  358.         // don't build the line until really needed
  359.         this.line1 = null;
  360.         this.line2 = null;
  361.         this.utc = utc;

  362.     }

  363.     /**
  364.      * Get the UTC time scale used to create this TLE.
  365.      *
  366.      * @return UTC time scale.
  367.      */
  368.     TimeScale getUtc() {
  369.         return utc;
  370.     }

  371.     /** Get the first line.
  372.      * @return first line
  373.      */
  374.     public String getLine1() {
  375.         if (line1 == null) {
  376.             buildLine1();
  377.         }
  378.         return line1;
  379.     }

  380.     /** Get the second line.
  381.      * @return second line
  382.      */
  383.     public String getLine2() {
  384.         if (line2 == null) {
  385.             buildLine2();
  386.         }
  387.         return line2;
  388.     }

  389.     /** Build the line 1 from the parsed elements.
  390.      */
  391.     private void buildLine1() {

  392.         final StringBuilder buffer = new StringBuilder();

  393.         buffer.append('1');

  394.         buffer.append(' ');
  395.         buffer.append(ParseUtils.buildSatelliteNumber(satelliteNumber, "satelliteNumber-1"));
  396.         buffer.append(classification);

  397.         buffer.append(' ');
  398.         buffer.append(ParseUtils.addPadding("launchYear",   launchYear % 100, '0', 2, true, satelliteNumber));
  399.         buffer.append(ParseUtils.addPadding("launchNumber", launchNumber, '0', 3, true, satelliteNumber));
  400.         buffer.append(ParseUtils.addPadding("launchPiece",  launchPiece, ' ', 3, false, satelliteNumber));

  401.         buffer.append(' ');
  402.         final DateTimeComponents dtc = epoch.getComponents(utc);
  403.         buffer.append(ParseUtils.addPadding("year", dtc.getDate().getYear() % 100, '0', 2, true, satelliteNumber));
  404.         buffer.append(ParseUtils.addPadding("day",  dtc.getDate().getDayOfYear(),  '0', 3, true, satelliteNumber));
  405.         buffer.append('.');
  406.         // nota: 31250/27 == 100000000/86400
  407.         final int fraction = (int) FastMath.rint(31250 * dtc.getTime().getSecondsInUTCDay() / 27.0);
  408.         buffer.append(ParseUtils.addPadding("fraction", fraction,  '0', 8, true, satelliteNumber));

  409.         buffer.append(' ');
  410.         final double n1 = meanMotionFirstDerivative.divide(pa.getPi()).multiply(1.86624e9).getReal();
  411.         final String sn1 = ParseUtils.addPadding("meanMotionFirstDerivative",
  412.                                                  new DecimalFormat(".00000000", SYMBOLS).format(n1),
  413.                                                  ' ', 10, true, satelliteNumber);
  414.         buffer.append(sn1);

  415.         buffer.append(' ');
  416.         final double n2 = meanMotionSecondDerivative.divide(pa.getPi()).multiply(5.3747712e13).getReal();
  417.         buffer.append(formatExponentMarkerFree("meanMotionSecondDerivative", n2, 5, ' ', 8, true));

  418.         buffer.append(' ');
  419.         buffer.append(formatExponentMarkerFree("B*", getBStar(), 5, ' ', 8, true));

  420.         buffer.append(' ');
  421.         buffer.append(ephemerisType);

  422.         buffer.append(' ');
  423.         buffer.append(ParseUtils.addPadding("elementNumber", elementNumber, ' ', 4, true, satelliteNumber));

  424.         buffer.append(Integer.toString(checksum(buffer)));

  425.         line1 = buffer.toString();

  426.     }

  427.     /** Format a real number without 'e' exponent marker.
  428.      * @param name parameter name
  429.      * @param d number to format
  430.      * @param mantissaSize size of the mantissa (not counting initial '-' or ' ' for sign)
  431.      * @param c padding character
  432.      * @param size desired size
  433.      * @param rightJustified if true, the resulting string is
  434.      * right justified (i.e. space are added to the left)
  435.      * @return formatted and padded number
  436.      */
  437.     private String formatExponentMarkerFree(final String name, final double d, final int mantissaSize,
  438.                                             final char c, final int size, final boolean rightJustified) {
  439.         final double dAbs = FastMath.abs(d);
  440.         int exponent = (dAbs < 1.0e-9) ? -9 : (int) FastMath.ceil(FastMath.log10(dAbs));
  441.         long mantissa = FastMath.round(dAbs * FastMath.pow(10.0, mantissaSize - exponent));
  442.         if (mantissa == 0) {
  443.             exponent = 0;
  444.         } else if (mantissa > (ArithmeticUtils.pow(10, mantissaSize) - 1)) {
  445.             // rare case: if d has a single digit like d = 1.0e-4 with mantissaSize = 5
  446.             // the above computation finds exponent = -4 and mantissa = 100000 which
  447.             // doesn't fit in a 5 digits string
  448.             exponent++;
  449.             mantissa = FastMath.round(dAbs * FastMath.pow(10.0, mantissaSize - exponent));
  450.         }
  451.         final String sMantissa = ParseUtils.addPadding(name, (int) mantissa,
  452.                                                        '0', mantissaSize, true, satelliteNumber);
  453.         final String sExponent = Integer.toString(FastMath.abs(exponent));
  454.         final String formatted = (d <  0 ? '-' : ' ') + sMantissa + (exponent <= 0 ? '-' : '+') + sExponent;

  455.         return ParseUtils.addPadding(name, formatted, c, size, rightJustified, satelliteNumber);

  456.     }

  457.     /** Build the line 2 from the parsed elements.
  458.      */
  459.     private void buildLine2() {

  460.         final StringBuilder buffer = new StringBuilder();
  461.         final DecimalFormat f34   = new DecimalFormat("##0.0000", SYMBOLS);
  462.         final DecimalFormat f211  = new DecimalFormat("#0.00000000", SYMBOLS);

  463.         buffer.append('2');

  464.         buffer.append(' ');
  465.         buffer.append(ParseUtils.buildSatelliteNumber(satelliteNumber, "satelliteNumber-2"));

  466.         buffer.append(' ');
  467.         buffer.append(ParseUtils.addPadding(INCLINATION, f34.format(FastMath.toDegrees(inclination).getReal()), ' ', 8, true, satelliteNumber));
  468.         buffer.append(' ');
  469.         buffer.append(ParseUtils.addPadding("raan", f34.format(FastMath.toDegrees(raan).getReal()), ' ', 8, true, satelliteNumber));
  470.         buffer.append(' ');
  471.         buffer.append(ParseUtils.addPadding(ECCENTRICITY, (int) FastMath.rint(eccentricity.getReal() * 1.0e7), '0', 7, true, satelliteNumber));
  472.         buffer.append(' ');
  473.         buffer.append(ParseUtils.addPadding("pa", f34.format(FastMath.toDegrees(pa).getReal()), ' ', 8, true, satelliteNumber));
  474.         buffer.append(' ');
  475.         buffer.append(ParseUtils.addPadding("meanAnomaly", f34.format(FastMath.toDegrees(meanAnomaly).getReal()), ' ', 8, true, satelliteNumber));

  476.         buffer.append(' ');
  477.         buffer.append(ParseUtils.addPadding(MEAN_MOTION, f211.format(meanMotion.divide(pa.getPi()).multiply(43200.0).getReal()), ' ', 11, true, satelliteNumber));
  478.         buffer.append(ParseUtils.addPadding("revolutionNumberAtEpoch", revolutionNumberAtEpoch,
  479.                                             ' ', 5, true, satelliteNumber));

  480.         buffer.append(Integer.toString(checksum(buffer)));

  481.         line2 = buffer.toString();

  482.     }

  483.     /** Get the drivers for TLE propagation SGP4 and SDP4.
  484.      * @return drivers for SGP4 and SDP4 model parameters
  485.      */
  486.     public List<ParameterDriver> getParametersDrivers() {
  487.         return Collections.singletonList(bStarParameterDriver);
  488.     }

  489.     /** Get model parameters.
  490.      * @param field field to which the elements belong
  491.      * @return model parameters
  492.      */
  493.     public T[] getParameters(final Field<T> field) {
  494.         final List<ParameterDriver> drivers = getParametersDrivers();
  495.         final T[] parameters = MathArrays.buildArray(field, drivers.size());
  496.         int i = 0;
  497.         for (ParameterDriver driver : drivers) {
  498.             parameters[i++] = field.getZero().add(driver.getValue());
  499.         }
  500.         return parameters;
  501.     }

  502.     /** Get the satellite id.
  503.      * @return the satellite number
  504.      */
  505.     public int getSatelliteNumber() {
  506.         return satelliteNumber;
  507.     }

  508.     /** Get the classification.
  509.      * @return classification
  510.      */
  511.     public char getClassification() {
  512.         return classification;
  513.     }

  514.     /** Get the launch year.
  515.      * @return the launch year
  516.      */
  517.     public int getLaunchYear() {
  518.         return launchYear;
  519.     }

  520.     /** Get the launch number.
  521.      * @return the launch number
  522.      */
  523.     public int getLaunchNumber() {
  524.         return launchNumber;
  525.     }

  526.     /** Get the launch piece.
  527.      * @return the launch piece
  528.      */
  529.     public String getLaunchPiece() {
  530.         return launchPiece;
  531.     }

  532.     /** Get the type of ephemeris.
  533.      * @return the ephemeris type (one of {@link #DEFAULT}, {@link #SGP},
  534.      * {@link #SGP4}, {@link #SGP8}, {@link #SDP4}, {@link #SDP8})
  535.      */
  536.     public int getEphemerisType() {
  537.         return ephemerisType;
  538.     }

  539.     /** Get the element number.
  540.      * @return the element number
  541.      */
  542.     public int getElementNumber() {
  543.         return elementNumber;
  544.     }

  545.     /** Get the TLE current date.
  546.      * @return the epoch
  547.      */
  548.     public FieldAbsoluteDate<T> getDate() {
  549.         return epoch;
  550.     }

  551.     /** Get the mean motion.
  552.      * @return the mean motion (rad/s)
  553.      */
  554.     public T getMeanMotion() {
  555.         return meanMotion;
  556.     }

  557.     /** Get the mean motion first derivative.
  558.      * @return the mean motion first derivative (rad/s²)
  559.      */
  560.     public T getMeanMotionFirstDerivative() {
  561.         return meanMotionFirstDerivative;
  562.     }

  563.     /** Get the mean motion second derivative.
  564.      * @return the mean motion second derivative (rad/s³)
  565.      */
  566.     public T getMeanMotionSecondDerivative() {
  567.         return meanMotionSecondDerivative;
  568.     }

  569.     /** Get the eccentricity.
  570.      * @return the eccentricity
  571.      */
  572.     public T getE() {
  573.         return eccentricity;
  574.     }

  575.     /** Get the inclination.
  576.      * @return the inclination (rad)
  577.      */
  578.     public T getI() {
  579.         return inclination;
  580.     }

  581.     /** Get the argument of perigee.
  582.      * @return omega (rad)
  583.      */
  584.     public T getPerigeeArgument() {
  585.         return pa;
  586.     }

  587.     /** Get Right Ascension of the Ascending node.
  588.      * @return the raan (rad)
  589.      */
  590.     public T getRaan() {
  591.         return raan;
  592.     }

  593.     /** Get the mean anomaly.
  594.      * @return the mean anomaly (rad)
  595.      */
  596.     public T getMeanAnomaly() {
  597.         return meanAnomaly;
  598.     }

  599.     /** Get the revolution number.
  600.      * @return the revolutionNumberAtEpoch
  601.      */
  602.     public int getRevolutionNumberAtEpoch() {
  603.         return revolutionNumberAtEpoch;
  604.     }

  605.     /** Get the ballistic coefficient.
  606.      * @return bStar
  607.      */
  608.     public double getBStar() {
  609.         return bStarParameterDriver.getValue();
  610.     }

  611.     /** Get a string representation of this TLE set.
  612.      * <p>The representation is simply the two lines separated by the
  613.      * platform line separator.</p>
  614.      * @return string representation of this TLE set
  615.      */
  616.     public String toString() {
  617.         try {
  618.             return getLine1() + System.getProperty("line.separator") + getLine2();
  619.         } catch (OrekitException oe) {
  620.             throw new OrekitInternalError(oe);
  621.         }
  622.     }

  623.     /**
  624.      * Convert Spacecraft State into TLE.
  625.      * This converter uses Newton method to reverse SGP4 and SDP4 propagation algorithm
  626.      * and generates a usable TLE version of a state.
  627.      * New TLE epoch is state epoch.
  628.      *
  629.      * <p>
  630.      * This method uses the {@link DataContext#getDefault() default data context},
  631.      * as well as {@link #EPSILON_DEFAULT} and {@link #MAX_ITERATIONS_DEFAULT} for method convergence.
  632.      *
  633.      * @param state Spacecraft State to convert into TLE
  634.      * @param templateTLE first guess used to get identification and estimate new TLE
  635.      * @param <T> type of the element
  636.      * @return TLE matching with Spacecraft State and template identification
  637.      * @see #stateToTLE(FieldSpacecraftState, FieldTLE, TimeScale, Frame)
  638.      * @see #stateToTLE(FieldSpacecraftState, FieldTLE, TimeScale, Frame, double, int)
  639.      * @since 11.0
  640.      */
  641.     @DefaultDataContext
  642.     public static <T extends CalculusFieldElement<T>> FieldTLE<T> stateToTLE(final FieldSpacecraftState<T> state, final FieldTLE<T> templateTLE) {
  643.         return stateToTLE(state, templateTLE,
  644.                           DataContext.getDefault().getTimeScales().getUTC(),
  645.                           DataContext.getDefault().getFrames().getTEME());
  646.     }

  647.     /**
  648.      * Convert Spacecraft State into TLE.
  649.      * This converter uses Newton method to reverse SGP4 and SDP4 propagation algorithm
  650.      * and generates a usable TLE version of a state.
  651.      * New TLE epoch is state epoch.
  652.      *
  653.      * <p>
  654.      * This method uses {@link #EPSILON_DEFAULT} and {@link #MAX_ITERATIONS_DEFAULT}
  655.      * for method convergence.
  656.      *
  657.      * @param state Spacecraft State to convert into TLE
  658.      * @param templateTLE first guess used to get identification and estimate new TLE
  659.      * @param utc the UTC time scale
  660.      * @param teme the TEME frame to use for propagation
  661.      * @param <T> type of the element
  662.      * @return TLE matching with Spacecraft State and template identification
  663.      * @see #stateToTLE(FieldSpacecraftState, FieldTLE, TimeScale, Frame, double, int)
  664.      * @since 11.0
  665.      */
  666.     public static <T extends CalculusFieldElement<T>> FieldTLE<T> stateToTLE(final FieldSpacecraftState<T> state, final FieldTLE<T> templateTLE,
  667.                                                                              final TimeScale utc, final Frame teme) {
  668.         return stateToTLE(state, templateTLE, utc, teme, EPSILON_DEFAULT, MAX_ITERATIONS_DEFAULT);
  669.     }

  670.     /**
  671.      * Convert Spacecraft State into TLE.
  672.      * This converter uses Newton method to reverse SGP4 and SDP4 propagation algorithm
  673.      * and generates a usable TLE version of a state.
  674.      * New TLE epoch is state epoch.
  675.      *
  676.      * @param state Spacecraft State to convert into TLE
  677.      * @param templateTLE first guess used to get identification and estimate new TLE
  678.      * @param utc the UTC time scale
  679.      * @param teme the TEME frame to use for propagation
  680.      * @param epsilon used to compute threshold for convergence check
  681.      * @param maxIterations maximum number of iterations for convergence
  682.      * @param <T> type of the element
  683.      * @return TLE matching with Spacecraft State and template identification
  684.      * @since 11.0
  685.      */
  686.     public static <T extends CalculusFieldElement<T>> FieldTLE<T> stateToTLE(final FieldSpacecraftState<T> state, final FieldTLE<T> templateTLE,
  687.                                                                              final TimeScale utc, final Frame teme,
  688.                                                                              final double epsilon, final int maxIterations) {

  689.         // Gets equinoctial parameters in TEME frame from state
  690.         final FieldEquinoctialOrbit<T> equiOrbit = convert(state.getOrbit(), teme);
  691.         T sma = equiOrbit.getA();
  692.         T ex  = equiOrbit.getEquinoctialEx();
  693.         T ey  = equiOrbit.getEquinoctialEy();
  694.         T hx  = equiOrbit.getHx();
  695.         T hy  = equiOrbit.getHy();
  696.         T lv  = equiOrbit.getLv();

  697.         // Rough initialization of the TLE
  698.         final FieldKeplerianOrbit<T> keplerianOrbit = (FieldKeplerianOrbit<T>) OrbitType.KEPLERIAN.convertType(equiOrbit);
  699.         FieldTLE<T> current = newTLE(keplerianOrbit, templateTLE, utc);

  700.         // Field
  701.         final Field<T> field = state.getDate().getField();

  702.         // threshold for each parameter
  703.         final T thrA = sma.add(1).multiply(epsilon);
  704.         final T thrE = FastMath.hypot(ex, ey).add(1).multiply(epsilon);
  705.         final T thrH = FastMath.hypot(hx, hy).add(1).multiply(epsilon);
  706.         final T thrV = sma.getPi().multiply(epsilon);

  707.         int k = 0;
  708.         while (k++ < maxIterations) {

  709.             // recompute the state from the current TLE
  710.             final FieldTLEPropagator<T> propagator = FieldTLEPropagator.selectExtrapolator(current, new InertialProvider(Rotation.IDENTITY, teme), state.getMass(), teme, templateTLE.getParameters(field));
  711.             final FieldOrbit<T> recovOrbit = propagator.getInitialState().getOrbit();
  712.             final FieldEquinoctialOrbit<T> recovEquiOrbit = (FieldEquinoctialOrbit<T>) OrbitType.EQUINOCTIAL.convertType(recovOrbit);

  713.             // adapted parameters residuals
  714.             final T deltaSma = equiOrbit.getA().subtract(recovEquiOrbit.getA());
  715.             final T deltaEx  = equiOrbit.getEquinoctialEx().subtract(recovEquiOrbit.getEquinoctialEx());
  716.             final T deltaEy  = equiOrbit.getEquinoctialEy().subtract(recovEquiOrbit.getEquinoctialEy());
  717.             final T deltaHx  = equiOrbit.getHx().subtract(recovEquiOrbit.getHx());
  718.             final T deltaHy  = equiOrbit.getHy().subtract(recovEquiOrbit.getHy());
  719.             final T deltaLv  = MathUtils.normalizeAngle(equiOrbit.getLv().subtract(recovEquiOrbit.getLv()), field.getZero());

  720.             // check convergence
  721.             if (FastMath.abs(deltaSma.getReal()) < thrA.getReal() &&
  722.                 FastMath.abs(deltaEx.getReal())  < thrE.getReal() &&
  723.                 FastMath.abs(deltaEy.getReal())  < thrE.getReal() &&
  724.                 FastMath.abs(deltaHx.getReal())  < thrH.getReal() &&
  725.                 FastMath.abs(deltaHy.getReal())  < thrH.getReal() &&
  726.                 FastMath.abs(deltaLv.getReal())  < thrV.getReal()) {

  727.                 return current;
  728.             }

  729.             // update state
  730.             sma = sma.add(deltaSma);
  731.             ex  = ex.add(deltaEx);
  732.             ey  = ey.add(deltaEy);
  733.             hx  = hx.add(deltaHx);
  734.             hy  = hy.add(deltaHy);
  735.             lv  = lv.add(deltaLv);
  736.             final FieldEquinoctialOrbit<T> newEquiOrbit =
  737.                                     new FieldEquinoctialOrbit<>(sma, ex, ey, hx, hy, lv, PositionAngle.TRUE,
  738.                                     equiOrbit.getFrame(), equiOrbit.getDate(), equiOrbit.getMu());
  739.             final FieldKeplerianOrbit<T> newKeplOrbit = (FieldKeplerianOrbit<T>) OrbitType.KEPLERIAN.convertType(newEquiOrbit);

  740.             // update TLE
  741.             current = newTLE(newKeplOrbit, templateTLE, utc);
  742.         }

  743.         throw new OrekitException(OrekitMessages.UNABLE_TO_COMPUTE_TLE, k);
  744.     }

  745.     /**
  746.      * Converts an orbit into an equinoctial orbit expressed in TEME frame.
  747.      *
  748.      * @param orbitIn the orbit to convert
  749.      * @param teme the TEME frame to use for propagation
  750.      * @param <T> type of the element
  751.      * @return the converted orbit, i.e. equinoctial in TEME frame
  752.      */
  753.     private static <T extends CalculusFieldElement<T>> FieldEquinoctialOrbit<T> convert(final FieldOrbit<T> orbitIn, final Frame teme) {
  754.         return new FieldEquinoctialOrbit<T>(orbitIn.getPVCoordinates(teme), teme, orbitIn.getMu());
  755.     }

  756.     /**
  757.      * Builds a new TLE from Keplerian parameters and a template for TLE data.
  758.      * @param keplerianOrbit the Keplerian parameters to build the TLE from
  759.      * @param templateTLE TLE used to get object identification
  760.      * @param utc the UTC time scale
  761.      * @param <T> type of the element
  762.      * @return TLE with template identification and new orbital parameters
  763.      */
  764.     private static <T extends CalculusFieldElement<T>> FieldTLE<T> newTLE(final FieldKeplerianOrbit<T> keplerianOrbit, final FieldTLE<T> templateTLE,
  765.                                                                           final TimeScale utc) {
  766.         // Keplerian parameters
  767.         final T meanMotion  = keplerianOrbit.getKeplerianMeanMotion();
  768.         final T e           = keplerianOrbit.getE();
  769.         final T i           = keplerianOrbit.getI();
  770.         final T raan        = keplerianOrbit.getRightAscensionOfAscendingNode();
  771.         final T pa          = keplerianOrbit.getPerigeeArgument();
  772.         final T meanAnomaly = keplerianOrbit.getMeanAnomaly();
  773.         // TLE epoch is state epoch
  774.         final FieldAbsoluteDate<T> epoch = keplerianOrbit.getDate();
  775.         // Identification
  776.         final int satelliteNumber = templateTLE.getSatelliteNumber();
  777.         final char classification = templateTLE.getClassification();
  778.         final int launchYear = templateTLE.getLaunchYear();
  779.         final int launchNumber = templateTLE.getLaunchNumber();
  780.         final String launchPiece = templateTLE.getLaunchPiece();
  781.         final int ephemerisType = templateTLE.getEphemerisType();
  782.         final int elementNumber = templateTLE.getElementNumber();
  783.         // Updates revolutionNumberAtEpoch
  784.         final int revolutionNumberAtEpoch = templateTLE.getRevolutionNumberAtEpoch();
  785.         final T dt = epoch.durationFrom(templateTLE.getDate());
  786.         final int newRevolutionNumberAtEpoch = (int) ((int) revolutionNumberAtEpoch + FastMath.floor(MathUtils.normalizeAngle(meanAnomaly, e.getPi()).add(dt.multiply(meanMotion)).divide(e.getPi().multiply(2.0))).getReal());
  787.         // Gets B*
  788.         final double bStar = templateTLE.getBStar();
  789.         // Gets Mean Motion derivatives
  790.         final T meanMotionFirstDerivative = templateTLE.getMeanMotionFirstDerivative();
  791.         final T meanMotionSecondDerivative = templateTLE.getMeanMotionSecondDerivative();
  792.         // Returns the new TLE
  793.         return new FieldTLE<>(satelliteNumber, classification, launchYear, launchNumber, launchPiece, ephemerisType,
  794.                        elementNumber, epoch, meanMotion, meanMotionFirstDerivative, meanMotionSecondDerivative,
  795.                        e, i, pa, raan, meanAnomaly, newRevolutionNumberAtEpoch, bStar, utc);
  796.     }


  797.     /** Check the lines format validity.
  798.      * @param line1 the first element
  799.      * @param line2 the second element
  800.      * @return true if format is recognized (non null lines, 69 characters length,
  801.      * line content), false if not
  802.      */
  803.     public static boolean isFormatOK(final String line1, final String line2) {
  804.         return TLE.isFormatOK(line1, line2);
  805.     }

  806.     /** Compute the checksum of the first 68 characters of a line.
  807.      * @param line line to check
  808.      * @return checksum
  809.      */
  810.     private static int checksum(final CharSequence line) {
  811.         int sum = 0;
  812.         for (int j = 0; j < 68; j++) {
  813.             final char c = line.charAt(j);
  814.             if (Character.isDigit(c)) {
  815.                 sum += Character.digit(c, 10);
  816.             } else if (c == '-') {
  817.                 ++sum;
  818.             }
  819.         }
  820.         return sum % 10;
  821.     }

  822.     /**
  823.      * Convert FieldTLE into TLE.
  824.      * @return TLE
  825.      */
  826.     public TLE toTLE() {
  827.         final TLE regularTLE = new TLE(getSatelliteNumber(), getClassification(), getLaunchYear(), getLaunchNumber(), getLaunchPiece(), getEphemerisType(),
  828.                                        getElementNumber(), getDate().toAbsoluteDate(), getMeanMotion().getReal(), getMeanMotionFirstDerivative().getReal(),
  829.                                        getMeanMotionSecondDerivative().getReal(), getE().getReal(), getI().getReal(), getPerigeeArgument().getReal(),
  830.                                        getRaan().getReal(), getMeanAnomaly().getReal(), getRevolutionNumberAtEpoch(), getBStar(), getUtc());

  831.         for (int k = 0; k < regularTLE.getParametersDrivers().size(); ++k) {
  832.             regularTLE.getParametersDrivers().get(k).setSelected(getParametersDrivers().get(k).isSelected());
  833.         }

  834.         return regularTLE;

  835.     }

  836.     /** Check if this tle equals the provided tle.
  837.      * <p>Due to the difference in precision between object and string
  838.      * representations of TLE, it is possible for this method to return false
  839.      * even if string representations returned by {@link #toString()}
  840.      * are equal.</p>
  841.      * @param o other tle
  842.      * @return true if this tle equals the provided tle
  843.      */
  844.     @Override
  845.     public boolean equals(final Object o) {
  846.         if (o == this) {
  847.             return true;
  848.         }
  849.         if (!(o instanceof FieldTLE)) {
  850.             return false;
  851.         }
  852.         @SuppressWarnings("unchecked")
  853.         final FieldTLE<T> tle = (FieldTLE<T>) o;
  854.         return satelliteNumber == tle.satelliteNumber &&
  855.                 classification == tle.classification &&
  856.                 launchYear == tle.launchYear &&
  857.                 launchNumber == tle.launchNumber &&
  858.                 Objects.equals(launchPiece, tle.launchPiece) &&
  859.                 ephemerisType == tle.ephemerisType &&
  860.                 elementNumber == tle.elementNumber &&
  861.                 Objects.equals(epoch, tle.epoch) &&
  862.                 meanMotion.getReal() == tle.meanMotion.getReal() &&
  863.                 meanMotionFirstDerivative.getReal() == tle.meanMotionFirstDerivative.getReal() &&
  864.                 meanMotionSecondDerivative.getReal() == tle.meanMotionSecondDerivative.getReal() &&
  865.                 eccentricity.getReal() == tle.eccentricity.getReal() &&
  866.                 inclination.getReal() == tle.inclination.getReal() &&
  867.                 pa.getReal() == tle.pa.getReal() &&
  868.                 raan.getReal() == tle.raan.getReal() &&
  869.                 meanAnomaly.getReal() == tle.meanAnomaly.getReal() &&
  870.                 revolutionNumberAtEpoch == tle.revolutionNumberAtEpoch &&
  871.                 getBStar() == tle.getBStar();
  872.     }

  873.     /** Get a hashcode for this tle.
  874.      * @return hashcode
  875.      */
  876.     @Override
  877.     public int hashCode() {
  878.         return Objects.hash(satelliteNumber,
  879.                 classification,
  880.                 launchYear,
  881.                 launchNumber,
  882.                 launchPiece,
  883.                 ephemerisType,
  884.                 elementNumber,
  885.                 epoch,
  886.                 meanMotion,
  887.                 meanMotionFirstDerivative,
  888.                 meanMotionSecondDerivative,
  889.                 eccentricity,
  890.                 inclination,
  891.                 pa,
  892.                 raan,
  893.                 meanAnomaly,
  894.                 revolutionNumberAtEpoch,
  895.                 getBStar());
  896.     }

  897. }