1   /* Copyright 2002-2024 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.files.ccsds.ndm.adm.aem;
18  
19  import java.io.IOException;
20  import java.util.Date;
21  
22  import org.hipparchus.geometry.euclidean.threed.RotationOrder;
23  import org.orekit.data.DataContext;
24  import org.orekit.errors.OrekitInternalError;
25  import org.orekit.files.ccsds.definitions.TimeSystem;
26  import org.orekit.files.ccsds.definitions.Units;
27  import org.orekit.files.ccsds.ndm.ParsedUnitsBehavior;
28  import org.orekit.files.ccsds.ndm.adm.AdmCommonMetadataKey;
29  import org.orekit.files.ccsds.ndm.adm.AdmHeader;
30  import org.orekit.files.ccsds.ndm.adm.AdmMetadataKey;
31  import org.orekit.files.ccsds.ndm.adm.AttitudeType;
32  import org.orekit.files.ccsds.section.Header;
33  import org.orekit.files.ccsds.section.HeaderKey;
34  import org.orekit.files.ccsds.section.KvnStructureKey;
35  import org.orekit.files.ccsds.section.MetadataKey;
36  import org.orekit.files.ccsds.section.XmlStructureKey;
37  import org.orekit.files.ccsds.utils.ContextBinding;
38  import org.orekit.files.ccsds.utils.FileFormat;
39  import org.orekit.files.ccsds.utils.generation.AbstractMessageWriter;
40  import org.orekit.files.ccsds.utils.generation.Generator;
41  import org.orekit.files.ccsds.utils.generation.XmlGenerator;
42  import org.orekit.time.AbsoluteDate;
43  import org.orekit.utils.IERSConventions;
44  import org.orekit.utils.TimeStampedAngularCoordinates;
45  import org.orekit.utils.units.Unit;
46  
47  /**
48   * A writer for Attitude Ephemeris Messsage (AEM) files.
49   *
50   * <h2> Metadata </h2>
51   *
52   * <p> The AEM header and metadata used by this writer are described in the following tables.
53   * Many metadata items are optional or have default values so they do not need to be specified.
54   * At a minimum the user must supply those values that are required and for which no
55   * default exits: {@link AdmMetadataKey#OBJECT_NAME}, {@link AdmCommonMetadataKey#OBJECT_ID},
56   * {@link AemMetadataKey#START_TIME} and {@link AemMetadataKey#STOP_TIME}.
57   * The usage column in the table indicates where the metadata item is used, either in the AEM header
58   * or in the metadata section at the start of an AEM attitude segment.
59   * </p>
60   *
61   * <p> The AEM header for the whole AEM file is set when calling {@link #writeHeader(Generator, Header)},
62   * the entries are defined in table 4-2 of the ADM standard.
63   *
64   * <table>
65   * <caption>AEM metadata</caption>
66   *     <thead>
67   *         <tr>
68   *             <th>Keyword</th>
69   *             <th>Mandatory</th>
70   *             <th>Default in Orekit</th>
71   *         </tr>
72   *    </thead>
73   *    <tbody>
74   *        <tr>
75   *            <td>{@link Aem#FORMAT_VERSION_KEY CCSDS_AEM_VERS}</td>
76   *            <td>Yes</td>
77   *            <td>{@link #CCSDS_AEM_VERS}</td>
78   *        </tr>
79   *        <tr>
80   *            <td>{@link HeaderKey#COMMENT}</td>
81   *            <td>No</td>
82   *            <td>empty</td>
83   *        </tr>
84   *        <tr>
85   *            <td>{@link HeaderKey#CREATION_DATE}</td>
86   *            <td>Yes</td>
87   *            <td>{@link Date#Date() Now}</td>
88   *        </tr>
89   *        <tr>
90   *            <td>{@link HeaderKey#ORIGINATOR}</td>
91   *            <td>Yes</td>
92   *            <td>{@link #DEFAULT_ORIGINATOR}</td>
93   *        </tr>
94   *    </tbody>
95   *    </table>
96   *
97   * <p> The AEM metadata for the AEM file is set when calling {@link #writeSegmentContent(Generator, double, AemSegment)},
98   * the entries are defined in tables 4-3, 4-4 and annex A of the ADM standard.
99   *
100  * <table>
101  * <caption>AEM metadata</caption>
102  *     <thead>
103  *         <tr>
104  *             <th>Keyword</th>
105  *             <th>Mandatory</th>
106  *             <th>Default in Orekit</th>
107  *         </tr>
108  *    </thead>
109  *    <tbody>
110  *        <tr>
111  *            <td>{@link MetadataKey#COMMENT}</td>
112  *            <td>No</td>
113  *            <td>empty</td>
114  *        </tr>
115  *        <tr>
116  *            <td>{@link AdmMetadataKey#OBJECT_NAME}</td>
117  *            <td>Yes</td>
118  *            <td></td>
119  *        </tr>
120  *        <tr>
121  *            <td>{@link AdmCommonMetadataKey#OBJECT_ID}</td>
122  *            <td>Yes</td>
123  *            <td></td>
124  *        </tr>
125  *        <tr>
126  *            <td>{@link AdmMetadataKey#CENTER_NAME}</td>
127  *            <td>No</td>
128  *            <td></td>
129  *        </tr>
130  *        <tr>
131  *            <td>{@link AemMetadataKey#REF_FRAME_A}</td>
132  *            <td>Yes</td>
133  *            <td></td>
134  *        </tr>
135  *        <tr>
136  *            <td>{@link AemMetadataKey#REF_FRAME_B}</td>
137  *            <td>Yes</td>
138  *            <td></td>
139  *        </tr>
140  *        <tr>
141  *            <td>{@link AemMetadataKey#ATTITUDE_DIR}</td>
142  *            <td>Yes</td>
143  *            <td></td>
144  *        </tr>
145  *        <tr>
146  *            <td>{@link MetadataKey#TIME_SYSTEM}</td>
147  *            <td>Yes</td>
148  *            <td></td>
149  *        </tr>
150  *        <tr>
151  *            <td>{@link AemMetadataKey#START_TIME}</td>
152  *            <td>Yes</td>
153  *            <td>default to propagation start time (for forward propagation)</td>
154  *        </tr>
155  *        <tr>
156  *            <td>{@link AemMetadataKey#USEABLE_START_TIME}</td>
157  *            <td>No</td>
158  *            <td></td>
159  *        </tr>
160  *        <tr>
161  *            <td>{@link AemMetadataKey#USEABLE_STOP_TIME}</td>
162  *            <td>No</td>
163  *            <td></td>
164  *        </tr>
165  *        <tr>
166  *            <td>{@link AemMetadataKey#STOP_TIME}</td>
167  *            <td>Yes</td>
168  *            <td>default to propagation target time (for forward propagation)</td>
169  *        </tr>
170  *        <tr>
171  *            <td>{@link AemMetadataKey#ATTITUDE_TYPE}</td>
172  *            <td>Yes</td>
173  *            <td>{@link AttitudeType#QUATERNION_DERIVATIVE QUATERNION/DERIVATIVE}</td>
174  *        </tr>
175  *        <tr>
176  *            <td>{@link AemMetadataKey#QUATERNION_TYPE}</td>
177  *            <td>No</td>
178  *            <td>{@code FIRST}</td>
179  *        </tr>
180  *        <tr>
181  *            <td>{@link AemMetadataKey#EULER_ROT_SEQ}</td>
182  *            <td>No</td>
183  *            <td></td>
184  *        </tr>
185  *        <tr>
186  *            <td>{@link AemMetadataKey#RATE_FRAME}</td>
187  *            <td>No</td>
188  *            <td>{@code REF_FRAME_B}</td>
189  *        </tr>
190  *        <tr>
191  *            <td>{@link AemMetadataKey#INTERPOLATION_METHOD}</td>
192  *            <td>No</td>
193  *            <td></td>
194  *        </tr>
195  *        <tr>
196  *            <td>{@link AemMetadataKey#INTERPOLATION_DEGREE}</td>
197  *            <td>No</td>
198  *            <td>always set in {@link AemMetadata}</td>
199  *        </tr>
200  *    </tbody>
201  *</table>
202  *
203  * <p> The {@link MetadataKey#TIME_SYSTEM} must be constant for the whole file and is used
204  * to interpret all dates except {@link HeaderKey#CREATION_DATE} which is always in {@link
205  * TimeSystem#UTC UTC}. The guessing algorithm is not guaranteed to work so it is recommended
206  * to provide values for {@link AdmMetadataKey#CENTER_NAME} and {@link MetadataKey#TIME_SYSTEM}
207  * to avoid any bugs associated with incorrect guesses.
208  *
209  * <p> Standardized values for {@link MetadataKey#TIME_SYSTEM} are GMST, GPS, MET, MRT, SCLK,
210  * TAI, TCB, TDB, TT, UT1, and UTC. Standardized values for reference frames
211  * are EME2000, GTOD, ICRF, ITRF2000, ITRF-93, ITRF-97, LVLH, RTN, QSW, TOD, TNW, NTW and RSW.
212  * Additionally ITRF followed by a four digit year may be used.
213  *
214  * @author Bryan Cazabonne
215  * @since 10.2
216  */
217 public class AemWriter extends AbstractMessageWriter<AdmHeader, AemSegment, Aem> {
218 
219     /** Version number implemented. **/
220     public static final double CCSDS_AEM_VERS = 2.0;
221 
222     /** Padding width for aligning the '=' sign. */
223     public static final int KVN_PADDING_WIDTH = 20;
224 
225     /** Constant for frame A to frame B attitude. */
226     private static final String A_TO_B = "A2B";
227 
228     /** Constant for frame B to frame A attitude. */
229     private static final String B_TO_A = "B2A";
230 
231     /** Constant for quaternions with scalar component in  position. */
232     private static final String FIRST = "FIRST";
233 
234     /** Constant for quaternions with scalar component in last position. */
235     private static final String LAST = "LAST";
236 
237     /** Constant for angular rates in frame A. */
238     private static final String REF_FRAME_A = "REF_FRAME_A";
239 
240     /** Constant for angular rates in frame B. */
241     private static final String REF_FRAME_B = "REF_FRAME_B";
242 
243     /** Prefix for Euler rotations. */
244     private static final String ROTATION = "rotation";
245 
246     /** Attribute for Euler angles. */
247     private static final String ANGLE_ATTRIBUTE = "angle";
248 
249     /** Suffix for Euler angles. */
250     private static final String ANGLE_SUFFIX = "_ANGLE";
251 
252     /**Attribute for Euler rates. */
253     private static final String RATE_ATTRIBUTE = "rate";
254 
255     /** Suffix for Euler rates. */
256     private static final String RATE_SUFFIX = "_RATE";
257 
258     /**
259      * Constructor used to create a new AEM writer configured with the necessary parameters
260      * to successfully fill in all required fields that aren't part of a standard object.
261      * @param conventions IERS Conventions
262      * @param dataContext used to retrieve frames, time scales, etc.
263      * @param missionReferenceDate reference date for Mission Elapsed Time or Mission Relative Time time systems
264      * @since 11.0
265      */
266     public AemWriter(final IERSConventions conventions, final DataContext dataContext,
267                      final AbsoluteDate missionReferenceDate) {
268         super(Aem.ROOT, Aem.FORMAT_VERSION_KEY, CCSDS_AEM_VERS,
269               new ContextBinding(
270                   () -> conventions,
271                   () -> true, () -> dataContext, () -> ParsedUnitsBehavior.STRICT_COMPLIANCE,
272                   () -> missionReferenceDate, () -> TimeSystem.UTC,
273                   () -> 0.0, () -> 1.0));
274     }
275 
276     /** {@inheritDoc} */
277     @Override
278     protected void writeSegmentContent(final Generator generator, final double formatVersion,
279                                        final AemSegment segment)
280         throws IOException {
281 
282         final AemMetadata metadata = segment.getMetadata();
283         writeMetadata(generator, formatVersion, metadata);
284 
285         // Loop on attitude data
286         startAttitudeBlock(generator);
287         generator.writeComments(((AemSegment) segment).getData().getComments());
288         for (final TimeStampedAngularCoordinates coordinates : segment.getAngularCoordinates()) {
289             writeAttitudeEphemerisLine(generator, formatVersion, metadata, coordinates);
290         }
291         endAttitudeBlock(generator);
292 
293     }
294 
295     /** Write an ephemeris segment metadata.
296      * @param generator generator to use for producing output
297      * @param formatVersion format version
298      * @param metadata metadata to write
299      * @throws IOException if the output stream throws one while writing.
300      */
301     void writeMetadata(final Generator generator, final double formatVersion, final AemMetadata metadata)
302         throws IOException {
303 
304         final ContextBinding oldContext = getContext();
305         setContext(new ContextBinding(oldContext::getConventions,
306                                       oldContext::isSimpleEOP,
307                                       oldContext::getDataContext,
308                                       oldContext::getParsedUnitsBehavior,
309                                       oldContext::getReferenceDate,
310                                       metadata::getTimeSystem,
311                                       oldContext::getClockCount,
312                                       oldContext::getClockRate));
313 
314         // Start metadata
315         generator.enterSection(generator.getFormat() == FileFormat.KVN ?
316                                KvnStructureKey.META.name() :
317                                XmlStructureKey.metadata.name());
318 
319         generator.writeComments(metadata.getComments());
320 
321         // objects
322         generator.writeEntry(AdmMetadataKey.OBJECT_NAME.name(),     metadata.getObjectName(), null, true);
323         generator.writeEntry(AdmCommonMetadataKey.OBJECT_ID.name(), metadata.getObjectID(),   null, true);
324         if (metadata.getCenter() != null) {
325             generator.writeEntry(AdmMetadataKey.CENTER_NAME.name(), metadata.getCenter().getName(), null, false);
326         }
327 
328         // frames
329         generator.writeEntry(AemMetadataKey.REF_FRAME_A.name(),  metadata.getEndpoints().getFrameA().getName(),     null, true);
330         generator.writeEntry(AemMetadataKey.REF_FRAME_B.name(),  metadata.getEndpoints().getFrameB().getName(),     null, true);
331         if (formatVersion < 2.0) {
332             generator.writeEntry(AemMetadataKey.ATTITUDE_DIR.name(), metadata.getEndpoints().isA2b() ? A_TO_B : B_TO_A, null, true);
333         }
334 
335         // time
336         generator.writeEntry(MetadataKey.TIME_SYSTEM.name(), metadata.getTimeSystem(), true);
337         generator.writeEntry(AemMetadataKey.START_TIME.name(), getTimeConverter(), metadata.getStartTime(), false, true);
338         if (metadata.getUseableStartTime() != null) {
339             generator.writeEntry(AemMetadataKey.USEABLE_START_TIME.name(), getTimeConverter(), metadata.getUseableStartTime(), false, false);
340         }
341         if (metadata.getUseableStopTime() != null) {
342             generator.writeEntry(AemMetadataKey.USEABLE_STOP_TIME.name(), getTimeConverter(), metadata.getUseableStopTime(), false, false);
343         }
344         generator.writeEntry(AemMetadataKey.STOP_TIME.name(), getTimeConverter(), metadata.getStopTime(), false, true);
345 
346         // types
347         final AttitudeType attitudeType = metadata.getAttitudeType();
348         generator.writeEntry(AemMetadataKey.ATTITUDE_TYPE.name(), attitudeType.getName(formatVersion), null, true);
349         if (formatVersion < 2.0) {
350             if (attitudeType == AttitudeType.QUATERNION ||
351                 attitudeType == AttitudeType.QUATERNION_DERIVATIVE ||
352                 attitudeType == AttitudeType.QUATERNION_ANGVEL) {
353                 generator.writeEntry(AemMetadataKey.QUATERNION_TYPE.name(), metadata.isFirst() ? FIRST : LAST, null, false);
354             }
355         }
356 
357         if (attitudeType == AttitudeType.QUATERNION_EULER_RATES ||
358             attitudeType == AttitudeType.EULER_ANGLE            ||
359             attitudeType == AttitudeType.EULER_ANGLE_DERIVATIVE ||
360             attitudeType == AttitudeType.EULER_ANGLE_ANGVEL) {
361             if (formatVersion < 2.0) {
362                 generator.writeEntry(AemMetadataKey.EULER_ROT_SEQ.name(),
363                                      metadata.getEulerRotSeq().name().replace('X', '1').replace('Y', '2').replace('Z', '3'),
364                                      null, false);
365             } else {
366                 generator.writeEntry(AemMetadataKey.EULER_ROT_SEQ.name(),
367                                      metadata.getEulerRotSeq().name(),
368                                      null, false);
369             }
370         }
371 
372         if (formatVersion < 2 && attitudeType == AttitudeType.EULER_ANGLE_DERIVATIVE) {
373             generator.writeEntry(AemMetadataKey.RATE_FRAME.name(),
374                                  metadata.rateFrameIsA() ? REF_FRAME_A : REF_FRAME_B,
375                                  null, false);
376         }
377 
378         if (attitudeType == AttitudeType.QUATERNION_ANGVEL ||
379             attitudeType == AttitudeType.EULER_ANGLE_ANGVEL) {
380             generator.writeEntry(AemMetadataKey.ANGVEL_FRAME.name(),
381                                  metadata.getFrameAngvelFrame().getName(),
382                                  null, true);
383         }
384 
385         // interpolation
386         if (metadata.getInterpolationMethod() != null) {
387             generator.writeEntry(AemMetadataKey.INTERPOLATION_METHOD.name(),
388                                  metadata.getInterpolationMethod(),
389                                  null, true);
390             generator.writeEntry(AemMetadataKey.INTERPOLATION_DEGREE.name(),
391                                  Integer.toString(metadata.getInterpolationDegree()),
392                                  null, true);
393         }
394 
395         // Stop metadata
396         generator.exitSection();
397 
398     }
399 
400     /**
401      * Write a single attitude ephemeris line according to section 4.2.4 and Table 4-4.
402      * @param generator generator to use for producing output
403      * @param formatVersion format version to use
404      * @param metadata metadata to use for interpreting data
405      * @param attitude the attitude information for a given date
406      * @throws IOException if the output stream throws one while writing.
407      */
408     void writeAttitudeEphemerisLine(final Generator generator, final double formatVersion,
409                                     final AemMetadata metadata,
410                                     final TimeStampedAngularCoordinates attitude)
411         throws IOException {
412 
413         // Attitude data in CCSDS units
414         final String[] data = metadata.getAttitudeType().createDataFields(metadata.isFirst(),
415                                                                           metadata.getEndpoints().isExternal2SpacecraftBody(),
416                                                                           metadata.getEulerRotSeq(),
417                                                                           metadata.isSpacecraftBodyRate(),
418                                                                           attitude);
419 
420         if (generator.getFormat() == FileFormat.KVN) {
421 
422             // epoch
423             generator.writeRawData(generator.dateToString(getTimeConverter(), attitude.getDate()));
424 
425             // data
426             for (int index = 0; index < data.length; index++) {
427                 generator.writeRawData(' ');
428                 generator.writeRawData(data[index]);
429             }
430 
431             // end the line
432             generator.newLine();
433 
434         } else {
435             final XmlGenerator xmlGenerator = (XmlGenerator) generator;
436             xmlGenerator.enterSection(XmlSubStructureKey.attitudeState.name());
437             switch (metadata.getAttitudeType()) {
438                 case QUATERNION :
439                     writeQuaternion(xmlGenerator, formatVersion, metadata.isFirst(), attitude.getDate(), data);
440                     break;
441                 case QUATERNION_DERIVATIVE :
442                     writeQuaternionDerivative(xmlGenerator, formatVersion, metadata.isFirst(), attitude.getDate(), data);
443                     break;
444                 case QUATERNION_EULER_RATES :
445                     writeQuaternionEulerRates(xmlGenerator, metadata.isFirst(), metadata.getEulerRotSeq(), attitude.getDate(), data);
446                     break;
447                 case QUATERNION_ANGVEL :
448                     writeQuaternionAngularVelocity(xmlGenerator, attitude.getDate(), data);
449                     break;
450                 case EULER_ANGLE :
451                     writeEulerAngle(xmlGenerator, formatVersion, metadata.getEulerRotSeq(), attitude.getDate(), data);
452                     break;
453                 case EULER_ANGLE_DERIVATIVE :
454                     writeEulerAngleDerivative(xmlGenerator, formatVersion, metadata.getEulerRotSeq(), attitude.getDate(), data);
455                     break;
456                 case EULER_ANGLE_ANGVEL :
457                     writeEulerAngleAngularVelocity(xmlGenerator, formatVersion, metadata.getEulerRotSeq(), attitude.getDate(), data);
458                     break;
459                 case SPIN :
460                     writeSpin(xmlGenerator, attitude.getDate(), data);
461                     break;
462                 case SPIN_NUTATION :
463                     writeSpinNutation(xmlGenerator, attitude.getDate(), data);
464                     break;
465                 case SPIN_NUTATION_MOMENTUM :
466                     writeSpinNutationMomentum(xmlGenerator, attitude.getDate(), data);
467                     break;
468                 default :
469                     // this should never happen
470                     throw new OrekitInternalError(null);
471             }
472             generator.exitSection();
473         }
474 
475     }
476 
477     /** Write a quaternion entry in XML.
478      * @param xmlGenerator generator to use for producing output
479      * @param formatVersion format version to use
480      * @param first flag for scalar component to appear first (only relevant in ADM V1)
481      * @param epoch of the entry
482      * @param data entry data
483      * @throws IOException if the output stream throws one while writing.
484      */
485     void writeQuaternion(final XmlGenerator xmlGenerator, final double formatVersion,
486                          final boolean first, final AbsoluteDate epoch, final String[] data)
487         throws IOException {
488 
489         xmlGenerator.enterSection(formatVersion < 2.0 ?
490                                   AttitudeEntryKey.quaternionState.name() :
491                                   AttitudeEntryKey.quaternionEphemeris.name());
492 
493         // data part
494         xmlGenerator.writeEntry(AttitudeEntryKey.EPOCH.name(), getTimeConverter(), epoch, false, true);
495 
496         // wrapping element
497         xmlGenerator.enterSection(AttitudeEntryKey.quaternion.name());
498 
499         // quaternion part
500         int i = 0;
501         if (formatVersion < 2.0 && first) {
502             xmlGenerator.writeEntry(AttitudeEntryKey.QC.name(), data[i++], Unit.ONE, false);
503         }
504         xmlGenerator.writeEntry(AttitudeEntryKey.Q1.name(), data[i++], Unit.ONE, false);
505         xmlGenerator.writeEntry(AttitudeEntryKey.Q2.name(), data[i++], Unit.ONE, false);
506         xmlGenerator.writeEntry(AttitudeEntryKey.Q3.name(), data[i++], Unit.ONE, false);
507         if (!(formatVersion < 2.0 && first)) {
508             xmlGenerator.writeEntry(AttitudeEntryKey.QC.name(), data[i++], Unit.ONE, false);
509         }
510 
511         xmlGenerator.exitSection();
512         xmlGenerator.exitSection();
513 
514     }
515 
516     /** Write a quaternion/derivative entry in XML.
517      * @param xmlGenerator generator to use for producing output
518      * @param formatVersion format version to use
519      * @param first flag for scalar component to appear first (only relevant in ADM V1)
520      * @param epoch of the entry
521      * @param data entry data
522      * @throws IOException if the output stream throws one while writing.
523      */
524     void writeQuaternionDerivative(final XmlGenerator xmlGenerator, final double formatVersion,
525                                    final boolean first, final AbsoluteDate epoch, final String[] data)
526         throws IOException {
527 
528         // wrapping element
529         xmlGenerator.enterSection(AttitudeEntryKey.quaternionDerivative.name());
530 
531         // data part
532         xmlGenerator.writeEntry(AttitudeEntryKey.EPOCH.name(), getTimeConverter(), epoch, false, true);
533         int i = 0;
534 
535         // quaternion part
536         xmlGenerator.enterSection(AttitudeEntryKey.quaternion.name());
537         if (formatVersion < 2.0 && first) {
538             xmlGenerator.writeEntry(AttitudeEntryKey.QC.name(), data[i++], Unit.ONE, true);
539         }
540         xmlGenerator.writeEntry(AttitudeEntryKey.Q1.name(), data[i++], Unit.ONE, true);
541         xmlGenerator.writeEntry(AttitudeEntryKey.Q2.name(), data[i++], Unit.ONE, true);
542         xmlGenerator.writeEntry(AttitudeEntryKey.Q3.name(), data[i++], Unit.ONE, true);
543         if (!(formatVersion < 2.0 && first)) {
544             xmlGenerator.writeEntry(AttitudeEntryKey.QC.name(), data[i++], Unit.ONE, true);
545         }
546         xmlGenerator.exitSection();
547 
548         // derivative part
549         xmlGenerator.enterSection(formatVersion < 2.0 ?
550                                   AttitudeEntryKey.quaternionRate.name() :
551                                   AttitudeEntryKey.quaternionDot.name());
552         if (formatVersion < 2.0 && first) {
553             xmlGenerator.writeEntry(AttitudeEntryKey.QC_DOT.name(), data[i++], Units.ONE_PER_S, true);
554         }
555         xmlGenerator.writeEntry(AttitudeEntryKey.Q1_DOT.name(), data[i++], Units.ONE_PER_S, true);
556         xmlGenerator.writeEntry(AttitudeEntryKey.Q2_DOT.name(), data[i++], Units.ONE_PER_S, true);
557         xmlGenerator.writeEntry(AttitudeEntryKey.Q3_DOT.name(), data[i++], Units.ONE_PER_S, true);
558         if (!(formatVersion < 2.0 && first)) {
559             xmlGenerator.writeEntry(AttitudeEntryKey.QC_DOT.name(), data[i++], Units.ONE_PER_S, true);
560         }
561         xmlGenerator.exitSection();
562 
563         xmlGenerator.exitSection();
564 
565     }
566 
567     /** Write a quaternion/Euler rates entry in XML.
568      * @param xmlGenerator generator to use for producing output
569      * @param first flag for scalar component to appear first (only relevant in ADM V1)
570      * @param order Euler rotation order
571      * @param epoch of the entry
572      * @param data entry data
573      * @throws IOException if the output stream throws one while writing.
574      */
575     void writeQuaternionEulerRates(final XmlGenerator xmlGenerator, final boolean first, final RotationOrder order,
576                                    final AbsoluteDate epoch, final String[] data)
577         throws IOException {
578 
579         // wrapping element
580         xmlGenerator.enterSection(AttitudeEntryKey.quaternionEulerRate.name());
581 
582         // data part
583         xmlGenerator.writeEntry(AttitudeEntryKey.EPOCH.name(), getTimeConverter(), epoch, false, true);
584         int i = 0;
585 
586         // quaternion part
587         xmlGenerator.enterSection(AttitudeEntryKey.quaternion.name());
588         if (first) {
589             xmlGenerator.writeEntry(AttitudeEntryKey.QC.name(), data[i++], Unit.ONE, true);
590         }
591         xmlGenerator.writeEntry(AttitudeEntryKey.Q1.name(), data[i++], Unit.ONE, true);
592         xmlGenerator.writeEntry(AttitudeEntryKey.Q2.name(), data[i++], Unit.ONE, true);
593         xmlGenerator.writeEntry(AttitudeEntryKey.Q3.name(), data[i++], Unit.ONE, true);
594         if (!first) {
595             xmlGenerator.writeEntry(AttitudeEntryKey.QC.name(), data[i++], Unit.ONE, true);
596         }
597         xmlGenerator.exitSection();
598 
599         // derivative part
600         xmlGenerator.enterSection(AttitudeEntryKey.rotationRates.name());
601         writeLabeledEulerRate(xmlGenerator, 0, order.name(), data[i++]);
602         writeLabeledEulerRate(xmlGenerator, 1, order.name(), data[i++]);
603         writeLabeledEulerRate(xmlGenerator, 2, order.name(), data[i++]);
604         xmlGenerator.exitSection();
605 
606         xmlGenerator.exitSection();
607 
608     }
609 
610     /** Write a quaternion/rate entry in XML.
611      * @param xmlGenerator generator to use for producing output
612      * @param epoch of the entry
613      * @param data entry data
614      * @throws IOException if the output stream throws one while writing.
615      */
616     void writeQuaternionAngularVelocity(final XmlGenerator xmlGenerator,
617                                         final AbsoluteDate epoch, final String[] data)
618         throws IOException {
619 
620         // wrapping element
621         xmlGenerator.enterSection(AttitudeEntryKey.quaternionAngVel.name());
622 
623         // data part
624         xmlGenerator.writeEntry(AttitudeEntryKey.EPOCH.name(), getTimeConverter(), epoch, false, true);
625         int i = 0;
626 
627         // quaternion part
628         xmlGenerator.enterSection(AttitudeEntryKey.quaternion.name());
629         xmlGenerator.writeEntry(AttitudeEntryKey.Q1.name(), data[i++], Unit.ONE, true);
630         xmlGenerator.writeEntry(AttitudeEntryKey.Q2.name(), data[i++], Unit.ONE, true);
631         xmlGenerator.writeEntry(AttitudeEntryKey.Q3.name(), data[i++], Unit.ONE, true);
632         xmlGenerator.writeEntry(AttitudeEntryKey.QC.name(), data[i++], Unit.ONE, true);
633         xmlGenerator.exitSection();
634 
635         // angular velocity part
636         xmlGenerator.enterSection(AttitudeEntryKey.angVel.name());
637         xmlGenerator.writeEntry(AttitudeEntryKey.ANGVEL_X.name(), data[i++], Units.DEG_PER_S, true);
638         xmlGenerator.writeEntry(AttitudeEntryKey.ANGVEL_Y.name(), data[i++], Units.DEG_PER_S, true);
639         xmlGenerator.writeEntry(AttitudeEntryKey.ANGVEL_Z.name(), data[i++], Units.DEG_PER_S, true);
640         xmlGenerator.exitSection();
641 
642         xmlGenerator.exitSection();
643 
644     }
645 
646     /** Write a Euler angles entry in XML.
647      * @param xmlGenerator generator to use for producing output
648      * @param formatVersion format version to use
649      * @param order Euler rotation order
650      * @param epoch of the entry
651      * @param data entry data
652      * @throws IOException if the output stream throws one while writing.
653      */
654     void writeEulerAngle(final XmlGenerator xmlGenerator, final double formatVersion,
655                          final RotationOrder order, final AbsoluteDate epoch, final String[] data)
656         throws IOException {
657 
658         // wrapping element
659         xmlGenerator.enterSection(AttitudeEntryKey.eulerAngle.name());
660 
661         // data part
662         xmlGenerator.writeEntry(AttitudeEntryKey.EPOCH.name(), getTimeConverter(), epoch, false, true);
663         int i = 0;
664 
665         // angle part
666         if (formatVersion < 2.0) {
667             xmlGenerator.enterSection(AttitudeEntryKey.rotationAngles.name());
668             writeLabeledEulerAngle(xmlGenerator, 0, order.name(), data[i++]);
669             writeLabeledEulerAngle(xmlGenerator, 1, order.name(), data[i++]);
670             writeLabeledEulerAngle(xmlGenerator, 2, order.name(), data[i++]);
671             xmlGenerator.exitSection();
672         } else {
673             xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_1.name(), data[i++], Unit.DEGREE, true);
674             xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_2.name(), data[i++], Unit.DEGREE, true);
675             xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_3.name(), data[i++], Unit.DEGREE, true);
676         }
677 
678         xmlGenerator.exitSection();
679 
680     }
681 
682     /** Write a Euler angles entry in XML.
683      * @param xmlGenerator generator to use for producing output
684      * @param formatVersion format version to use
685      * @param order Euler rotation order
686      * @param epoch of the entry
687      * @param data entry data
688      * @throws IOException if the output stream throws one while writing.
689      */
690     void writeEulerAngleDerivative(final XmlGenerator xmlGenerator, final double formatVersion,
691                                    final RotationOrder order, final AbsoluteDate epoch, final String[] data)
692         throws IOException {
693 
694         // wrapping element
695         xmlGenerator.enterSection(formatVersion < 2.0 ?
696                                   AttitudeEntryKey.eulerAngleRate.name() :
697                                   AttitudeEntryKey.eulerAngleDerivative.name());
698 
699         // data part
700         xmlGenerator.writeEntry(AttitudeEntryKey.EPOCH.name(), getTimeConverter(), epoch, false, true);
701         int i = 0;
702 
703         // angle part
704         if (formatVersion < 2.0) {
705             xmlGenerator.enterSection(AttitudeEntryKey.rotationAngles.name());
706             writeLabeledEulerAngle(xmlGenerator, 0, order.name(), data[i++]);
707             writeLabeledEulerAngle(xmlGenerator, 1, order.name(), data[i++]);
708             writeLabeledEulerAngle(xmlGenerator, 2, order.name(), data[i++]);
709             xmlGenerator.exitSection();
710             xmlGenerator.enterSection(AttitudeEntryKey.rotationRates.name());
711             writeLabeledEulerRate(xmlGenerator, 0, order.name(), data[i++]);
712             writeLabeledEulerRate(xmlGenerator, 1, order.name(), data[i++]);
713             writeLabeledEulerRate(xmlGenerator, 2, order.name(), data[i++]);
714             xmlGenerator.exitSection();
715         } else {
716             xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_1.name(),     data[i++], Unit.DEGREE,     true);
717             xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_2.name(),     data[i++], Unit.DEGREE,     true);
718             xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_3.name(),     data[i++], Unit.DEGREE,     true);
719             xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_1_DOT.name(), data[i++], Units.DEG_PER_S, true);
720             xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_2_DOT.name(), data[i++], Units.DEG_PER_S, true);
721             xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_3_DOT.name(), data[i++], Units.DEG_PER_S, true);
722         }
723 
724         xmlGenerator.exitSection();
725 
726     }
727 
728     /** Write a Euler angles/angular velocity entry in XML.
729      * @param xmlGenerator generator to use for producing output
730      * @param formatVersion format version to use
731      * @param order Euler rotation order
732      * @param epoch of the entry
733      * @param data entry data
734      * @throws IOException if the output stream throws one while writing.
735      */
736     void writeEulerAngleAngularVelocity(final XmlGenerator xmlGenerator, final double formatVersion, final RotationOrder order,
737                                         final AbsoluteDate epoch, final String[] data)
738         throws IOException {
739 
740         // wrapping element
741         xmlGenerator.enterSection(AttitudeEntryKey.eulerAngleAngVel.name());
742 
743         // data part
744         xmlGenerator.writeEntry(AttitudeEntryKey.EPOCH.name(), getTimeConverter(), epoch, false, true);
745         int i = 0;
746 
747         // angle part
748         xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_1.name(), data[i++], Unit.DEGREE, true);
749         xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_2.name(), data[i++], Unit.DEGREE, true);
750         xmlGenerator.writeEntry(AttitudeEntryKey.ANGLE_3.name(), data[i++], Unit.DEGREE, true);
751 
752         // angular velocity part
753         xmlGenerator.writeEntry(AttitudeEntryKey.ANGVEL_X.name(), data[i++], Units.DEG_PER_S, true);
754         xmlGenerator.writeEntry(AttitudeEntryKey.ANGVEL_Y.name(), data[i++], Units.DEG_PER_S, true);
755         xmlGenerator.writeEntry(AttitudeEntryKey.ANGVEL_Z.name(), data[i++], Units.DEG_PER_S, true);
756 
757         xmlGenerator.exitSection();
758 
759     }
760 
761     /** Write a spin entry in XML.
762      * @param xmlGenerator generator to use for producing output
763      * @param epoch of the entry
764      * @param data entry data
765      * @throws IOException if the output stream throws one while writing.
766      */
767     void writeSpin(final XmlGenerator xmlGenerator, final AbsoluteDate epoch, final String[] data)
768         throws IOException {
769 
770         // wrapping element
771         xmlGenerator.enterSection(AttitudeEntryKey.spin.name());
772 
773         // data part
774         xmlGenerator.writeEntry(AttitudeEntryKey.EPOCH.name(), getTimeConverter(), epoch, false, true);
775         int i = 0;
776         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_ALPHA.name(),     data[i++], Unit.DEGREE,     true);
777         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_DELTA.name(),     data[i++], Unit.DEGREE,     true);
778         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_ANGLE.name(),     data[i++], Unit.DEGREE,     true);
779         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_ANGLE_VEL.name(), data[i++], Units.DEG_PER_S, true);
780 
781         xmlGenerator.exitSection();
782 
783     }
784 
785     /** Write a spin/nutation entry in XML.
786      * @param xmlGenerator generator to use for producing output
787      * @param epoch of the entry
788      * @param data entry data
789      * @throws IOException if the output stream throws one while writing.
790      */
791     void writeSpinNutation(final XmlGenerator xmlGenerator, final AbsoluteDate epoch, final String[] data)
792         throws IOException {
793 
794         // wrapping element
795         xmlGenerator.enterSection(AttitudeEntryKey.spinNutation.name());
796 
797         // data part
798         xmlGenerator.writeEntry(AttitudeEntryKey.EPOCH.name(), getTimeConverter(), epoch, false, true);
799         int i = 0;
800         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_ALPHA.name(),     data[i++], Unit.DEGREE,     true);
801         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_DELTA.name(),     data[i++], Unit.DEGREE,     true);
802         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_ANGLE.name(),     data[i++], Unit.DEGREE,     true);
803         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_ANGLE_VEL.name(), data[i++], Units.DEG_PER_S, true);
804         xmlGenerator.writeEntry(AttitudeEntryKey.NUTATION.name(),       data[i++], Unit.DEGREE,     true);
805         xmlGenerator.writeEntry(AttitudeEntryKey.NUTATION_PER.name(),   data[i++], Unit.SECOND,     true);
806         xmlGenerator.writeEntry(AttitudeEntryKey.NUTATION_PHASE.name(), data[i++], Unit.DEGREE,     true);
807 
808         xmlGenerator.exitSection();
809 
810     }
811 
812     /** Write a spin/nutation/momentum entry in XML.
813      * @param xmlGenerator generator to use for producing output
814      * @param epoch of the entry
815      * @param data entry data
816      * @throws IOException if the output stream throws one while writing.
817      */
818     void writeSpinNutationMomentum(final XmlGenerator xmlGenerator, final AbsoluteDate epoch, final String[] data)
819         throws IOException {
820 
821         // wrapping element
822         xmlGenerator.enterSection(AttitudeEntryKey.spinNutationMom.name());
823 
824         // data part
825         xmlGenerator.writeEntry(AttitudeEntryKey.EPOCH.name(), getTimeConverter(), epoch, false, true);
826         int i = 0;
827         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_ALPHA.name(),     data[i++], Unit.DEGREE,     true);
828         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_DELTA.name(),     data[i++], Unit.DEGREE,     true);
829         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_ANGLE.name(),     data[i++], Unit.DEGREE,     true);
830         xmlGenerator.writeEntry(AttitudeEntryKey.SPIN_ANGLE_VEL.name(), data[i++], Units.DEG_PER_S, true);
831         xmlGenerator.writeEntry(AttitudeEntryKey.MOMENTUM_ALPHA.name(), data[i++], Unit.DEGREE,     true);
832         xmlGenerator.writeEntry(AttitudeEntryKey.MOMENTUM_DELTA.name(), data[i++], Unit.DEGREE,     true);
833         xmlGenerator.writeEntry(AttitudeEntryKey.NUTATION_VEL.name(),   data[i++], Units.DEG_PER_S, true);
834 
835         xmlGenerator.exitSection();
836 
837     }
838 
839     /** Write an angle from an Euler sequence.
840      * @param xmlGenerator generator to use
841      * @param index angle index
842      * @param seq Euler sequence
843      * @param angle angle value
844      * @throws IOException if the output stream throws one while writing.
845      */
846     private void writeLabeledEulerAngle(final XmlGenerator xmlGenerator, final int index,
847                                         final String seq, final String angle)
848         throws IOException {
849         if (xmlGenerator.writeUnits(Unit.DEGREE)) {
850             xmlGenerator.writeTwoAttributesElement(ROTATION + (index + 1), angle,
851                                                    ANGLE_ATTRIBUTE, seq.charAt(index) + ANGLE_SUFFIX,
852                                                    XmlGenerator.UNITS,
853                                                    xmlGenerator.siToCcsdsName(Unit.DEGREE.getName()));
854         } else {
855             xmlGenerator.writeOneAttributeElement(ROTATION + (index + 1), angle,
856                                                   ANGLE_ATTRIBUTE, seq.charAt(index) + ANGLE_SUFFIX);
857         }
858     }
859 
860     /** Write a rate from an Euler sequence.
861      * @param xmlGenerator generator to use
862      * @param index angle index
863      * @param seq Euler sequence
864      * @param rate rate value
865      * @throws IOException if the output stream throws one while writing.
866      */
867     private void writeLabeledEulerRate(final XmlGenerator xmlGenerator, final int index, final String seq, final String rate)
868         throws IOException {
869         if (xmlGenerator.writeUnits(Units.DEG_PER_S)) {
870             xmlGenerator.writeTwoAttributesElement(ROTATION + (index + 1), rate,
871                                                    RATE_ATTRIBUTE, seq.charAt(index) + RATE_SUFFIX,
872                                                    XmlGenerator.UNITS,
873                                                    xmlGenerator.siToCcsdsName(Units.DEG_PER_S.getName()));
874         } else {
875             xmlGenerator.writeOneAttributeElement(ROTATION + (index + 1), rate,
876                                                   RATE_ATTRIBUTE, seq.charAt(index) + RATE_SUFFIX);
877         }
878     }
879 
880     /** Start of an attitude block.
881      * @param generator generator to use for producing output
882      * @throws IOException if the output stream throws one while writing.
883      */
884     void startAttitudeBlock(final Generator generator) throws IOException {
885         generator.enterSection(generator.getFormat() == FileFormat.KVN ?
886                                KvnStructureKey.DATA.name() :
887                                XmlStructureKey.data.name());
888     }
889 
890     /** End of an attitude block.
891      * @param generator generator to use for producing output
892      * @throws IOException if the output stream throws one while writing.
893      */
894     void endAttitudeBlock(final Generator generator) throws IOException {
895         generator.exitSection();
896     }
897 
898 }