示例#1
1
文件: marsPos.py 项目: atmelino/PAT8
from jplephem.spk import SPK
kernel = SPK.open('de430.bsp')
print(kernel)
position = kernel[0,4].compute(2457061.5)
print(position)

示例#2
0
def _sun_coor(julian):
    """Return the sun's coordinates.

    Parameters
    ----------
    julian : np.ndarray
        1-D array containing Julian times in the J2000 epoch.

    Returns
    -------
    Coordinate
        Coordinate object containing the sun's position.
    """

    ephem = pkg_resources.resource_filename(__name__, '../data/de421.bsp')
    kernal = SPK.open(ephem)

    ssb2sunb = kernal[0, 10].compute(julian)
    ssb2eb = kernal[0, 3].compute(julian)
    eb2e = kernal[3, 399].compute(julian)
    e2sun = (ssb2sunb - ssb2eb - eb2e).T

    SPK.close(kernal)

    sun_coor = Coordinate(e2sun, "gcrs", julian)

    return sun_coor
示例#3
0
def _get_kernel(value):
    """
    Try importing jplephem, download/retrieve from cache the Satellite Planet
    Kernel corresponding to the given ephemeris.
    """
    if value is None or value.lower() == 'builtin':
        return None

    try:
        from jplephem.spk import SPK
    except ImportError:
        raise ImportError("Solar system JPL ephemeris calculations require "
                          "the jplephem package "
                          "(https://pypi.org/project/jplephem/)")

    if value.lower() == 'jpl':
        value = DEFAULT_JPL_EPHEMERIS

    if value.lower() in ('de430', 'de432s'):
        value = ('https://naif.jpl.nasa.gov/pub/naif/generic_kernels'
                 '/spk/planets/{:s}.bsp'.format(value.lower()))

    elif os.path.isfile(value):
        return SPK.open(value)

    else:
        try:
            urlparse(value)
        except Exception:
            raise ValueError(
                '{} was not one of the standard strings and '
                'could not be parsed as a file path or URL'.format(value))

    return SPK.open(download_file(value, cache=True))
示例#4
0
 def test_single_position(self):
     kernel = SPK(NAIF_DAF(open('de405.bsp', 'rb')))
     x, y, z = kernel[0,4].compute(2457061.5)
     # Expect rough agreement with a DE430 position from our README:
     self.assertAlmostEqual(x, 2.05700211e+08, delta=2.0)
     self.assertAlmostEqual(y, 4.25141646e+07, delta=2.0)
     self.assertAlmostEqual(z, 1.39379183e+07, delta=2.0)
     kernel.close()
示例#5
0
 def __init__(self, filename):
     self.filename = filename
     self.spk = SPK.open(filename)
     self.segments = [Segment(s.center, s.target, _build_compute(s))
                      for s in self.spk.segments]
     self.codes = set(s.center for s in self.segments).union(
                      s.target for s in self.segments)
示例#6
0
def main():
    for size in 10, 1000, 100000:
        jd = np.linspace(2414992.5, 2471184.50, size)
        kernel = SPK.open('de432.bsp')
        ephem = Ephemeris(de421)
        mars = kernel[0,4]

        print(size)
        print('-- old code (2 successive runs):')

        t0 = time()
        ephem.position('mars', jd)
        print(time() - t0)

        t0 = time()
        ephem.position('mars', jd)
        print(time() - t0)

        print('-- new SPK-powered code (2 successive runs):')

        t0 = time()
        mars.compute(jd)
        print(time() - t0)

        t0 = time()
        mars.compute(jd)
        print(time() - t0)

        print()
示例#7
0
def main():
    for size in 10, 1000, 100000:
        jd = np.linspace(2414992.5, 2471184.50, size)
        kernel = SPK.open('de421.bsp')
        ephem = Ephemeris(de421)
        mars = kernel[0,4]

        print(size)
        print('-- old code (2 successive runs):')

        t0 = time()
        ephem.position('mars', jd)
        print(time() - t0)

        t0 = time()
        ephem.position('mars', jd)
        print(time() - t0)

        print('-- new SPK-powered code (2 successive runs):')

        t0 = time()
        mars.compute(jd)
        print(time() - t0)

        t0 = time()
        mars.compute(jd)
        print(time() - t0)

        print()
示例#8
0
    def __init__(self,
                 sc_inertia,
                 wheel_inertias,
                 As,
                 C_principal_body,
                 wheel_rates=array([0, 0, 0, 0]),
                 mode="Nadir"):
        self.As = As  #assumes 4 wheels
        self.As_bar_inv = inv(vstack([self.As, array([1, -1, 1, -1])]))
        self.J = sc_inertia * 1.05
        self.Ics = wheel_inertias
        self.kp = 1
        self.kd = 1
        self.wheel_rates = wheel_rates
        self.mode = mode
        self.C_princ_body = C_principal_body

        # Load .bsp containing JPL ephemerides:
        self.kernel = SPK.open('de430.bsp')

        # Constants for each relevant celestial body:
        self.EARTH = 3
        self.MOON = 301
        self.SUN = 10
        self.CENTER = 0
示例#9
0
    def __init__(self, time, ephemerides):
        """Create an Ephemerides-instance that calculates ephemerides for the given time epochs.

        It is possible to not specify the time epochs when creating the instance (set `time=None`). In this case `time`
        must be supplied as a parameter to each call calculating ephemerides.

        The SPK-file is read and parsed at the creation of this instance. In particular the names and ids of the
        available objects are read.

        Args:
            time (Time):           Time epochs for which to calculate ephemerides.
            ephemerides (String):  Name of ephemerides to use.
        """
        self.time = time
        self.ephemerides = ephemerides

        # Open the SPK-file corresponding to the ephemerides
        eph_filepath = config.files.path(
            "ephemerides",
            file_vars=dict(ephemerides=ephemerides),
            download_missing=True)
        self._spk = SPK.open(eph_filepath)  # TODO: Close file in destructor
        dependencies.add(eph_filepath, label="ephemerides")

        # Parse segments in SPK file
        self._names, self._segments = self._parse_segments()
