rsspice 0.1.0

Pure Rust port of the SPICE Toolkit for space geometry
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//
// GENERATED FILE
//

use super::*;
use crate::SpiceContext;
use f2rust_std::*;

const MAXTRM: i32 = 25;
const SIDLEN: i32 = 40;
const FPRINT: i32 = 32;
const LPRINT: i32 = 126;
const MINDSZ: i32 = 71;
const DSCSIZ: i32 = 5;
const DTYPE: i32 = 21;
const DIRSIZ: i32 = 100;

/// Write SPK segment, type 21
///
/// Write a type 21 segment to an SPK file.
///
/// # Required Reading
///
/// * [NAIF_IDS](crate::required_reading::naif_ids)
/// * [SPK](crate::required_reading::spk)
/// * [TIME](crate::required_reading::time)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  HANDLE     I   Handle of an SPK file open for writing.
///  BODY       I   NAIF code for an ephemeris object.
///  CENTER     I   NAIF code for center of motion of BODY.
///  FRAME      I   Reference frame name.
///  FIRST      I   Start time of interval covered by segment.
///  LAST       I   End time of interval covered by segment.
///  SEGID      I   Segment identifier.
///  N          I   Number of difference lines in segment.
///  DLSIZE     I   Difference line size.
///  DLINES     I   Array of difference lines.
///  EPOCHS     I   Coverage end times of difference lines.
///  MAXTRM     P   Maximum number of terms per difference table
///                 component.
/// ```
///
/// # Detailed Input
///
/// ```text
///  HANDLE   is the file handle of an SPK file that has been
///           opened for writing.
///
///  BODY     is the NAIF integer code for an ephemeris object
///           whose state relative to another body is described
///           by the segment to be created.
///
///  CENTER   is the NAIF integer code for the center of motion
///           of the object identified by BODY.
///
///  FRAME    is the NAIF name for a reference frame relative to
///           which the state information for BODY is specified.
///
///  FIRST,
///  LAST     are, respectively, the start and stop times of
///           the time interval over which the segment defines
///           the state of BODY.
///
///  SEGID    is the segment identifier. An SPK segment
///           identifier may contain up to 40 characters.
///
///  N        is the number of difference lines in the input
///           difference line array.
///
///  DLSIZE   is the size of each difference line data structure
///           in the difference line array input DLINES. Let
///           MAXDIM be the dimension of each component of the
///           difference table within each difference line. Then
///           the size DLSIZE of the difference line is
///
///              ( 4 * MAXDIM ) + 11
///
///  DLINES   contains a time-ordered array of difference lines.
///           The Ith difference line occupies elements (1,I)
///           through (MAXDIM,I) of DLINES, where MAXDIM is
///           as described above in the description of DLSIZE.
///           Each difference line represents the state (x, y,
///           z, dx/dt, dy/dt, dz/dt, in kilometers and
///           kilometers per second) of BODY relative to CENTER,
///           specified relative to FRAME, for an interval of
///           time. The time interval covered by the Ith
///           difference line ends at the Ith element of the
///           array EPOCHS (described below). The interval
///           covered by the first difference line starts at the
///           segment start time.
///
///           The contents of a difference line are as shown
///           below:
///
///              Dimension  Description
///              ---------  ----------------------------------
///              1          Reference epoch of difference line
///              MAXDIM     Stepsize function vector
///              1          Reference position vector,  x
///              1          Reference velocity vector,  x
///              1          Reference position vector,  y
///              1          Reference velocity vector,  y
///              1          Reference position vector,  z
///              1          Reference velocity vector,  z
///              MAXDIM,3   Modified divided difference
///                         arrays (MDAs)
///              1          Maximum integration order plus 1
///              3          Integration order array
///
///           The reference position and velocity are those of
///           BODY relative to CENTER at the reference epoch.
///           (A difference line is essentially a polynomial
///           expansion of acceleration about the reference
///           epoch.)
///
///  EPOCHS   is an array of epochs corresponding to the members
///           of the difference line array. The epochs are
///           specified as seconds past J2000 TDB.
///
///           The first difference line covers the time interval
///           from the segment start time to EPOCHS(1). For
///           I > 1, the Ith difference line covers the half-open
///           time interval from, but not including, EPOCHS(I-1)
///           through EPOCHS(I).
///
///           The elements of EPOCHS must be strictly increasing.
/// ```
///
/// # Detailed Output
///
/// ```text
///  None. See $Particulars for a description of the effect of this
///  routine.
/// ```
///
/// # Parameters
///
/// ```text
///  MAXTRM   is the maximum number of terms allowed in
///           each component of the difference table
///           contained in the input argument RECORD.
///           See the INCLUDE file spk21.inc for the value
///           of MAXTRM.
/// ```
///
/// # Exceptions
///
/// ```text
///  If any of the following exceptions occur, this routine will return
///  without creating a new segment.
///
///  1)  If FRAME is not a recognized name, the error
///      SPICE(INVALIDREFFRAME) is signaled.
///
///  2)  If the last non-blank character of SEGID occurs past index 40,
///      the error SPICE(SEGIDTOOLONG) is signaled.
///
///  3)  If SEGID contains any nonprintable characters, the error
///      SPICE(NONPRINTABLECHARS) is signaled.
///
///  4)  If the number of difference lines N is not at least one,
///      the error SPICE(INVALIDCOUNT) is signaled.
///
///  5)  If FIRST is greater than LAST, the error
///      SPICE(BADDESCRTIMES) is signaled.
///
///  6)  If the elements of the array EPOCHS are not in strictly
///      increasing order, the error SPICE(TIMESOUTOFORDER) is
///      signaled.
///
///  7)  If the last epoch EPOCHS(N) is less than LAST, the error
///      SPICE(COVERAGEGAP) is signaled.
///
///  8)  If DLSIZE is greater than the limit
///
///         ( 4 * MAXTRM ) + 11
///
///      the error SPICE(DIFFLINETOOLARGE) is signaled. If
///      DLSIZE is less than 71, the error SPICE(DIFFLINETOOSMALL)
///      is signaled.
///
///  9)  Let KQMAX1 be the maximum integration order for a given
///      difference line. If any value at index KQMAX1-1 or greater
///      in the step size array of that difference line is zero, the
///      error SPICE(ZEROSTEP) is signaled. The checked portion
///      of the step size vector lies in the index range 2:KQMAX-1
///      of the difference line containing the vector.
/// ```
///
/// # Files
///
/// ```text
///  A new type 21 SPK segment is written to the SPK file attached
///  to HANDLE.
/// ```
///
/// # Particulars
///
/// ```text
///  This routine writes an SPK type 21 data segment to the open SPK
///  file according to the format described in the type 21 section of
///  the SPK Required Reading. The SPK file must have been opened with
///  write access.
/// ```
///
/// # Examples
///
/// ```text
///  Suppose that you have difference lines and are prepared to
///  produce a segment of type 21 in an SPK file.
///
///  The following code fragment could be used to add the new segment
///  to a previously opened SPK file attached to HANDLE. The file must
///  have been opened with write access.
///
///     C
///     C     Create a segment identifier.
///     C
///           SEGID = 'MY_SAMPLE_SPK_TYPE_21_SEGMENT'
///
///     C
///     C     Write the segment.
///     C
///           CALL SPKW21 (  HANDLE,  BODY,    CENTER,  FRAME,
///          .               FIRST,   LAST,    SEGID,   N,
///          .               DLSIZE,  DLINES,  EPOCHS         )
/// ```
///
/// # Restrictions
///
/// ```text
///  1)  The validity of the difference lines is not checked by
///      this routine.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 2.0.1, 03-JUN-2021 (JDR)
///
///         Edited the header to comply with NAIF standard.
///
/// -    SPICELIB Version 2.0.0, 21-AUG-2015 (NJB)
///
///         Relaxed step size error check to allow zero
///         values in elements indexed greater than KQMAX1-2.
///
/// -    SPICELIB Version 1.0.0, 03-FEB-2014 (NJB)
/// ```
pub fn spkw21(
    ctx: &mut SpiceContext,
    handle: i32,
    body: i32,
    center: i32,
    frame: &str,
    first: f64,
    last: f64,
    segid: &str,
    n: i32,
    dlsize: i32,
    dlines: &[f64],
    epochs: &[f64],
) -> crate::Result<()> {
    SPKW21(
        handle,
        body,
        center,
        frame.as_bytes(),
        first,
        last,
        segid.as_bytes(),
        n,
        dlsize,
        dlines,
        epochs,
        ctx.raw_context(),
    )?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SPKW21 ( Write SPK segment, type 21 )
pub fn SPKW21(
    HANDLE: i32,
    BODY: i32,
    CENTER: i32,
    FRAME: &[u8],
    FIRST: f64,
    LAST: f64,
    SEGID: &[u8],
    N: i32,
    DLSIZE: i32,
    DLINES: &[f64],
    EPOCHS: &[f64],
    ctx: &mut Context,
) -> f2rust_std::Result<()> {
    let DLINES = DummyArray2D::new(DLINES, 1..=DLSIZE, 1..);
    let EPOCHS = DummyArray::new(EPOCHS, 1..);
    let mut DESCR = StackArray::<f64, 5>::new(1..=DSCSIZ);
    let mut PRVEPC: f64 = 0.0;
    let mut CHRCOD: i32 = 0;
    let mut KQMAX1: i32 = 0;
    let mut KQMLOC: i32 = 0;
    let mut MAXDIM: i32 = 0;
    let mut MAXDSZ: i32 = 0;
    let mut REFCOD: i32 = 0;

    //
    // SPICELIB functions
    //

    //
    // Local parameters
    //

    //
    // MINDSZ is the minimum MDA size; this is the size
    // of type 1 MDAs.
    //

    //
    // Local variables
    //

    //
    // Local variables
    //

    //
    // Standard SPICE error handling.
    //
    if RETURN(ctx) {
        return Ok(());
    }

    CHKIN(b"SPKW21", ctx)?;

    //
    // Make sure the difference line size is within limits.
    //
    MAXDSZ = ((4 * MAXTRM) + 11);

    if (DLSIZE > MAXDSZ) {
        SETMSG(b"The input difference line size is #, while the maximum supported by this routine is #. It is possible that this problem is due to your SPICE Toolkit being out of date.", ctx);
        ERRINT(b"#", DLSIZE, ctx);
        ERRINT(b"#", MAXDSZ, ctx);
        SIGERR(b"SPICE(DIFFLINETOOLARGE)", ctx)?;
        CHKOUT(b"SPKW21", ctx)?;
        return Ok(());
    }

    if (DLSIZE < MINDSZ) {
        SETMSG(b"The input difference line size is #, while the minimum supported by this routine is #. It is possible that this problem is due to your SPICE Toolkit being out of date.", ctx);
        ERRINT(b"#", DLSIZE, ctx);
        ERRINT(b"#", MINDSZ, ctx);
        SIGERR(b"SPICE(DIFFLINETOOSMALL)", ctx)?;
        CHKOUT(b"SPKW21", ctx)?;
        return Ok(());
    }

    //
    // Get the NAIF integer code for the reference frame.
    //
    NAMFRM(FRAME, &mut REFCOD, ctx)?;

    if (REFCOD == 0) {
        SETMSG(b"The reference frame # is not supported.", ctx);
        ERRCH(b"#", FRAME, ctx);
        SIGERR(b"SPICE(INVALIDREFFRAME)", ctx)?;
        CHKOUT(b"SPKW21", ctx)?;
        return Ok(());
    }

    //
    // Check to see if the segment identifier is too long.
    //
    if (LASTNB(SEGID) > SIDLEN) {
        SETMSG(b"Segment identifier contains more than 40 characters.", ctx);
        SIGERR(b"SPICE(SEGIDTOOLONG)", ctx)?;
        CHKOUT(b"SPKW21", ctx)?;
        return Ok(());
    }

    //
    // Now check that all the characters in the segment identifier
    // can be printed.
    //
    for I in 1..=LASTNB(SEGID) {
        CHRCOD = intrinsics::ICHAR(fstr::substr(SEGID, I..=I));

        if ((CHRCOD < FPRINT) || (CHRCOD > LPRINT)) {
            SETMSG(
                b"The segment identifier contains nonprintable characters",
                ctx,
            );
            SIGERR(b"SPICE(NONPRINTABLECHARS)", ctx)?;
            CHKOUT(b"SPKW21", ctx)?;
            return Ok(());
        }
    }

    //
    // The difference line count must be at least one.
    //
    if (N < 1) {
        SETMSG(
            b"The difference line count was #; the count must be at least one.",
            ctx,
        );
        ERRINT(b"#", N, ctx);
        SIGERR(b"SPICE(INVALIDCOUNT)", ctx)?;
        CHKOUT(b"SPKW21", ctx)?;
        return Ok(());
    }

    //
    // The segment stop time should be greater than or equal to
    // the begin time.
    //
    if (FIRST > LAST) {
        SETMSG(
            b"The segment start time: # is greater than the segment end time: #",
            ctx,
        );
        ERRDP(b"#", FIRST, ctx);
        ERRDP(b"#", LAST, ctx);
        SIGERR(b"SPICE(BADDESCRTIMES)", ctx)?;
        CHKOUT(b"SPKW21", ctx)?;
        return Ok(());
    }

    //
    // Make sure the epochs form a strictly increasing sequence.
    //
    PRVEPC = EPOCHS[1];

    for I in 2..=N {
        if (EPOCHS[I] <= PRVEPC) {
            SETMSG(
                b"EPOCH # having index # is not greater than its predecessor #.",
                ctx,
            );
            ERRDP(b"#", EPOCHS[I], ctx);
            ERRINT(b"#", I, ctx);
            ERRDP(b"#", EPOCHS[(I - 1)], ctx);
            SIGERR(b"SPICE(TIMESOUTOFORDER)", ctx)?;
            CHKOUT(b"SPKW21", ctx)?;
            return Ok(());
        }

        PRVEPC = EPOCHS[I];
    }

    //
    // Make sure there's no gap between the last difference line
    // epoch and the end of the time interval defined by the segment
    // descriptor.
    //
    if (EPOCHS[N] < LAST) {
        SETMSG(
            b"Segment has coverage gap: segment end time # follows last epoch #.",
            ctx,
        );
        ERRDP(b"#", LAST, ctx);
        ERRDP(b"#", EPOCHS[N], ctx);
        SIGERR(b"SPICE(COVERAGEGAP)", ctx)?;
        CHKOUT(b"SPKW21", ctx)?;
        return Ok(());
    }

    //
    // Check the step size vectors in the difference lines.
    //
    MAXDIM = ((DLSIZE - 11) / 4);
    KQMLOC = ((4 * MAXDIM) + 8);

    for I in 1..=N {
        //
        // Check only the first KQMAX1-2 elements of the step size
        // vector. The higher-indexed elements are allowed to be zero.
        //
        KQMAX1 = intrinsics::IDNINT(DLINES[[KQMLOC, I]]);

        for J in 2..=(KQMAX1 - 1) {
            if (DLINES[[J, I]] == 0.0) {
                SETMSG(
                    b"Step size was zero at step size vector index # within difference line #.",
                    ctx,
                );
                ERRINT(b"#", (J - 1), ctx);
                ERRINT(b"#", I, ctx);
                SIGERR(b"SPICE(ZEROSTEP)", ctx)?;
                CHKOUT(b"SPKW21", ctx)?;
                return Ok(());
            }
        }
    }

    //
    // If we made it this far, we're ready to start writing the segment.
    //
    // Create the segment descriptor.
    //
    SPKPDS(
        BODY,
        CENTER,
        FRAME,
        DTYPE,
        FIRST,
        LAST,
        DESCR.as_slice_mut(),
        ctx,
    )?;

    //
    // Begin a new segment.
    //
    DAFBNA(HANDLE, DESCR.as_slice(), SEGID, ctx)?;

    if FAILED(ctx) {
        CHKOUT(b"SPKW21", ctx)?;
        return Ok(());
    }

    //
    // The type 21 segment structure is shown below:
    //
    //    +-----------------------+
    //    | Difference line 1     |
    //    +-----------------------+
    //    | Difference line 2     |
    //    +-----------------------+
    //               ...
    //    +-----------------------+
    //    | Difference line N     |
    //    +-----------------------+
    //    | Epoch 1               |
    //    +-----------------------+
    //    | Epoch 2               |
    //    +-----------------------+
    //               ...
    //    +-----------------------+
    //    | Epoch N               |
    //    +-----------------------+
    //    | Epoch 100             | (First directory)
    //    +-----------------------+
    //               ...
    //    +-----------------------+
    //    | Epoch (N/100)*100     | (Last directory)
    //    +-----------------------+
    //    | Max diff table size   |
    //    +-----------------------+
    //    | Number of diff lines  |
    //    +-----------------------+
    //

    DAFADA(DLINES.as_slice(), (N * DLSIZE), ctx)?;
    DAFADA(EPOCHS.as_slice(), N, ctx)?;

    for I in 1..=(N / DIRSIZ) {
        DAFADA(EPOCHS.subarray((DIRSIZ * I)), 1, ctx)?;
    }

    DAFADA(&[(MAXDIM as f64)], 1, ctx)?;
    DAFADA(&[(N as f64)], 1, ctx)?;

    //
    // As long as nothing went wrong, end the segment.
    //
    if !FAILED(ctx) {
        DAFENA(ctx)?;
    }

    CHKOUT(b"SPKW21", ctx)?;
    Ok(())
}