-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspicedb.py
More file actions
executable file
·3340 lines (2608 loc) · 126 KB
/
spicedb.py
File metadata and controls
executable file
·3340 lines (2608 loc) · 126 KB
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
################################################################################
# spicedb.py
#
# This set of routines handles the selection of SPICE kernels based on various
# criteria related to body, instrument, time frame, etc. It also sorts selected
# kernels into their proper load order.
################################################################################
from __future__ import division
import os
import datetime
import unittest
import numbers
import julian
import interval
import textkernel
import cspyce
import sqlite_db as db
# For testing and debugging
DEBUG = False # If true, no files are furnished.
ABSPATH_LIST = [] # If DEBUG, lists the files that would have been furnished.
IS_OPEN = False
DB_PATH = ''
TRANSLATOR = None # Optional user-specified function to alter the absolute
# paths of SPICE kernels. This can be used to override the
# default kernels to be loaded. See set_translator().
TRANSLATOR_ID = None
################################################################################
# Global variables to track loaded kernels
################################################################################
# Furnished kernel names by type, listed in load order
FURNISHED_NAMES = {
'CK': [],
'FK': [],
'IK': [],
'LSK': [],
'PCK': [],
'SCLK': [],
'SPK': [],
'STARS':[],
'META': [],
'UNK': [],
}
# Furnished kernel file paths and names by type, listed in load order
FURNISHED_ABSPATHS = {
'CK': [],
'FK': [],
'IK': [],
'LSK': [],
'PCK': [],
'SCLK': [],
'SPK': [],
'STARS':[],
'META': [],
'UNK': [],
}
# Furnished file numbers by name.
FURNISHED_FILENOS = {}
# Furnished sets of kernel file info objects, keyed by basename
FURNISHED_INFO = {}
SPICE_PATH = None
################################################################################
# Kernel Information class
################################################################################
TABLE_NAME = "SPICEDB"
COLUMN_NAMES = ["KERNEL_NAME", "KERNEL_VERSION", "KERNEL_TYPE",
"FILESPEC", "START_TIME", "STOP_TIME", "RELEASE_DATE",
"SPICE_ID", "LOAD_PRIORITY", "FILE_NO"]
# Derived constants
COLUMN_STRING = ", ".join(COLUMN_NAMES)
KERNEL_NAME_INDEX = COLUMN_NAMES.index("KERNEL_NAME")
KERNEL_VERSION_INDEX = COLUMN_NAMES.index("KERNEL_VERSION")
KERNEL_TYPE_INDEX = COLUMN_NAMES.index("KERNEL_TYPE")
FILESPEC_INDEX = COLUMN_NAMES.index("FILESPEC")
START_TIME_INDEX = COLUMN_NAMES.index("START_TIME")
STOP_TIME_INDEX = COLUMN_NAMES.index("STOP_TIME")
RELEASE_DATE_INDEX = COLUMN_NAMES.index("RELEASE_DATE")
SPICE_ID_INDEX = COLUMN_NAMES.index("SPICE_ID")
LOAD_PRIORITY_INDEX = COLUMN_NAMES.index("LOAD_PRIORITY")
FILE_NO_INDEX = COLUMN_NAMES.index("FILE_NO")
KERNEL_TYPE_SORT_DICT = {'LSK': 0, 'SCLK': 1, 'FK': 2, 'IK': 3, 'PCK': 4,
'SPK': 5, 'CK': 6, 'STARS': 7, 'META': 8}
KERNEL_TYPE_SORT_ORDER = ['LSK', 'SCLK', 'FK', 'IK', 'PCK', 'SPK', 'CK',
'STARS', 'META']
KERNEL_TYPE_FROM_EXT = {
'.tls': 'LSK',
'.tpc': 'PCK',
'.bpc': 'PCK',
'.bsp': 'SPK',
'.tsc': 'SCLK',
'.tf' : 'FK',
'.ti' : 'IK',
'.bc' : 'CK',
'.bdb': 'STARS',
'.txt': 'META',
}
class KernelInfo(object):
def __init__(self, list):
self.kernel_name = list[KERNEL_NAME_INDEX]
self.kernel_version = list[KERNEL_VERSION_INDEX]
self.kernel_type = list[KERNEL_TYPE_INDEX]
self.filespec = list[FILESPEC_INDEX]
self.start_time = list[START_TIME_INDEX]
self.stop_time = list[STOP_TIME_INDEX]
self.release_date = list[RELEASE_DATE_INDEX]
self.spice_id = list[SPICE_ID_INDEX]
self.load_priority = list[LOAD_PRIORITY_INDEX]
self.basename = os.path.basename(self.filespec)
if self.start_time:
self.start_tai = julian.tai_from_iso(self.start_time)
self.stop_tai = julian.tai_from_iso(self.stop_time)
self.start_tdb = julian.tdb_from_tai(self.start_tai)
self.stop_tdb = julian.tdb_from_tai(self.stop_tai)
else:
self.start_tai = -1.e99
self.stop_tai = 1.e99
self.start_tdb = -1.e99
self.stop_tdb = 1.e99
if len(list) > FILE_NO_INDEX:
self.file_no = list[FILE_NO_INDEX]
else:
self.file_no = None
def compare(self, other):
"""Identify which of two kernels has a higher load priority.
The compare() operator compares two KernelInfo objects and returns
-1 if the former should be earlier in load order, 0 if they are equal,
or +1 if the former should be later in loader order.
"""
# Compare types
self_type = KERNEL_TYPE_SORT_DICT[self.kernel_type]
other_type = KERNEL_TYPE_SORT_DICT[other.kernel_type]
if self_type < other_type: return -1
if self_type > other_type: return +1
# Other kernel types are organized alphabetically for no particular
# reason except to keep kernels of the same type together
if self.kernel_type < other.kernel_type: return -1
if self.kernel_type > other.kernel_type: return +1
# Compare load priorities
if self.load_priority < other.load_priority: return -1
if self.load_priority > other.load_priority: return +1
# Compare release dates
if self.release_date < other.release_date: return -1
if self.release_date > other.release_date: return +1
# Group names alphabetically
if self.kernel_name < other.kernel_name: return -1
if self.kernel_name > other.kernel_name: return +1
# Earlier versions go first
if self.kernel_version < other.kernel_version: return -1
if self.kernel_version > other.kernel_version: return +1
# Earlier file numbers go first
if self.file_no < other.file_no: return -1
if self.file_no > other.file_no: return +1
# Earlier end dates, later starts go first for better chance of override
if self.stop_time < other.stop_time: return -1
if self.stop_time > other.stop_time: return +1
if self.start_time > other.start_time: return -1
if self.start_time < other.start_time: return +1
# Organize by file name if appropriate
if self.filespec < other.filespec: return -1
if self.filespec > other.filespec: return +1
# Finally, organize by file name and SPICE ID
if self.spice_id < other.spice_id: return -1
if self.spice_id > other.spice_id: return +1
# If all else fails, they're the same
return 0
# Comparison operators, needed for sorting, etc. Note __cmp__ is deprecated.
def __eq__(self, other):
if type(self) != type(other): return False
return self.compare(other) == 0
def __ne__(self, other):
return not self.__eq__(other)
def __le__(self, other):
return self.compare(other) <= 0
def __lt__(self, other):
return self.compare(other) < 0
def __ge__(self, other):
return self.compare(other) >= 0
def __gt__(self, other):
return self.compare(other) > 0
def __str__(self): return self.__repr__()
def __repr__(self):
if self.spice_id is None:
id = ""
else:
id = str(self.spice_id)
result = (self.full_name + "|" +
self.kernel_type + "|" +
self.filespec + "|" +
(self.start_time or '') + "|" +
(self.stop_time or '') + "|" +
(self.release_date or '') + "|" +
id + "|" +
str(self.load_priority))
if self.file_no is not None:
result = result + "[" + str(self.file_no) + "]"
return result
@property
def full_name(self):
# Append version if present
if self.kernel_version:
# Separate name and version by a dash unless version starts with '+'
if self.kernel_version[0] == '+':
return self.kernel_name + self.kernel_version[1:]
else:
return self.kernel_name + '-' + self.kernel_version
# Otherwise it's just the name
else:
return self.kernel_name
@property
def timeless(self):
return (self.start_time is None and self.stop_time is None)
def kernels_from_filespec(filespec, name=None, version=None, release=None,
priority=100):
"""Fill in kernel info as well as possible from a file path."""
# Search in the database first
basename = os.path.basename(filespec)
try:
if db_is_open():
return select_by_filespec(basename, time=None)
else:
open_db()
kernels = select_by_filespec(basename, time=None)
close_db()
return kernels
except ValueError:
pass
if name is None:
(name, ext) = os.path.splitext(basename)
name = name.upper()
else:
ext = os.path.splitext(basename)[1]
ext = ext.lower()
if version is None:
version = 'V1'
full_name = name + '-' + version
if release is None:
today = datetime.datetime.today()
release = '%4d-%02d-%02d' % (today.year, today.month, today.day)
kernels = []
# Get info about a CK
try:
spice_ids = cspyce.ckobj(filespec)
for spice_id in spice_ids:
spice_id = int(spice_id)
if spice_id < -999:
body_id = spice_id // 1000
else:
body_id = spice_id
coverages = cspyce.ckcov(filespec, spice_id,
False, 'SEGMENT', 1., 'TDB')
for (start_tdb, stop_tdb) in coverages:
start_time = julian.iso_from_tai(julian.tai_from_tdb(start_tdb))
stop_time = julian.iso_from_tai(julian.tai_from_tdb(stop_tdb))
kernel = KernelInfo([name, version, 'CK', filespec,
start_time, stop_time, release,
body_id, priority, full_name, 1])
kernels.append(kernel)
return kernels
except RuntimeError:
pass
# Get info about an SPK
try:
spice_ids = cspyce.spkobj(filespec)
for spice_id in spice_ids:
spice_id = int(spice_id)
coverages = cspyce.spkcov(filespec, spice_id)
for (start_tdb, stop_tdb) in coverages:
start_time = julian.iso_from_tai(julian.tai_from_tdb(start_tdb))
stop_time = julian.iso_from_tai(julian.tai_from_tdb(stop_tdb))
kernel = KernelInfo([name, version, 'SPK', filespec,
start_time, stop_time, release,
spice_id, priority, full_name, 1])
kernels.append(kernel)
return kernels
except RuntimeError:
pass
ktype = KERNEL_TYPE_FROM_EXT.get(ext, 'UNK')
return [KernelInfo([name, version, ktype, filespec, None, None, release,
None, priority, full_name, 1])]
################################################################################
# Kernel List Manipulations
################################################################################
def _sort_kernels(kernel_list):
"""Sort a list of KernelInfo objects immediately prior to loading.
Input:
kernel_list a list of KernelInfo objects.
Return: a new list in which duplicates are removed and the rest are
sorted into their proper load order.
"""
# Sort kernels into load order
kernel_list.sort()
# Delete kernels that are no longer needed
namekeys = [] # ordered list of kernel (name,version)
bodies_by_name = {} # dict of bodies vs. kernel (name,version)
timeless_by_name = {} # dict of timeless state vs. (name,version)
# For each kernel...
for kernel in kernel_list:
spice_id = kernel.spice_id
namekey = (kernel.kernel_name, kernel.kernel_version)
timeless_by_name[namekey] = kernel.timeless
# Accumulate kernel names in load order and bodies per kernel name
if namekey in namekeys:
i = namekeys.index(namekey)
del namekeys[i]
namekeys.append(namekey)
bodies_by_name[namekey] |= {spice_id}
else:
namekeys.append(namekey)
bodies_by_name[namekey] = {spice_id}
# Delete SPICE IDs that appear in later versions of timeless kernels
for j in range(len(namekeys)):
namekey = namekeys[j]
if not timeless_by_name[namekey]: continue
if bodies_by_name[namekey] == {None}: continue
for k in range(j+1,len(namekeys)):
if namekey[0] == namekeys[k][0]:
bodies_by_name[namekey] -= bodies_by_name[namekeys[k]]
# Delete kernels that are no longer needed
for j in range(len(namekeys)-1, -1, -1):
if len(bodies_by_name[namekey]) == 0:
del namekeys[j]
# Remove kernels that are still used but identical except for the SPICE_ID
filtered_list = []
for kernel in kernel_list:
namekey = (kernel.kernel_name, kernel.kernel_version)
if namekey not in namekeys: continue
if kernel.spice_id not in bodies_by_name[namekey]: continue
for (k,filtered) in enumerate(filtered_list):
if filtered.filespec == kernel.filespec:
del filtered_list[k]
break
filtered_list.append(kernel)
return filtered_list
def _remove_overlaps(kernel_list, start_time, stop_time):
"""Filter out kernels completely overridden by higher-priority kernels.
For kernels that have time limits such as CKs and SPKs, this method
determines which kernels overlap higher-priority kernels, and removes
kernels from the list if they are not required. It returns the filtered
list in the proper load order.
Input:
kernel_list a list of KernelInfo objects as returned by one or more
calls to select_kernels("SPK", ...), in its intended load
order.
start_time the start time of the interval of interest, as ISO format
"yyyy-hh-mmThh:mm:ss" or as seconds TAI since January 1,
2000. None to ignore time limits and just select the most
recent kernel(s).
stop_time the stop time of the interval of interest. None to ignore
time limits. and just select the most recent kernel(s).
Return: A filtered list of kernels, in which unnecessary kernels
have been removed. An unnecessary kernel is one whose entire
time range is covered by higher-priority kernels.
"""
# Construct a dictionary of kernel lists, one list for each body
body_dict = {}
for kernel in kernel_list:
if kernel.spice_id not in body_dict:
body_dict[kernel.spice_id] = []
body_dict[kernel.spice_id].append(kernel)
# Sort the kernels in each list
for kernels in body_dict.values():
kernels.sort()
# If time limits are not specified, select the last kernel in each list
if start_time is None or stop_time is None:
filtered_kernels = []
for kernels in body_dict.values():
full_name = kernels[-1].full_name
filtered_kernels += [k for k in kernels if k.full_name == full_name]
return _sort_kernels(filtered_kernels)
# Define the time interval of interest
if type(start_time) == str:
interval_start_tai = julian.tai_from_iso(start_time)
else:
interval_start_tai = start_time
if type(stop_time) == str:
interval_stop_tai = julian.tai_from_iso(stop_time)
else:
interval_stop_tai = start_time
# Remove overlaps for each body individually
filtered_kernels = []
for id in body_dict:
# Create an empty interval
inter = interval.Interval(interval_start_tai, interval_stop_tai)
# Insert the kernels for this body, beginning with the lowest priority
for kernel in body_dict[id]:
kernel_start_tai = julian.tai_from_iso(kernel.start_time)
kernel_stop_tai = julian.tai_from_iso(kernel.stop_time)
inter[(kernel_start_tai,kernel_stop_tai)] = kernel
# Retrieve the needed kernels in the proper order
interval_kernels = inter[(interval_start_tai, interval_stop_tai)]
# A leading value of None means there is a gap in time coverage
if interval_kernels[0] is None:
interval_kernels = interval_kernels[1:]
# Add this set to the list
filtered_kernels += interval_kernels
return _sort_kernels(filtered_kernels)
def _fileno_str(filenos):
"""Construct a string listing filenos and their ranges inside brackets."""
# Copy and sort the list
filenos = list(filenos)
filenos.sort()
strlist = ['[', str(filenos[0])]
k_written = filenos[0]
k_prev = filenos[0]
for k in filenos[1:]:
# Don't write anything till we reach the end of a sequence
if k == k_prev + 1:
k_prev = k
continue
# Separate single values by commas
if k_prev == k_written:
strlist += [',']
# Use a comma on a list of just two
elif k_prev == k_written + 1:
strlist += [',', str(k_prev), ',']
# Otherwise, use a dash
else:
strlist += ['-', str(k_prev), ',']
strlist += [str(k)]
k_written = k
k_prev = k
if k_prev == k_written:
pass
elif k_prev == k_written + 1:
strlist += [',', str(k_prev)]
else:
strlist += ['-', str(k_prev)]
return ''.join(strlist + [']'])
def _fileno_values(name):
"""Return a kernel name and list of fileno values from a name string."""
# If there are no file_nos in the name, just return it with an empty list
if name[-1] != ']':
return (name, [])
# Isolate the name and indices
ibracket = name.index('[')
indices = name[ibracket+1:-1]
name = name[:ibracket]
# Interpret the indices
filenos = []
split_by_commas = index.split(',')
for item in split_by_commas:
split_by_dash = item.split('-')
if len(split_by_dash) == 2:
k0 = int(split_by_dash[0])
k1 = int(split_by_dash[1])
for fileno in range(k0,k1+1):
filenos.append(fileno)
else:
filenos.append(str(item))
return (name, filenos)
################################################################################
# Database Query Support
################################################################################
def _query_kernels(kernel_type, name=None, body=None, time=None, asof=None,
after=None, path=None, limit=True, redo=False):
"""Return a list of KernelInfo objects based on the given constraints.
Input:
kernel_type "SPK", "CK, "IK", "LSK", etc.
name a SQL match string for the name of the kernel; use "%" for
multiple wildcards and "_" for a single wildcard.
body zero or more SPICE body IDs.
time a tuple consisting of a start and stop time, each expressed
as a string in ISO format, "yyyy-mm-ddThh:mm:ss".
Alternatively, times may be given as elapsed seconds TAI
since January 1, 2000.
asof an optional date earlier than today for which values should
be returned. Wherever possible, the kernels selected will
have release dates earlier than this date. The date is
expressed as a string in ISO format or as a number of
seconds TAI elapsed since January 1, 2000.
after an optional date such that files originating earlier are not
considered. The date is expressed as a string in ISO format
or as a number of seconds TAI elapsed since January 1, 2000.
path an optional string that must appear within the file
specification path of the kernel.
limit True to limit the number of returned kernels to one where
appropriate; False to return all the matching kernels.
Return: A list of KernelInfo objects describing the files that match
the requirements.
"""
# Query the database
sql_string = _sql_query(kernel_type, name, body, time, asof, after, path,
limit)
table = db.query(sql_string)
# If nothing was returned, relax the "asof" and "after" constraints and try
# again
if redo and len(table) == 0 and (asof is not None or after is not None):
sql_string = _sql_query(kernel_type, name, body, time, None, None,
path, limit)
table = db.query(sql_string)
# If we still have nothing, raise an exception
if len(table) == 0:
raise ValueError("no results found matching query")
kernel_info = []
for row in table:
kernel_info.append(KernelInfo(row))
return kernel_info
def _sql_query(kernel_type, name=None, body=None, time=None, asof=None,
after=None, path=None, limit=True):
"""Generate a query string based on the constraints.
Input:
kernel_type "SPK", "CK, "IK", "LSK", etc.
name a SQL match string for the name of the kernel; use "%" for
multiple wildcards and "_" for a single wildcard.
body one or more SPICE body IDs.
time a tuple consisting of a start and stop time, each expressed
as a string in ISO format "yyyy-mm-ddThh:mm:ss".
Alternatively, times may be given as elapsed seconds TAI
since January 1, 2000.
asof an optional date earlier than today for which values should
be returned. Wherever possible, the kernels selected will
have release dates earlier than this date. The date is
expressed as a string in ISO format or as a number of
seconds TAI elapsed since January 1, 2000.
after an optional date such that files originating earlier are not
considered. The date is expressed as a string in ISO format
or as a number of seconds TAI elapsed since January 1, 2000.
path an optional string that must appear within the file
specification path of the kernel.
limit True to limit the number of returned kernels to one where
appropriate; False to return all the matching kernels.
Return: A complete SQL query string.
"""
# Begin query
query_list = ["SELECT ", COLUMN_STRING, " FROM SPICEDB\n"]
query_list += ["WHERE KERNEL_TYPE = '", kernel_type, "'\n"]
# Insert kernel name constraint
if name is not None:
query_list += ["AND KERNEL_NAME LIKE '", name, "'\n"]
# Insert body or bodies
bodies = 0
if body is not None:
if isinstance(body, numbers.Integral):
query_list += ["AND SPICE_ID = ", str(body), "\n"]
bodies = 1
else:
bodies = len(body)
if bodies == 0:
pass
elif bodies == 1:
query_list += ["AND SPICE_ID = ", str(body[0]), "\n"]
else:
query_list += ["AND SPICE_ID in (", str(list(body))[1:-1],
")\n"]
# Insert start and stop times
if time is None: time = (None, None)
(time0, time1) = time
if time0 is not None:
if type(time0) != str:
time0 = julian.ymdhms_format_from_tai(time0, sep="T", digits=0,
suffix="")
query_list += ["AND STOP_TIME >= '", time0, "'\n"]
if time1 is not None:
if type(time1) != str:
time1 = julian.ymdhms_format_from_tai(time1, sep="T", digits=0,
suffix="")
query_list += ["AND START_TIME <= '", time1, "'\n"]
# Insert path constraint
if path is not None:
path = path.replace('\\', '/') # Must change Windows file separator
query_list += ["AND FILESPEC LIKE '%", path, "%'\n"]
# Insert 'after' constraint except on second pass
if after is not None:
if type(after) != str:
after = julian.ymdhms_format_from_tai(after, sep="T", digits=0,
suffix="")
query_list += ["AND RELEASE_DATE >= '", after, "'\n"]
# Insert 'as of' constraint
if asof is not None:
if type(asof) != str:
asof = julian.ymdhms_format_from_tai(asof, sep="T", digits=0,
suffix="")
query_list += ["AND RELEASE_DATE <= '", asof, "'\n"]
# Return limited or unlimited results
if limit:
query_list += ["ORDER BY RELEASE_DATE DESC\n", "LIMIT 1\n"]
else:
query_list += ["ORDER BY RELEASE_DATE ASC\n"]
return "".join(query_list)
def _query_by_name(names, time=None):
"""Return a list of KernelInfo objects based on a name (including version).
Input:
names one or more full kernel names, including versions,
optionally indexed by file_no ranges.
time a tuple consisting of a start and stop time, each expressed
as a string in ISO format, "yyyy-mm-ddThh:mm:ss".
Alternatively, times may be given as elapsed seconds TAI
since January 1, 2000. Use None to return kernels regardless
of the time.
Return: A list of KernelInfo objects describing the files that match
the requirements.
"""
# Normalize the input
if type(names) == str: names = [names]
# Loop through names...
kernel_info = []
for name in names:
# Query the database
sql_string = _sql_query_by_name(name, time)
table = db.query(sql_string)
# If we have nothing, raise an exception
if len(table) == 0:
raise ValueError("no results found matching query")
for row in table:
kernel_info.append(KernelInfo(row))
return kernel_info
def _sql_query_by_name(name, time=None):
"""Generate a query string based on a kernel name.
Input:
name a full kernel name including version, optionally indexed by
file_no ranges.
time a tuple consisting of a start and stop time, each expressed
as a string in ISO format, "yyyy-mm-ddThh:mm:ss".
Alternatively, times may be given as elapsed seconds TAI
since January 1, 2000. Use None to return kernels regardless
of the time.
Return: A list of KernelInfo objects describing the files that match
the requirements.
"""
# Begin query
query_list = ["SELECT ", COLUMN_STRING, " FROM SPICEDB\n"]
# Extract file_no ranges if necessary
if name[-1] == ']':
ibracket = name.index('[')
index = name[ibracket+1:-1]
name = name[:ibracket]
query_list += ["WHERE FULL_NAME = '", name, "'\n"]
filenos = []
split_by_commas = index.split(',')
for item in split_by_commas:
split_by_dash = item.split('-')
if len(split_by_dash) == 2:
k0 = int(split_by_dash[0])
k1 = int(split_by_dash[1])
for fileno in range(k0,k1+1):
filenos.append(fileno)
else:
filenos.append(int(item))
query_list += ["AND FILE_NO in (", str(list(filenos))[1:-1], ")\n"]
else:
query_list += ["WHERE FULL_NAME = '", name, "'\n"]
# Insert start and stop times
if time is None: time = (None, None)
(time0, time1) = time
if time0 is not None:
if type(time0) != str:
time0 = julian.ymdhms_format_from_tai(time0, sep="T", digits=0,
suffix="")
query_list += ["AND STOP_TIME >= '", time0, "'\n"]
if time1 is not None:
if type(time1) != str:
time1 = julian.ymdhms_format_from_tai(time1, sep="T", digits=0,
suffix="")
query_list += ["AND START_TIME <= '", time1, "'\n"]
query_list += ["ORDER BY LOAD_PRIORITY ASC, RELEASE_DATE ASC\n"]
return "".join(query_list)
def _query_by_filespec(filespecs, time=None):
"""Return a list of KernelInfo objects based on a filename or pattern.
Input:
filespec one file path or match pattern.
time a tuple consisting of a start and stop time, each expressed
as a string in ISO format, "yyyy-mm-ddThh:mm:ss".
Alternatively, times may be given as elapsed seconds TAI
since January 1, 2000. Use None to return kernels regardless
of the time.
Return: A list of KernelInfo objects describing the files that match
the pattern.
"""
# Normalize the input
if type(filespecs) == str: filespecs = [filespecs]
# Loop through names...
kernel_info = []
for filespec in filespecs:
# Query the database
sql_string = _sql_query_by_filespec(filespec, time)
table = db.query(sql_string)
# If we have nothing, raise an exception
if len(table) == 0:
if time is not None: # Maybe it's just out of time range
sql_string = _sql_query_by_filespec(filespec)
table2 = db.query(sql_string)
if len(table2) > 0: continue
raise ValueError("no results found matching query")
for row in table:
kernel_info.append(KernelInfo(row))
return kernel_info
def _sql_query_by_filespec(filespec, time=None):
"""Generate a query string based on a kernel name.
Input:
filespec one file path or match pattern.
time a tuple consisting of a start and stop time, each expressed
as a string in ISO format, "yyyy-mm-ddThh:mm:ss".
Alternatively, times may be given as elapsed seconds TAI
since January 1, 2000. Use None to return kernels regardless
of the time.
Return: A list of KernelInfo objects describing the files that match
the requirements.
"""
# Begin query
query_list = ["SELECT ", COLUMN_STRING, " FROM SPICEDB\n"]
query_list += ["WHERE FILESPEC like '%", filespec, "'\n"]
# Insert start and stop times
if time is None: time = (None, None)
(time0, time1) = time
if time0 is not None:
if type(time0) != str:
time0 = julian.ymdhms_format_from_tai(time0, sep="T", digits=0,
suffix="")
query_list += ["AND STOP_TIME >= '", time0, "'\n"]
if time1 is not None:
if type(time1) != str:
time1 = julian.ymdhms_format_from_tai(time1, sep="T", digits=0,
suffix="")
query_list += ["AND START_TIME <= '", time1, "'\n"]
query_list += ["ORDER BY LOAD_PRIORITY ASC, RELEASE_DATE ASC\n"]
return "".join(query_list)
################################################################################
################################################################################
# Public API
################################################################################
################################################################################
def set_spice_path(spice_path=""):
"""Define the directory path to the root of the SPICE file directory tree.
Call with no argument to reset the path to its default value."""
global SPICE_PATH
SPICE_PATH = spice_path
def get_spice_path():
"""Return the current path to the root of the SPICE file directory tree.
If the path is undefined, it uses the value of environment variable
SPICE_PATH.
"""
global SPICE_PATH
if SPICE_PATH is None:
SPICE_PATH = os.environ["SPICE_PATH"]
return SPICE_PATH
def open_db(name=None):
"""Open the SPICE database given its name or file path.
If no name is given, the value of the environment variable
SPICE_SQLITE_DB_NAME is used.
"""
global IS_OPEN, DB_PATH
if IS_OPEN: return
if name is None:
if DB_PATH:
name = DB_PATH
else:
name = os.environ["SPICE_SQLITE_DB_NAME"]
db.open(name)
DB_PATH = name
IS_OPEN = True
def close_db():
"""Close the SPICE database."""
global IS_OPEN
if IS_OPEN:
db.close()
IS_OPEN = False
def db_is_open():
"""Return True if SPICE database is currently open."""
global IS_OPEN
return IS_OPEN
################################################################################