示例#10
0
 def __init__(self, path):
     self.path = path
     self.filename = os.path.basename(path)
     self.spk = SPK.open(path)
     self.segments = [SPICESegment(self, s) for s in self.spk.segments]
     self.codes = set(s.center for s in self.segments).union(
                      s.target for s in self.segments)
示例#11
0
def _get_kernel(value):
    """
    Try importing jplephem, download/retrieve from cache the Satellite Planet
    Kernel corresponding to the given ephemeris.
    """
    if value is None or value.lower() == 'builtin':
        return None

    if value.lower() == 'jpl':
        value = DEFAULT_JPL_EPHEMERIS

    if value.lower() in ('de430', 'de432s'):
        value = ('http://naif.jpl.nasa.gov/pub/naif/generic_kernels'
                 '/spk/planets/{:s}.bsp'.format(value.lower()))
    else:
        try:
            six.moves.urllib.parse.urlparse(value)
        except Exception:
            raise ValueError('{} was not one of the standard strings and '
                             'could not be parsed as a URL'.format(value))

    try:
        from jplephem.spk import SPK
    except ImportError:
        raise ImportError("Solar system JPL ephemeris calculations require "
                          "the jplephem package "
                          "(https://pypi.python.org/pypi/jplephem)")

    return SPK.open(download_file(value, cache=True))
示例#12
0
 def __init__(self, path):
     self.path = path
     self.filename = os.path.basename(path)
     self.spk = SPK.open(path)
     self.segments = [_Segment(s) for s in self.spk.segments]
     self.codes = set(s.center for s in self.segments).union(
                      s.target for s in self.segments)
示例#13
0
 def __init__(self, spk, units):
     self.kernel = SPK.open(spk)
     self.r_unit = units[0]
     self.v_unit = units[1]
     self.graph = nx.Graph()
     for edge in self.kernel.pairs:
         self.graph.add_edge(*edge)
     self.paths = nx.shortest_path(self.graph)
def v_earth(source):
    kernel = SPK.open('de435.bsp')
    time = source.obstime.jd
    position, velocity = kernel[0, 3].compute_and_differentiate(time)
    position2, velocity2 = kernel[3, 399].compute_and_differentiate(time)
    velocity = velocity - velocity2
    source = source.cartesian
    return np.dot(((velocity * 1000 * u.meter / u.day).to(u.meter / u.second)).T, source.xyz)
示例#15
0
 def setUp(self):
     try:
         self.spk = SPK.open('de421.bsp')
     except IOError:
         raise SkipTest('the "de421.bsp" SPK file is not available')
     segment = self.spk[0, 1]
     self.jalpha = segment.start_jd
     self.jomega = segment.end_jd
示例#16
0
    def jpl(number, jd):
        kernel = SPK.open('/Users/baotong/desktop/pulsar/de430.bsp')
        position, velocity = kernel[0, number].compute_and_differentiate(jd)

        #position=np.array(position)
        #velocity=np.array(velocity)
        velocity = velocity / 86400.0
        return [position, velocity]
示例#17
0
 def setUp(self):
     try:
         self.spk = SPK.open('de421.bsp')
     except IOError:
         raise SkipTest('the "de421.bsp" SPK file is not available')
     segment = self.spk[0,1]
     self.jalpha = segment.start_jd
     self.jomega = segment.end_jd
示例#18
0
 def __init__(self, spk, units):
     self.kernel = SPK.open(spk)
     self.r_unit = units[0]
     self.v_unit = units[1]
     self.graph = nx.Graph()
     for edge in self.kernel.pairs:
         self.graph.add_edge(*edge)
     self.paths = nx.shortest_path(self.graph)
示例#19
0
def load_kernel():
    from jplephem.spk import SPK
    kernel_path = Path(__file__).parent / 'data' / 'de432s.bsp'
    if not kernel_path.exists():
        raise FileNotFoundError(
            f'kernel data file {kernel_path} not found, '
            'run "python setup.py build" to install it locally')
    kernel = SPK.open(kernel_path)
    return kernel
示例#20
0
 def __init__(self, filename):
     self.filename = filename
     self.spk = SPK.open(filename)
     self.segments = [
         Segment(s.center, s.target, _build_compute(s))
         for s in self.spk.segments
     ]
     self.codes = set(s.center
                      for s in self.segments).union(s.target
                                                    for s in self.segments)
示例#21
0
def bsp_expiration(fileobj):
    """
    Return the expiration date for a .bsp file.
    """
    daf_object = DAF(fileobj)
    spk_object = SPK(daf_object)
    dates = [segment.end_jd for segment in spk_object.segments]
    # We take the closest end date, to expire the file as soon as it's obsolete
    end_jd = min(dates)
    return calendar_date(end_jd)
示例#22
0
	def __init__(self, mass, position=None):
		if not os.path.isfile('de430.bsp'):
			raise ValueError('de430.bsp Was not found!')
		self.kernel = SPK.open('de430.bsp')

		self.mass = np.longdouble(mass)
		self.hist = [[], [], []]
		if position is not None:
			self.pos = position
		else:
			self.pos = []
示例#23
0
    def __init__(self, mass, position=None):
        if not os.path.isfile('de430.bsp'):
            raise ValueError('de430.bsp Was not found!')
        self.kernel = SPK.open('de430.bsp')

        self.mass = np.longdouble(mass)
        self.hist = [[], [], []]
        if position is not None:
            self.pos = position
        else:
            self.pos = []
示例#24
0
 def __init__(self, path):
     self.path = path
     self.filename = os.path.basename(path)
     self.spk = SPK.open(path)
     self.segments = [
         Segment(s.center, s.target, _build_compute(s))
         for s in self.spk.segments
     ]
     self.codes = set(s.center
                      for s in self.segments).union(s.target
                                                    for s in self.segments)
示例#25
0
def get_jwst_position(times, jwstpos, debug=False):
    """Get the position of JWST.

    This returns the pair of relative positions to
    the barycenter and heliocenter in that order
    as a tuple of two arrays with 3 components

    Parameters
    ----------
    times : float, or 1-D ndarray of float
        A time or an array of times, in MJD (TT).

    jwstpos : 1-D array, or None
        `jwstpos` is a 3 element vector (list, tuple, whatever) in km if it
        is provided.

    debug : bool
        This is for testing.  If `debug` is `True`, the values returned
        will be the barycenter of the Earth and the center of the Sun (km),
        both with respect to the solar-system barycenter.

    Returns
    -------
    jwst_bary_vectors : ndarray, float
        Equatorial (ICRS) rectangular coordinates of JWST with respect to
        the solar-system barycenter, in km.  If `times` is a float,
        `jwst_bary_vectors` will have shape (3,); otherwise, it will have
        shape (3, nt), where `nt` is the length of the input `times`.

    jwst_sun_vectors : ndarray, float
        Equatorial (ICRS) rectangular coordinates of JWST with respect to
        the center of the Sun, in km.  If `times` is a float,
        `jwst_sun_vectors` will have shape (3,); otherwise, it will have
        shape (3, nt), where `nt` is the length of the input `times`.
    """

    ekernel = SPK.open(os.path.join(EPHEMERIS_PATH, 'de430.bsp'))
    # JPL ephemeris uses JD_tt based times
    barysun_baryearth_pos = ekernel[0, 3].compute(times + JDOFFSET)
    barysun_centersun_pos = ekernel[0, 10].compute(times + JDOFFSET)
    baryearth_centerearth_pos = ekernel[3, 399].compute(times + JDOFFSET)
    ekernel.close()
    if debug:
        return barysun_baryearth_pos, barysun_centersun_pos
    barysun_centerearth_pos = barysun_baryearth_pos + baryearth_centerearth_pos
    centersun_centerearth_pos = barysun_centerearth_pos - barysun_centersun_pos
    if jwstpos is not None:
        centerearth_jwst = jwstpos
    else:
        centerearth_jwst = jwst_ephem_interp(times)
    return (barysun_centerearth_pos + centerearth_jwst), \
            (centersun_centerearth_pos + centerearth_jwst)
示例#26
0
 def __init__(self, filename='de430.bsp'):
     self._kernel = SPK.open(filename)
     self._PlanetDict = {
         "Mercury": 1,
         "Venus": 2,
         "Earth": 3,
         "Mars": 4,
         "Jupiter": 5,
         "Saturn": 6,
         "Uranus": 7,
         "Neptune": 8,
         "Pluto": 9,
         "Sun": 10
     }
示例#27
0
    def open(self):
        """Open the files
        """
        segments = []

        files = config.get("env", "jpl", fallback=[])

        if not files:
            raise JplConfigError("No JPL file defined")

        # Extraction of segments from each .bsp file
        for filepath in files:

            filepath = Path(filepath)

            if filepath.suffix.lower() != ".bsp":
                continue

            segments.extend(SPK.open(str(filepath)).segments)

        if not segments:
            raise JplError("No segment loaded")

        # list of available segments
        self.segments = dict(((s.center, s.target), s) for s in segments)

        # This variable will contain the Target of reference from which
        # all relations between frames are linked
        targets = {}

        for center_id, target_id in self.segments.keys():

            center_name = target_names.get(center_id, "Unknown")
            target_name = target_names.get(target_id, "Unknown")

            # Retrieval of the Target object representing the center if it exists
            # or creation of said object if it doesn't.
            center = targets.setdefault(center_id,
                                        Target(center_name, center_id))
            target = targets.setdefault(target_id,
                                        Target(target_name, target_id))

            # Link between the Target objects (see Node2)
            center + target

        # We take the Earth target and make it the top of the structure.
        # That way, it is easy to link it to the already declared earth-centered reference frames
        # from the `frames.frame` module.
        self.top = targets[399]
示例#28
0
def position_sun_moon(bspFileName, time):

    jd = julian.to_jd(time, fmt='jd')

    kernel = SPK.open(bspFileName)
    positionMoon = kernel[3, 301].compute(jd)

    positionSun = kernel[0, 10].compute(jd)
    positionSun -= kernel[0, 3].compute(jd)
    positionSun -= kernel[3, 399].compute(jd)

    positionSun = positionSun * 1000
    positionMoon = positionMoon * 1000

    return positionSun, positionMoon
示例#29
0
 def __init__(self, file):
     if isinstance(file, str):
         file = open(file, 'rb')
     self.spk = SPK(file)
     segments = [Segment(s.center, s.target, _build_compute(s))
                 for s in self.spk.segments]
     codes = set(s.center for s in segments).union(
                 s.target for s in segments)
     for code in codes:
         body = Body(code, segments)
         self[code] = body
         raw_name = target_names.get(code, None)
         if raw_name is None:
             continue
         name = raw_name.lower().replace(' ', '_')
         setattr(self, name, body)
示例#30
0
    def open(self):
        """Open the files
        """
        segments = []

        files = config.get('env', 'jpl', fallback=[])

        if not files:
            raise JplConfigError("No JPL file defined")

        # Extraction of segments from each .bsp file
        for filepath in files:

            filepath = Path(filepath)

            if filepath.suffix.lower() != ".bsp":
                continue

            segments.extend(SPK.open(str(filepath)).segments)

        if not segments:
            raise JplError("No segment loaded")

        # list of available segments
        self.segments = dict(((s.center, s.target), s) for s in segments)

        # This variable will contain the Target of reference from which
        # all relations between frames are linked
        targets = {}

        for center_id, target_id in self.segments.keys():

            center_name = target_names.get(center_id, 'Unknown')
            target_name = target_names.get(target_id, 'Unknown')

            # Retrieval of the Target object representing the center if it exists
            # or creation of said object if it doesn't.
            center = targets.setdefault(center_id, Target(center_name, center_id))
            target = targets.setdefault(target_id, Target(target_name, target_id))

            # Link between the Target objects (see Node2)
            center + target

        # We take the Earth target and make it the top of the structure.
        # That way, it is easy to link it to the already declared earth-centered reference frames
        # from the `frames.frame` module.
        self.top = targets[399]
示例#31
0
def get_ephemerides(eph_date):
	#Can be downloaded from ftp://ssd.jpl.nasa.gov/pub/eph/planets/bsp
	eph = SPK.open('../input/de430.bsp')

	solar_system = OrderedDict()
	solar_system['date'] = eph_date.datetime.strftime('%Y-%m-%d')

	solar_system['Sun'] = np.hstack(eph[0,10].compute_and_differentiate(eph_date.jd))
	solar_system['Mercury'] = np.hstack(eph[0,1].compute_and_differentiate(eph_date.jd))
	solar_system['Venus'] = np.hstack(eph[0,2].compute_and_differentiate(eph_date.jd))
	solar_system['Earth'] = np.hstack(eph[0,3].compute_and_differentiate(eph_date.jd))
	solar_system['Mars'] = np.hstack(eph[0,4].compute_and_differentiate(eph_date.jd))
	solar_system['Jupiter'] = np.hstack(eph[0,5].compute_and_differentiate(eph_date.jd))	
	solar_system['Saturn'] = np.hstack(eph[0,6].compute_and_differentiate(eph_date.jd))
	solar_system['Uranus'] = np.hstack(eph[0,7].compute_and_differentiate(eph_date.jd))
	solar_system['Neptune'] = np.hstack(eph[0,8].compute_and_differentiate(eph_date.jd))

	return solar_system
示例#32
0
def _load_kernel_local(ephem, path=''):
    load_kernel = False # a flag for checking if the kernel has been loaded
    if path.endswith("%s.bsp" % ephem):
        custom_path = path
    else:
        custom_path = os.path.join(path, "%s.bsp" % ephem)
    search_list = [custom_path, datapath("%s.bsp" % ephem)]
    for p in search_list:
        if load_kernel:
            break
        try:# Bipass the astropy kernel loading system.
            coor.solar_system_ephemeris._kernel = SPK.open(p)
            coor.solar_system_ephemeris._value = p
            coor.solar_system_ephemeris._kernel.origin = coor.solar_system_ephemeris._value
            load_kernel = True
        except:
            load_kernel = False
    return load_kernel
示例#33
0
def _load_kernel_local(ephem, path=''):
    load_kernel = False # a flag for checking if the kernel has been loaded
    if path.endswith("%s.bsp" % ephem):
        custom_path = path
    else:
        custom_path = os.path.join(path, "%s.bsp" % ephem)
    search_list = [custom_path, datapath("%s.bsp" % ephem)]
    for p in search_list:
        if load_kernel:
            break
        try:# Bipass the astropy kernel loading system.
            coor.solar_system_ephemeris._kernel = SPK.open(p)
            coor.solar_system_ephemeris._value = p
            coor.solar_system_ephemeris._kernel.origin = coor.solar_system_ephemeris._value
            load_kernel = True
        except:
            load_kernel = False
    return load_kernel
示例#34
0
def get_summary(url, spk=True):
    ''' simple function to retrieve the header of a BSP file and return SPK object'''
    # connect to file at URL
    bspurl = urllib2.urlopen(url)
    # retrieve the "tip" of a file at URL
    bsptip = bspurl.read(10**5)  # first 100kB
    # save data in fake file object (in-memory)
    bspstr = StringIO(bsptip)
    # load into DAF object
    daf = DAF(bspstr)
    # return either SPK or DAF object
    if spk:
        # make a SPK object
        spk = SPK(daf)
        # return representation
        return spk
    else:
        # return representation
        return daf
示例#35
0
def Position_and_Velocity_Celestial_Body(celestial_body, time):
    # The JPL ephemeris index of the celestial body
    jpli = celestial_body.jplephem_index
    # Path to ephemeris file
    path_ephem = Directory + '/Information/Celestial_Bodies/Ephemerides/de430.bsp'
    # The ephemeris kernel
    kernel = SPK.open(path_ephem)
    # The position and velocity
    pv = np.vstack(kernel[jpli].compute_and_differentiate(time))
    # If the ephemeris was wrt to its local barcyentre
    if not jpli[0] == 0:
        # Compute barycentric position rather
        pv = np.add(pv, np.vstack(
            kernel[0, jpli[0]].compute_and_differentiate(time)))
        pass
    # Convert km to m
    pv[0, :] = np.multiply(pv[0, :], 1e3)
    # Convert km/day to m/s
    pv[1, :] = np.multiply(pv[1, :], 0.0115741)
    # Return a (2,3) numpy array
    return pv
示例#36
0
def get_jwst_position(times, jwstpos, debug=False):
    '''
    This returns the pair of relative positions to
    the barycenter and heliocenter in that order
    as a tuple of two arrays with 3 components
    '''
    ekernel = SPK.open(os.path.join(EPHEMERIS_PATH, 'de430.bsp'))
    # JPL ephemeris uses JD_tt based times
    barysun_baryearth_pos = ekernel[0, 3].compute(times + JDOFFSET)
    barysun_centersun_pos = ekernel[0, 10].compute(times + JDOFFSET)
    baryearth_centerearth_pos = ekernel[3, 399].compute(times + JDOFFSET)
    ekernel.close()
    if debug:
        return barysun_baryearth_pos, barysun_centersun_pos
    barysun_centerearth_pos = barysun_baryearth_pos + baryearth_centerearth_pos
    centersun_centerearth_pos = barysun_centerearth_pos - barysun_centersun_pos
    if jwstpos is not None:
        centerearth_jwst = jwstpos
    else:
        centerearth_jwst = jwst_ephem_interp(times)
    return (barysun_centerearth_pos + centerearth_jwst), \
            (centersun_centerearth_pos + centerearth_jwst)
示例#37
0
def objPosVel2SSB(objname, t, ephem):
    """This function computes a solar system object position and velocity respect
    to solar system barycenter using astropy coordinates get_body_barycentric()
    method.
    Parameters
    ----------
    objname: str
        Solar system object name. Current support solar system bodies are listed in
        astropy.coordinates.olar_system_ephemeris.bodies attribution.
    t: Astropy.time.Time object
        Observation time in Astropy.time.Time object format.
    ephem: str
        The ephem to for computing solar system object position and velocity
    """
    ephem = ephem.lower()
    objname = objname.lower()
    # Use astropy to compute postion.
    try:
        pos = coor.get_body_barycentric(objname, t, ephemeris=ephem)
    except ValueError:
        pos = coor.get_body_barycentric(objname, t, ephemeris= kernel_link_base + "%s.bsp" % ephem)
    # Use jplephem to compute velocity.
    # TODO: Astropy 1.3 will have velocity calculation availble.
    kernel = SPK.open(datapath("%s.bsp" % ephem))
    # Compute vel from planet barycenter to solar system barycenter
    lcod = len(str(jpl_obj_code[objname]))
    tjd1 = t.tdb.jd1
    tjd2 = t.tdb.jd2
    # Planets with barycenter computing
    if lcod == 3:
        _, vel_pbary_ssb = kernel[0,jpl_obj_code[objname]/100].compute_and_differentiate(tjd1, tjd2)
        _, vel_p_pbary = kernel[jpl_obj_code[objname]/100,
                        jpl_obj_code[objname]].compute_and_differentiate(tjd1, tjd2)
        vel = vel_pbary_ssb + vel_p_pbary
    # Planets without barycenter computing
    else:
         _, vel = kernel[0,jpl_obj_code[objname]].compute_and_differentiate(tjd1, tjd2)
    return PosVel(pos.xyz, vel / SECS_PER_DAY * u.km/u.second, origin='ssb', obj=objname)
示例#38
0
def objPosVel2SSB(objname, t, ephem):
    """This function computes a solar system object position and velocity respect
    to solar system barycenter using astropy coordinates get_body_barycentric()
    method.
    Parameters
    ----------
    objname: str
        Solar system object name. Current support solar system bodies are listed in
        astropy.coordinates.olar_system_ephemeris.bodies attribution.
    t: Astropy.time.Time object
        Observation time in Astropy.time.Time object format.
    ephem: str
        The ephem to for computing solar system object position and velocity
    """
    ephem = ephem.lower()
    objname = objname.lower()
    # Use astropy to compute postion.
    try:
        pos = coor.get_body_barycentric(objname, t, ephemeris=ephem)
    except ValueError:
        pos = coor.get_body_barycentric(objname, t, ephemeris= kernel_link_base + "%s.bsp" % ephem)
    # Use jplephem to compute velocity.
    # TODO: Astropy 1.3 will have velocity calculation availble.
    kernel = SPK.open(datapath("%s.bsp" % ephem))
    # Compute vel from planet barycenter to solar system barycenter
    lcod = len(str(jpl_obj_code[objname]))
    tjd1 = t.tdb.jd1
    tjd2 = t.tdb.jd2
    # Planets with barycenter computing
    if lcod == 3:
        _, vel_pbary_ssb = kernel[0,jpl_obj_code[objname]/100].compute_and_differentiate(tjd1, tjd2)
        _, vel_p_pbary = kernel[jpl_obj_code[objname]/100,
                        jpl_obj_code[objname]].compute_and_differentiate(tjd1, tjd2)
        vel = vel_pbary_ssb + vel_p_pbary
    # Planets without barycenter computing
    else:
        _, vel = kernel[0,jpl_obj_code[objname]].compute_and_differentiate(tjd1, tjd2)
    return PosVel(pos.xyz, vel / SECS_PER_DAY * u.km/u.second, origin='ssb', obj=objname)
示例#39
0
    def spk(self):
        if not hasattr(self, "_spk"):
            self._spk = []

            files = config.get("env", "jpl", "files", fallback=[])

            if not files:
                raise JplConfigError("No JPL file defined")

            # Extraction of segments from each .bsp file
            for filepath in files:

                filepath = Path(filepath)

                if filepath.suffix.lower() != ".bsp":
                    continue

                if not filepath.exists():
                    log.warning(f"File not found : {filepath}")
                    continue

                self._spk.append(SPK.open(str(filepath)))

        return self._spk
示例#40
0
__version__ = '0.7.0'

# Configure logging
logger = logging.getLogger(__name__)

# Find path to ephemeris from environmental variable.

JDOFFSET = 2400000.5

try:
    EPHEMERIS_PATH = os.environ['JPL_EPHEMERIS']
except KeyError:
    raise KeyError('Environmental variable JPL_EPHEMERIS not found')

ekernel = SPK.open(os.path.join(EPHEMERIS_PATH, 'de430.bsp'))

# The following three functions are only needed if reading from a file
# Currently it is obtained from a DMS database


def read_jwst_ephemeris(times):
    '''
    Returns the x,y,z positions of JWST with respect to the earth's center
    for the times provided. Times should be in JD.
    '''
    f = open(os.path.join(EPHEMERIS_PATH, 'ephem_10days.txt'), 'r')
    # First get header info.
    mdict = get_jwst_ephem_metadata(f)
    if ((mdict['CENTER_NAME'] != 'Earth') or (mdict['OBJECT_NAME'] != 'JWST')
            or (mdict['REF_FRAME'] != 'EME2000')
示例#41
0
文件: __init__.py 项目: sosey/jwst
__version__ = '0.7.0'

# Configure logging
logger = logging.getLogger(__name__)

# Find path to ephemeris from environmental variable.

JDOFFSET = 2400000.5

try:
    EPHEMERIS_PATH = os.environ['JPL_EPHEMERIS']
except KeyError:
    raise KeyError('Environmental variable JPL_EPHEMERIS not found')

ekernel = SPK.open(os.path.join(EPHEMERIS_PATH, 'de430.bsp'))

# The following three functions are only needed if reading from a file
# Currently it is obtained from a DMS database

def read_jwst_ephemeris(times):
    '''
    Returns the x,y,z positions of JWST with respect to the earth's center
    for the times provided. Times should be in JD.
    '''
    f = open(os.path.join(EPHEMERIS_PATH, 'ephem_10days.txt'), 'r')
    # First get header info.
    mdict = get_jwst_ephem_metadata(f)
    if ((mdict['CENTER_NAME'] != 'Earth') or
        (mdict['OBJECT_NAME'] != 'JWST') or
        (mdict['REF_FRAME'] != 'EME2000') or
示例#42
0
from jplephem.spk import SPK

#################
## JPL KERNELS ##
#################

modpath = os.path.abspath(os.path.dirname(__file__))
planetdatafile = os.path.join(modpath, 'data/de430.bsp')

# we'll try to load the SPK kernel. if that fails, we'll download it direct from
# JPL so the source distribution is kept small

try:

    # load the JPL kernel
    jplkernel = SPK.open(planetdatafile)
    HAVEKERNEL = True

except Exception:

    # this is so we don't download the JPL kernel when this module is imported
    # as part of a docs build on RTD
    import os
    RTD_INVOCATION = os.environ.get('RTD_IGNORE_HTLS_FAIL')

    if not RTD_INVOCATION:

        # this function is used to check progress of the download
        def on_download_chunk(transferred, blocksize, totalsize):
            progress = transferred * blocksize / float(totalsize) * 100.0
            print('{progress:.1f}%'.format(progress=progress), end='\r')
示例#43
0
 def __init__(self):
     self.jpl = SPK.open('/home/amigos/python/jpl_ephem/de430.bsp')
     # from https://pypi.python.org/pypi/jplephem
     self.geomech = geomech.geomech_monitor_client('172.20.0.12',8101)
示例#44
0
 def __init__(self, settlingTime=1., thrust=450., slewIsp=4160., scMass=6000.,\
              dryMass=3400., coMass=5800., occulterSep=55000., skIsp=220.,\
              defburnPortion=0.05, spkpath=None, forceStaticEphem=False,\
              **specs):
     
     # default Observatory values
     # instrument settling time after repoint (days)
     self.settlingTime = float(settlingTime)*u.day 
     # occulter slew thrust (mN)
     self.thrust = float(thrust)*u.mN 
     # occulter slew specific impulse (s)
     self.slewIsp = float(slewIsp)*u.s 
     # occulter (maneuvering sc) initial (wet) mass (kg)
     self.scMass = float(scMass)*u.kg 
     # occulter (maneuvering sc) dry mass (kg)
     self.dryMass = float(dryMass)*u.kg 
     # telescope (or non-maneuvering sc) mass (kg)
     self.coMass = float(coMass)*u.kg 
     # occulter-telescope distance (km)
     self.occulterSep = float(occulterSep)*u.km
     # station-keeping Isp (s)
     self.skIsp = float(skIsp)*u.s 
     # default burn portion
     self.defburnPortion = float(defburnPortion)
     
     # set values derived from quantities above
     # slew flow rate (kg/day)
     self.flowRate = (self.thrust/const.g0/self.slewIsp).to('kg/day')
     
     #if jplephem is available, we'll use that for propagating solar system bodies
     #otherwise, use static ephemeris
     if not forceStaticEphem:
         try:
             from jplephem.spk import SPK
             self.havejplephem = True
         except ImportError:
             print "WARNING: Module jplephem not found, using static solar system ephemeris."
             self.havejplephem = False
     else:
         self.havejplephem = False
         print "Using static solar system ephemeris."
     
     # populate outspec
     for att in self.__dict__.keys():
         dat = self.__dict__[att]
         self._outspec[att] = dat.value if isinstance(dat,u.Quantity) else dat
     
     # define function for calculating obliquity of the ecliptic 
     # (arg Julian centuries from J2000)
     self.obe = lambda TDB: 23.439279 - 0.0130102*TDB - 5.086e-8*(TDB**2) + \
             5.565e-7*(TDB**3) + 1.6e-10*(TDB**4) + 1.21e-11*(TDB**5) 
     
     # if you have jplephem, load spice file, otherwise load static ephem
     if self.havejplephem:
         if (spkpath is None) or not(os.path.exists(spkpath)):
             # if the path does not exist, load the default de432s.bsp
                 classpath = os.path.split(inspect.getfile(self.__class__))[0]
                 classpath = os.path.normpath(os.path.join(classpath,'..','Observatory'))
                 filename = 'de432s.bsp'
                 spkpath = os.path.join(classpath, filename)
         self.kernel = SPK.open(spkpath)
     else:
         """All ephemeride data from Vallado Appendix D.4
         Values are:
         a     e             I               O                       w                   lM
         sma   eccentricity  inclination     long. ascending node    long. perihelion    mean longitude
         AU    N/A           deg             deg                     deg                 deg
         """
         
         # Store Mercury ephemerides data (ecliptic)
         Mercurya = 0.387098310
         Mercurye = [0.20563175, 0.000020406, -0.0000000284, -0.00000000017]
         Mercuryi = [7.004986, -0.0059516, 0.00000081, 0.000000041]
         MercuryO = [48.330893, -0.1254229, -0.00008833, -0.000000196]
         Mercuryw = [77.456119, 0.1588643, -0.00001343, 0.000000039]
         MercurylM = [252.250906, 149472.6746358, -0.00000535, 0.000000002]
         Mercury = self.SolarEph(Mercurya, Mercurye, Mercuryi, MercuryO, Mercuryw, MercurylM)
         
         # Store Venus epemerides data (ecliptic)
         Venusa = 0.723329820
         Venuse = [0.00677188, -0.000047766, 0.0000000975, 0.00000000044]
         Venusi = [3.394662, -0.0008568, -0.00003244, 0.000000010]
         VenusO = [76.679920, -0.2780080, -0.00014256, -0.000000198]
         Venusw = [131.563707, 0.0048646, -0.00138232, -0.000005332]
         VenuslM = [181.979801, 58517.8156760, 0.00000165, -0.000000002]
         Venus = self.SolarEph(Venusa, Venuse, Venusi, VenusO, Venusw, VenuslM)
         
         # Store Earth ephemerides data (ecliptic)
         Eartha = 1.000001018
         Earthe = [0.01670862, -0.000042037, -0.0000001236, 0.00000000004]
         Earthi = [0., 0.0130546, -0.00000931, -0.000000034]
         EarthO = [174.873174, -0.2410908, 0.00004067, -0.000001327]
         Earthw = [102.937348, 0.3225557, 0.00015026, 0.000000478]
         EarthlM = [100.466449, 35999.3728519, -0.00000568, 0.]
         Earth = self.SolarEph(Eartha, Earthe, Earthi, EarthO, Earthw, EarthlM)
         
         # Store Mars ephemerides data (ecliptic)
         Marsa = 1.523679342
         Marse = [0.09340062, 0.000090483, -0.0000000806, -0.00000000035]
         Marsi = [1.849726, -0.0081479, -0.00002255, -0.000000027]
         MarsO = [49.558093, -0.2949846, -0.00063993, -0.000002143]
         Marsw = [336.060234, 0.4438898, -0.00017321, 0.000000300]
         MarslM = [355.433275, 19140.2993313, 0.00000261, -0.000000003]
         Mars = self.SolarEph(Marsa, Marse, Marsi, MarsO, Marsw, MarslM)
         
         # Store Jupiter ephemerides data (ecliptic)
         Jupitera = [5.202603191, 0.0000001913]
         Jupitere = [0.04849485, 0.000163244, -0.0000004719, -0.00000000197]
         Jupiteri = [1.303270, -0.0019872, 0.00003318, 0.000000092]
         JupiterO = [100.464441, 0.1766828, 0.00090387, -0.000007032]
         Jupiterw = [14.331309, 0.2155525, 0.00072252, -0.000004590]
         JupiterlM = [34.351484, 3034.9056746, -0.00008501, 0.000000004]
         Jupiter = self.SolarEph(Jupitera, Jupitere, Jupiteri, JupiterO, Jupiterw, JupiterlM)
         
         # Store Saturn ephemerides data (ecliptic)
         Saturna = [9.554909596, -0.0000021389]
         Saturne = [0.05550862, -0.000346818, -0.0000006456, 0.00000000338]
         Saturni = [2.488878, 0.0025515, -0.00004903, 0.000000018]
         SaturnO = [113.665524, -0.2566649, -0.00018345, 0.000000357]
         Saturnw = [93.056787, 0.5665496, 0.00052809, 0.000004882]
         SaturnlM = [50.077471, 1222.1137943, 0.00021004, -0.000000019]
         Saturn = self.SolarEph(Saturna, Saturne, Saturni, SaturnO, Saturnw, SaturnlM)
         
         # Store Uranus ephemerides data (ecliptic)
         Uranusa = [19.218446062, -0.0000000372, 0.00000000098]
         Uranuse = [0.04629590, -0.000027337, 0.0000000790, 0.00000000025]
         Uranusi = [0.773196, -0.0016869, 0.00000349, 0.000000016]
         UranusO = [74.005947, 0.0741461, 0.00040540, 0.000000104]
         Uranusw = [173.005159, 0.0893206, -0.00009470, 0.000000413]
         UranuslM = [314.055005, 428.4669983, -0.00000486, 0.000000006]
         Uranus = self.SolarEph(Uranusa, Uranuse, Uranusi, UranusO, Uranusw, UranuslM)
         
         # Store Neptune ephemerides data (ecliptic)
         Neptunea = [30.110386869, -0.0000001663, 0.00000000069]
         Neptunee = [0.00898809, 0.000006408, -0.0000000008]
         Neptunei = [1.769952, 0.0002257, 0.00000023, -0.000000000]
         NeptuneO = [131.784057, -0.0061651, -0.00000219, -0.000000078]
         Neptunew = [48.123691, 0.0291587, 0.00007051, 0.]
         NeptunelM = [304.348665, 218.4862002, 0.00000059, -0.000000002]
         Neptune = self.SolarEph(Neptunea, Neptunee, Neptunei, NeptuneO, Neptunew, NeptunelM)
         
         # Store Pluto ephemerides data (ecliptic)
         Plutoa = [39.48168677, -0.00076912]
         Plutoe = [0.24880766, 0.00006465]
         Plutoi = [17.14175, 0.003075]
         PlutoO = [110.30347, -0.01036944]
         Plutow = [224.06676, -0.03673611]
         PlutolM = [238.92881, 145.2078]
         Pluto = self.SolarEph(Plutoa, Plutoe, Plutoi, PlutoO, Plutow, PlutolM)
         
         #store all as dictionary:
         self.planets = {'Mercury': Mercury,
                         'Venus': Venus,
                         'Earth': Earth,
                         'Mars': Mars,
                         'Jupiter': Jupiter,
                         'Saturn': Saturn,
                         'Uranus': Uranus,
                         'Neptune': Neptune,
                         'Pluto': Pluto}
示例#45
0
    body = Pck()[name]
    body.propagate = lambda date: get_orbit(name, date)
    return body


if __name__ == '__main__':  # pragma: no cover

    import sys

    config.update({
        'eop': {
            'missing_policy': "pass"
        }
    })

    for file in sys.argv[1:]:
        print(file)
        print("*" * len(file))
        for segment in SPK.open(file).segments:

            start = Date(segment.start_jd - Date.JD_MJD)
            end = Date(segment.end_jd - Date.JD_MJD)

            center = target_names[segment.center]
            target = target_names[segment.target]
            print("from {start:{fmt}} to {end:{fmt}} : {center} -> {target}".format(
                start=start, end=end, center=center, target=target,
                fmt="%Y-%m-%d"
            ))
        print()
示例#46
0
def ephem(iaucode, peph, objcode, timefile, kern=None, output='sky'):

############## Reading planetary kernel ##############################################
    if peph[-3:] != 'bsp':
        peph = peph + '.bsp'
    if not os.path.isfile(peph):
        raise OSError('Planetary Kernel {} not found'.format(peph[:-4]))
    kernel = SPK.open(peph)

########## Reading Time File  #######################################################
    if isinstance(timefile, str): ## if input is a file
        jd = np.loadtxt(timefile)
        time = Time(jd, format='jd', scale='utc')
    elif isinstance(timefile, Time):  ## if input is Time Object of Astropy
        time = timefile
    else: ## if input is an array or a number
        time = Time(timefile, format='jd', scale='utc')
    timetdb = time.tdb
       
        
####################### look for object kernel ###########################################
    objt, objn, objm, objk = objs(objcode, kern)
    objk = objk + '.bsp'
    if not os.path.isfile(objk):
        raise OSError('Object Kernel {} not found'.format(objk[:-4]))
    kernelobj = SPK.open(objk)
  
######## Checking if it is geocenter or not and getting topocentric vectors ############
##### Running low yet, have to see for many times #######
    if not isinstance(iaucode, str):
        iaucode = str(iaucode)
    if iaucode.lower() not in ['g', 'geocenter']:
        ### not geocenter
        gcrsx, gcrsy, gcrsz = [], [], []
        site, siten = sitios(iaucode)
        for i in time.utc:
            itrs = site.get_itrs(obstime=i)
            gcrs = itrs.transform_to(GCRS(obstime=i))
            gcrsx.append(gcrs.cartesian.x.value)
            gcrsy.append(gcrs.cartesian.y.value)
            gcrsz.append(gcrs.cartesian.z.value)
        gcrsx = gcrsx*u.m
        gcrsy = gcrsy*u.m
        gcrsz = gcrsz*u.m
    else:
        ### geocenter
        siten = 'Geocenter'

#########################################################################################

## compute vector Solar System Barycenter -> Earth Geocenter -> Topocenter
    if iaucode.lower() in ['g', 'geocenter']:
        geop = kernel[0,3].compute(timetdb.jd) + kernel[3,399].compute(timetdb.jd)
    else:
        geop = kernel[0,3].compute(timetdb.jd) + kernel[3,399].compute(timetdb.jd) + np.array([gcrsx.to(u.km).value,gcrsy.to(u.km).value,gcrsz.to(u.km).value])

########### Calculates time delay ###########################################
# delt = light time
# n = number of loops necessary

    delt = 0*u.s
    n = 0
    while True:
        ### calculates new time
        tempo = timetdb - delt
        ### calculates vector Solar System Baricenter -> Object
        positm = np.array([0.0, 0.0, 0.0])
        if objk == ephs['lau'] + '.bsp':
            objtj, objnj, objmj, objkj = objs(599)
            kernelj = SPK.open(objkj + '.bsp')
            objp = kernel[0,5].compute(tempo.jd) + kernelj[5,599].compute(tempo.jd)[0:3] + compute(kernelobj,599,objn,tempo.jd)[0:3]
        elif objt in ['s', 'p']:
            cc = objn//100
            objp = kernel[0,cc].compute(tempo.jd) + compute(kernelobj,cc,objn,tempo.jd)[0:3]
        elif objt in ['t', 'c']:
            objp = kernel[0,10].compute(tempo.jd) + compute(kernelobj,10,objn,tempo.jd)[0:3]
        ### calculates vector Earth Geocenter -> Object
        position = (objp - geop)
        ### calculates linear distance Earth Geocenter -> Object
        dist = np.linalg.norm(position, axis=0)*u.km
        ### calculates new light time
        delt = (dist/const.c).decompose()
        n = n + 1
        ### if difference between new and previous light time is smaller than 0.001 sec, than continue.
        if np.all(np.absolute(((timetdb - tempo) - delt).sec) < 0.001):
            break
           
##############################################################################
### Creating SkyCoord Object with the coordinates for each instant
    coord = SkyCoord(position[0], position[1], position[2], frame='icrs', unit=u.km, representation='cartesian')

    
### returning values
    if output  == 'radec':
        return coord.spherical.lon.hourangle, coord.spherical.lat.deg
    elif output == 'sky':
        return SkyCoord(ra=coord.spherical.lon, dec=coord.spherical.lat, distance=coord.spherical.distance)
    elif output == 'xyz':
        return coord.cartesian.x, coord.cartesian.y, coord.cartesian.z
    elif isinstance(output, str):
        f = open(output, 'w')
        f.write('Object={}, Kernel={}+{}, Site={}\n\n'.format(objn, objk[:-4], peph[:-4], siten))
        for i in np.arange(len(time)):
            f.write(' {:013.10f} {:+013.9f} {:16.8f} {:16.8f}\n'.format(coord[i].spherical.lon.hourangle, coord[i].spherical.lat.deg, time[i].utc.jd, time[i].tdb.jd))
        f.close()
示例#47
0
        # asteroid database:
        path_to_database = config.get("Path", "asteroid_database_path")
        f_database = os.path.join(path_to_database, "ELEMENTS.NUMBR")

        try:
            asteroid = asteroid_data_load(_f_database=f_database, asteroid_name=name)
            # print(asteroid)
        except Exception:
            # print error code 2 (failed to load asteroid database) and exit
            print(2, ra_apr, dec_apr, ra_rate_apr, dec_rate_apr)
            raise SystemExit

        try:
            # init jplephem:
            f_spk = config.get("Path", "jpl_ephem_spk_kernel")
            kernel = SPK.open(f_spk)
        except Exception:
            # print error code 3 (failed to load JPL DE ephemeris) and exit
            print(3, ra_apr, dec_apr, ra_rate_apr, dec_rate_apr)
            raise SystemExit

        try:
            ra, dec, ra_rate, dec_rate = get_current_state_asteroid(_asteroid=asteroid, _kernel=kernel)
            print(0, ra, dec, ra_rate, dec_rate)
        except Exception:
            # print error code 4 (calculation failed) and exit
            print(4, ra_apr, dec_apr, ra_rate_apr, dec_rate_apr)
            raise SystemExit

    else:
        """ planets and moons """
示例#48
0
    """
    if "de421.bsp" in kernel_filenames:
        kernel = "de421.bsp"
    elif kernel_filenames:
        kernel = kernel_filenames[0]
    else:
        kernel = None

    return kernel

kernel_fname = select_kernel(
    glob.glob(os.path.join(SPK_LOCAL_DIR, "*.bsp")))

if kernel_fname:
    default_kernel = SPK.open(kernel_fname)
else:
    warnings.warn("""No SPICE kernels found under ~/.poliastro.
Please download them manually or using

  poliastro download-spk [-d NAME]

to provide a default kernel, else pass a custom one as
an argument to `planet_ephem`.""")
    default_kernel = None


def download_kernel(name):
    """Downloads SPICE kernel by name.

    The function will try the top SPK path first, and then the old versions