def test_analytical_propagator(self):
        """
        analytical_propagator test
        """
        parameters = {
            "eccentricity": 0.0008641,
            "semimajor_axis": 6801395.04,
            "inclination": radians(87.0),
            "perigee_argument": radians(20.0),
            "right_ascension_of_ascending_node": radians(10.0),
            "anomaly": radians(0.0),
            "anomaly_type": "TRUE",
            "orbit_update_date": '2021-12-02T00:00:00.000',
            "frame": "EME"
        }
        k_orbit = keplerian_orbit(parameters)
        test1 = analytical_propagator(parameters)
        test2 = KeplerianPropagator(keplerian_orbit(parameters),
                                    Constants.WGS84_EARTH_MU)
        time1 = orekit_utils.absolute_time_converter_utc_string(
            '2022-01-02T00:00:00.000')

        self.assertTrue(
            test1.getPVCoordinates(time1, FramesFactory.getEME2000()).toString(
            ) == test2.getPVCoordinates(time1,
                                        FramesFactory.getEME2000()).toString())
Beispiel #2
0
    def _get_frame(self, name):
        '''Uses a string to identify which coordinate frame to initialize from Orekit package.

        See `Orekit FramesFactory <https://www.orekit.org/static/apidocs/org/orekit/frames/FramesFactory.html>`_
        '''
        if self.logger_func is not None:
            self._logger_start('_get_frame')

        if name == 'EME':
            return FramesFactory.getEME2000()
        elif name == 'CIRF':
            return FramesFactory.getCIRF(IERSConventions.IERS_2010,
                                         not self.frame_tidal_effects)
        elif name == 'ITRF':
            return FramesFactory.getITRF(IERSConventions.IERS_2010,
                                         not self.frame_tidal_effects)
        elif name == 'TIRF':
            return FramesFactory.getTIRF(IERSConventions.IERS_2010,
                                         not self.frame_tidal_effects)
        elif name == 'ITRFEquinox':
            return FramesFactory.getITRFEquinox(IERSConventions.IERS_2010,
                                                not self.frame_tidal_effects)
        if name == 'TEME':
            return FramesFactory.getTEME()
        else:
            raise Exception('Frame "{}" not recognized'.format(name))

        if self.logger_func is not None:
            self._logger_record('_get_frame')
Beispiel #3
0
def frame_to_string(frame):
    """
	Given a orekit frame object with the following defined options below, the fucntion returns the orekit
	associated frame string.
	Args:
		frame: (Frame) with the following options...
					ITRF (geocentric and rotates with earth for use
						for points near or on earth's surface--very accurate)
					Earth Centered Inertial (ECI) Frame
						the frame is fixed to the celetial grid and doesn't rotate
						with the earth
					ECI frame, but specifically used by NORAD TLEs
					very specific frame defined at an coordinate on or near
									  the surface of an object (here we define earth). Rotates
									  with body defined by ITRF frame (can think as an offset
									  of ITRF frame for things like ground stations)
	Returns:
		string OR -1 if undefined Frame
	"""
    if frame == FramesFactory.getITRF(IERSConventions.IERS_2010, True):
        return utils.ITRF
    elif frame == FramesFactory.getEME2000():
        return utils.EME
    elif frame == FramesFactory.getTEME():
        return utils.TEME
    else:
        return -1
def is_day_local_time(local_date, station_frame, time_zone, summer_time):
    """
    Check if it's day or not at a given date (in local time) at a given place on Earth'


    Parameters
    ----------
    utc_date : AbsoluteDate
        date and time in the UTC.
    station_frame : Topocentric Frame
        Frame of the place on Earth.
    time_zone : int
        Time zone of the place where you stand on Earth (e.g. 1 for Paris, 0 for London...).
    summer_time : bool
        True if it's summer time, False otherwise.

    Returns
    -------
    bool
        True if it is day, False otherwise.

    """
    j2000 = FramesFactory.getEME2000()
    pv_sun = CelestialBodyFactory.getSun()
    pv_sun = PVCoordinatesProvider.cast_(pv_sun)
    if summer_time:  # heure d'ete
        time_zone += 1
    sun_pos_j2000 = pv_sun.getPVCoordinates(local_date.shiftedBy(-time_zone * 60.0 * 60),
                                            j2000).getPosition()
    j2000_to_topocentric = j2000.getTransformTo(station_frame,
                                                local_date.shiftedBy(-time_zone * 60.0 * 60))
    sun_pos_topo = j2000_to_topocentric.transformPosition(sun_pos_j2000)
    return sun_pos_topo.getZ() > 0
Beispiel #5
0
    def test_get_ground_passes(self):
        """
        Testing whether OreKit finds ground passess
        """
        # test will fail if setup_orekit fails

        utc = TimeScalesFactory.getUTC()
        ra = 500 * 1000         #  Apogee
        rp = 400 * 1000         #  Perigee
        i = radians(55.0)      # inclination
        omega = radians(20.0)   # perigee argument
        raan = radians(10.0)  # right ascension of ascending node
        lv = radians(0.0)    # True anomaly

        epochDate = AbsoluteDate(2020, 1, 1, 0, 0, 00.000, utc)
        initial_date = epochDate

        a = (rp + ra + 2 * Constants.WGS84_EARTH_EQUATORIAL_RADIUS) / 2.0
        e = 1.0 - (rp + Constants.WGS84_EARTH_EQUATORIAL_RADIUS) / a

        ## Inertial frame where the satellite is defined
        inertialFrame = FramesFactory.getEME2000()

        ## Orbit construction as Keplerian
        initialOrbit = KeplerianOrbit(a, e, i, omega, raan, lv,
                                    PositionAngle.TRUE,
                                    inertialFrame, epochDate, Constants.WGS84_EARTH_MU)

        propagator = KeplerianPropagator(initialOrbit)
        durand_lat = 37.4269
        durand_lat = -122.1733
        durand_alt = 10.0

        output = get_ground_passes(propagator, durand_lat, durand_lat, durand_alt, initial_date, initial_date.shiftedBy(3600.0 * 24), ploting_param=False)
        assert len(output) == 5
Beispiel #6
0
    def test_string_to_frame(self):
        """
        string_to_frame tests
        """
        frame_ITRF_1 = orekit_utils.string_to_frame("ITRF")
        frame_ITRF_2 = FramesFactory.getITRF(IERSConventions.IERS_2010, True)
        self.assertTrue(frame_ITRF_1.equals(frame_ITRF_2))

        frame_EME2000_1 = orekit_utils.string_to_frame("EME")
        frame_EME2000_2 = FramesFactory.getEME2000()
        frame_EME2000_3 = orekit_utils.string_to_frame("J2000")
        self.assertTrue(frame_EME2000_1.equals(frame_EME2000_2) and
                            frame_EME2000_1.equals(frame_EME2000_3))

        frame_TEME_1 = orekit_utils.string_to_frame("TEME")
        frame_TEME_2 = FramesFactory.getTEME()
        self.assertTrue(frame_TEME_1.equals(frame_TEME_2))


        frame_Topo_1 = orekit_utils.string_to_frame("Topocentric", 5., 5., 5., "groundstation_1")
        earth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                         Constants.WGS84_EARTH_FLATTENING,
                         FramesFactory.getITRF(IERSConventions.IERS_2010, True))
        location = GeodeticPoint(radians(5.), radians(5.), 5.)
        frame_Topo_2 = TopocentricFrame(earth, location, "groundstation_1")
        self.assertTrue(frame_Topo_1.getNadir().equals(frame_Topo_2.getNadir()))
Beispiel #7
0
 def test_frame_to_string(self):
     """
     frame_to_string test
     """
     EME = FramesFactory.getEME2000()
     ITRF = FramesFactory.getITRF(IERSConventions.IERS_2010, True)
     TEME = FramesFactory.getTEME()
     self.assertTrue(orekit_utils.frame_to_string(EME) == "EME")
     self.assertTrue(orekit_utils.frame_to_string(ITRF) == "ITRF")
     self.assertTrue(orekit_utils.frame_to_string(TEME) == "TEME")
Beispiel #8
0
def _pose_absolute_keplerian(ns_spacecraft, init_coords, init_epoch):
    pos = init_coords["init_coord"]
    init_state = Cartesian()

    init_pose_oe = KepOrbElem()
    init_pose_oe.a = float(pos["a"])
    init_pose_oe.e = float(pos["e"])
    init_pose_oe.i = float(radians(pos["i"]))
    init_pose_oe.O = float(radians(pos["O"]))
    init_pose_oe.w = float(radians(pos["w"]))
    try:
        init_pose_oe.v = float(radians(pos["v"]))
    except KeyError:
        try:
            init_pose_oe.m = float(radians(pos["m"]))
        except KeyError:
            raise ValueError("No Anomaly for initialization of spacecraft: " +
                             ns_spacecraft)

    # Coordinates given in J2000 Frame
    # ----------------------------------------------------------------------------------------
    if init_coords["coord_frame"] == "J2000":
        init_state.from_keporb(init_pose_oe)
    # ----------------------------------------------------------------------------------------

    if init_coords["coord_frame"] == "TEME":
        teme_state = CartesianTEME()
        teme_state.from_keporb(init_pose_oe)

        init_frame = FramesFactory.getTEME()
        inertialFrame = FramesFactory.getEME2000()

        TEME2EME = init_frame.getTransformTo(inertialFrame,
                                             to_orekit_date(init_epoch))
        p = Vector3D(
            float(1e3),  # convert to [m]
            Vector3D(float(teme_state.R[0]), float(teme_state.R[1]),
                     float(teme_state.R[2])))
        v = Vector3D(
            float(1e3),  # convert to [m/s]
            Vector3D(float(teme_state.V[0]), float(teme_state.V[1]),
                     float(teme_state.V[2])))

        pv_EME = TEME2EME.transformPVCoordinates(PVCoordinates(p, v))

        init_state.R = np.array([
            pv_EME.position.x, pv_EME.position.y, pv_EME.position.z
        ]) / 1e3  # convert to [km]
        init_state.V = np.array([
            pv_EME.velocity.x, pv_EME.velocity.y, pv_EME.velocity.z
        ]) / 1e3  # convert to [km/s]

    # ----------------------------------------------------------------------------------------

    return init_state
Beispiel #9
0
    def _get_frame(self, name):
        '''Uses a string to identify which coordinate frame to initialize from Orekit package.

        See `Orekit FramesFactory <https://www.orekit.org/static/apidocs/org/orekit/frames/FramesFactory.html>`_
        '''

        if self.profiler is not None:
            self.profiler.start('Orekit:get_frame')

        if name == 'EME':
            frame = FramesFactory.getEME2000()
        elif name == 'EME2000':
            frame = FramesFactory.getEME2000()
        elif name == 'GCRF':
            frame = FramesFactory.getGCRF()
        elif name == 'CIRF':
            frame = FramesFactory.getCIRF(
                IERSConventions.IERS_2010,
                not self.settings['frame_tidal_effects'])
        elif name == 'ITRF':
            frame = FramesFactory.getITRF(
                IERSConventions.IERS_2010,
                not self.settings['frame_tidal_effects'])
        elif name == 'TIRF':
            frame = FramesFactory.getTIRF(
                IERSConventions.IERS_2010,
                not self.settings['frame_tidal_effects'])
        elif name == 'ITRFEquinox':
            frame = FramesFactory.getITRFEquinox(
                IERSConventions.IERS_2010,
                not self.settings['frame_tidal_effects'])
        elif name == 'TEME':
            frame = FramesFactory.getTEME()
        else:
            raise Exception('Frame "{}" not recognized'.format(name))

        if self.profiler is not None:
            self.profiler.stop('Orekit:get_frame')

        return frame
Beispiel #10
0
def _pose_absolute_cartesian(ns_spacecraft, init_coords, init_epoch):
    pos = init_coords["init_coord"]
    init_state = Cartesian()

    # Coordinates given in J2000 Frame
    # ----------------------------------------------------------------------------------------
    if init_coords["coord_frame"] == "J2000":
        init_state.R = np.array(
            [float(pos["x"]),
             float(pos["y"]),
             float(pos["z"])])

        init_state.V = np.array(
            [float(pos["v_x"]),
             float(pos["v_y"]),
             float(pos["v_z"])])
    # ----------------------------------------------------------------------------------------

    # Coordinates given in ITRF Frame
    # ----------------------------------------------------------------------------------------
    elif init_coords["coord_frame"] == "ITRF":
        inertialFrame = FramesFactory.getEME2000()
        init_frame = FramesFactory.getITRF(
            IERS.IERS_2010, False)  # False -> don't ignore tidal effects
        p = Vector3D(
            float(1e3),  # convert to [m]
            Vector3D(float(pos["x"]), float(pos["y"]), float(pos["z"])))
        v = Vector3D(
            float(1e3),  # convert to [m/s]
            Vector3D(float(pos["v_x"]), float(pos["v_y"]), float(pos["v_z"])))

        ITRF2EME = init_frame.getTransformTo(inertialFrame,
                                             to_orekit_date(init_epoch))
        pv_EME = ITRF2EME.transformPVCoordinates(PVCoordinates(p, v))

        init_state.R = np.array([
            pv_EME.position.x, pv_EME.position.y, pv_EME.position.z
        ]) / 1e3  # convert to [km]
        init_state.V = np.array([
            pv_EME.velocity.x, pv_EME.velocity.y, pv_EME.velocity.z
        ]) / 1e3  # convert to [km/s]

    else:
        raise ValueError(
            "[" + ns_spacecraft + " ]: " +
            "Conversion from coordinate frame " + init_coords["coord_frame"] +
            " not implemented. Please provided coordinates in a different reference frame."
        )
    # ----------------------------------------------------------------------------------------

    return init_state
def when_is_iss_visible(longi, lat, station_name):
    """
    Returns some parameters of the ISS at its maximum elevation.

    Parameters
    ----------
    longi : float
        Longitude of the place where you stand on Earth.
    lat : float
        Latitude of the place where you stand on Earth.
    station_name : str
        Name of this place.

    Returns
    -------
    extrap_date : AbsoluteDate
        Date and time of the event.
    elevation : float
        Maximum elevation angle in radians.
    current_x : float
        X coordinate in the Topocentric Frame.
    current_y : TYPE
        Y coordinate in the Topocentric Frame.

    """
    iss_tle = get_iss_tle()
    itrf = FramesFactory.getITRF(IERSConventions.IERS_2010, True)
    earth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                             Constants.WGS84_EARTH_FLATTENING, itrf)
    station_frame = get_station(longi, lat, station_name, planet=earth)
    propagator = TLEPropagator.selectExtrapolator(iss_tle)

    current_x = 100001
    current_y = 100001
    current_ele = 0
    extrap_date = iss_tle.getDate()
    inertial_frame = FramesFactory.getEME2000()
    while not is_iss_visible(degrees(current_ele)):
        pv = propagator.getPVCoordinates(extrap_date, inertial_frame)
        pos_tmp = pv.getPosition()
        inertial2station_frame = inertial_frame.getTransformTo(station_frame, extrap_date)
        current_pos_station_frame = inertial2station_frame.transformPosition(pos_tmp)
        current_x = current_pos_station_frame.getX()
        current_y = current_pos_station_frame.getY()
        current_ele = station_frame.getElevation(current_pos_station_frame,
                                                 station_frame, extrap_date)
        extrap_date = extrap_date.shiftedBy(10.0)
    elevation = station_frame.getElevation(pos_tmp, inertial_frame,
                                           extrap_date)
    return extrap_date, elevation, current_x, current_y
Beispiel #12
0
    def test_moving_body_pointing_law(self):
        """
        moving_body_pointing_law test
        """
        parameters = {
            "eccentricity": 0.0008641,
            "semimajor_axis": 6801395.04,
            "inclination": 87.0,
            "perigee_argument": 20.0,
            "right_ascension_of_ascending_node": 10.0,
            "anomaly": radians(0.0),
            "anomaly_type": "TRUE",
            "orbit_update_date": '2021-12-02T00:00:00.000',
            "frame": "EME"
        }
        parameters1 = {
            "eccentricity": 0.0008641,
            "semimajor_axis": 6801395.04,
            "inclination": 87.0,
            "perigee_argument": 10.0,
            "right_ascension_of_ascending_node": 10.0,
            "anomaly": radians(0.0),
            "anomaly_type": "TRUE",
            "orbit_update_date": '2021-12-02T00:00:00.000',
            "frame": "EME"
        }

        orbit_propagator_1 = analytical_propagator(parameters1)
        orbit_propagator_2 = analytical_propagator(parameters1)
        parameters["frame"] = orekit_utils.frame_to_string(
            orbit_propagator_1.getFrame())

        time_to_propagate = orekit_utils.absolute_time_converter_utc_string(
            '2022-05-02T00:00:00.000')
        orbit_to_track_propagator = analytical_propagator(parameters)

        test1 = CelestialBodyPointed(FramesFactory.getEME2000(),
                                     orbit_to_track_propagator,
                                     Vector3D.PLUS_K, Vector3D.PLUS_K,
                                     Vector3D.MINUS_J)
        test2 = moving_body_pointing_law(orbit_to_track_propagator, parameters)

        orbit_propagator_1.setAttitudeProvider(test1)
        orbit_propagator_2.setAttitudeProvider(test2)
        state_1 = orbit_propagator_1.propagate(time_to_propagate)
        state_2 = orbit_propagator_2.propagate(time_to_propagate)
        self.assertTrue((state_1.getAttitude().getSpin().toString() ==
                         state_2.getAttitude().getSpin().toString()))
Beispiel #13
0
def string_to_frame(frame_name,
                    latitude=0.,
                    longitude=0.,
                    altitude=0.,
                    name=""):
    """
	Given a string with the following defined options below, the fucntion returns the orekit
	associated frame object.
	Args:
		frame_name: (string) with the following options...
					"ITRF" ... returns the ITRF (geocentric and rotates with earth for use
								for points near or on earth's surface--very accurate)
					"EME2000"/"J2000" ... Earth Centered Inertial (ECI) Frame
								  the frame is fixed to the celetial grid and doesn't rotate
								  with the earth
					"TEME" ... another ECI frame, but specifically used by NORAD TLEs
					"Topocentric" ... very specific frame defined at an coordinate on or near
									  the surface of an object (here we define earth). Rotates
									  with body defined by ITRF frame (can think as an offset
									  of ITRF frame for things like ground stations)
		latitude, longitude: (float in degrees) for defining the topocentric frame origin--not
							 required otherwise
		altitude: (float in meters) for defining the topocentric frame origin--not required otherwise
		name: (string) for defining the topocentric frame origin label--not required otherwise
	Returns:
		orekit frame object OR -1 if undefined string
	"""
    if (frame_name == utils.ITRF):
        return FramesFactory.getITRF(IERSConventions.IERS_2010, True)
    elif ((frame_name == utils.EME) or (frame_name == "J2000")):
        return FramesFactory.getEME2000()
    elif (frame_name == utils.TEME):
        return FramesFactory.getTEME()
    elif (frame_name == utils.TOPOCENTRIC):
        earth = OneAxisEllipsoid(
            Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
            Constants.WGS84_EARTH_FLATTENING,
            FramesFactory.getITRF(IERSConventions.IERS_2010, True))
        location = GeodeticPoint(radians(latitude), radians(longitude),
                                 float(altitude))
        return TopocentricFrame(earth, location, name)
    else:
        return -1
def when_is_iss_visible_bis(longi, lat, station_name):
    iss_tle = get_iss_tle()
    itrf = FramesFactory.getITRF(IERSConventions.IERS_2010, True)
    earth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                             Constants.WGS84_EARTH_FLATTENING, itrf)
    station_frame = get_station(longi, lat, earth, station_name)
    propagator = TLEPropagator.selectExtrapolator(iss_tle)
    ele_detector = ElevationDetector(60.0, 0.001, station_frame).withConstantElevation(radians(5.0)).withHandler(ContinueOnEvent())
    logger = EventsLogger()
    logged_detector = logger.monitorDetector(ele_detector)
    # propagator = Propagator.cast_(propagator)
    propagator.addEventDetector(logged_detector)
    initial_date = iss_tle.getDate()
    propagator.propagate(initial_date, initial_date.shiftedBy(3600.0*0.5)) ##20 days here
    date_ele_max = logger.getLoggedEvents().get(0).getState().getDate()
    pos_max_j2000 = logger.getLoggedEvents().get(0).getState().getPVCoordinates().getPosition()
    ele_max = station_frame.getElevation(pos_max_j2000,
                                         FramesFactory.getEME2000(), date_ele_max)
    return date_ele_max, ele_max
Beispiel #15
0
    def test_ground_pointing_law(self):
        """
        ground_pointing_law test
        """
        parameters = {"latitude": 12.0, "altitude": 2343.0, "longitude": 12.0}
        parameters1 = {
            "eccentricity": 0.0008641,
            "semimajor_axis": 6801395.04,
            "inclination": 87.0,
            "perigee_argument": 10.0,
            "right_ascension_of_ascending_node": 10.0,
            "anomaly": radians(0.0),
            "anomaly_type": "TRUE",
            "orbit_update_date": '2021-12-02T00:00:00.000',
            "frame": "EME"
        }

        orbit_propagator_1 = analytical_propagator(parameters1)
        orbit_propagator_2 = analytical_propagator(parameters1)
        parameters["frame"] = orekit_utils.frame_to_string(
            orbit_propagator_1.getFrame())

        ITRF = FramesFactory.getITRF(IERSConventions.IERS_2010, True)
        target = GeodeticPoint(parameters["latitude"], parameters["longitude"],
                               parameters["altitude"])
        attitude_provider = ground_pointing_law(parameters)
        attitude_provider_1 = TargetPointing(
            FramesFactory.getEME2000(), target,
            OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                             Constants.WGS84_EARTH_FLATTENING, ITRF))

        orbit_propagator_1.setAttitudeProvider(attitude_provider)
        orbit_propagator_2.setAttitudeProvider(attitude_provider_1)

        time_to_propagate = orekit_utils.absolute_time_converter_utc_string(
            '2022-05-02T00:00:00.000')
        state_1 = orbit_propagator_1.propagate(time_to_propagate)
        state_2 = orbit_propagator_2.propagate(time_to_propagate)

        self.assertTrue((state_1.getAttitude().getSpin().toString() ==
                         state_2.getAttitude().getSpin().toString()))
    def change_initial_conditions(self, initial_state, date, mass):
        """
            Allows to change the initial conditions given to the propagator without initializing it again.

        Args:
            initial_state (Cartesian): New initial state of the satellite in cartesian coordinates.
            date (datetime): New starting date of the propagator.
            mass (float64): New satellite mass.
        """
        # Redefine the start date
        self.date = date

        # Create position and velocity vectors as Vector3D
        p = Vector3D(
            float(initial_state.R[0]) * 1e3,
            float(initial_state.R[1]) * 1e3,
            float(initial_state.R[2]) * 1e3)
        v = Vector3D(
            float(initial_state.V[0]) * 1e3,
            float(initial_state.V[1]) * 1e3,
            float(initial_state.V[2]) * 1e3)

        # Initialize orekit date
        seconds = float(date.second) + float(date.microsecond) / 1e6
        orekit_date = AbsoluteDate(date.year, date.month, date.day, date.hour,
                                   date.minute, seconds,
                                   TimeScalesFactory.getUTC())

        # Extract frame
        inertialFrame = FramesFactory.getEME2000()

        # Evaluate new initial orbit
        initialOrbit = CartesianOrbit(PVCoordinates(p, v), inertialFrame,
                                      orekit_date, Cst.WGS84_EARTH_MU)

        # Create new spacecraft state
        newSpacecraftState = SpacecraftState(initialOrbit, mass)

        # Rewrite propagator initial conditions
        self.orekit_prop._propagator_num.setInitialState(newSpacecraftState)
Beispiel #17
0
    def get_sun_pos_sundial_frame(self, utc_date):
        """
        Returns the position of the Sun in the sundial frame.

        Parameters
        ----------
        utc_date : Absolute Date
            Date when the position of the Sun should be computed.

        Returns
        -------
        sun_pos_sundial_frame : Vector3D
            Position vector of the Sun in the sundial frame.

        """
        j2000 = FramesFactory.getEME2000()
        sun_pos_j2000 = self.pv_sun.getPVCoordinates(utc_date,
                                                     j2000).getPosition()
        j2000_to_sundial = j2000.getTransformTo(self.sundial_frame, utc_date)
        sun_pos_sundial_frame = j2000_to_sundial.transformPosition(
            sun_pos_j2000)
        return sun_pos_sundial_frame
def is_day_utc(utc_date, station_frame):
    """
    Check if it's day or not at a given date (in UTC time) at a given place on Earth'

    Parameters
    ----------
    utc_date : AbsoluteDate
        date and time in the UTC.
    station_frame : Topocentric Frame
        Frame of the place on Earth.

    Returns
    -------
    bool
        True if it is day, False otherwise.

    """
    j2000 = FramesFactory.getEME2000()
    pv_sun = CelestialBodyFactory.getSun()
    pv_sun = PVCoordinatesProvider.cast_(pv_sun)
    sun_pos_j2000 = pv_sun.getPVCoordinates(utc_date, j2000).getPosition()
    j2000_to_topocentric = j2000.getTransformTo(station_frame, utc_date)
    sun_pos_topo = j2000_to_topocentric.transformPosition(sun_pos_j2000)
    return sun_pos_topo.getZ() > 0
Beispiel #19
0
def main():

    a = 24396159.0  # semi major axis (m)
    e = 0.720  # eccentricity
    i = radians(10.0)  # inclination
    omega = radians(50.0)  # perigee argument
    raan = radians(150)  # right ascension of ascending node
    lM = 0.0  # mean anomaly

    # Set inertial frame
    inertialFrame = FramesFactory.getEME2000()

    # Initial date in UTC time scale
    utc = TimeScalesFactory.getUTC()
    initial_date = AbsoluteDate(2004, 1, 1, 23, 30, 00.000, utc)

    # Setup orbit propagator
    # gravitation coefficient
    mu = 3.986004415e+14

    # Orbit construction as Keplerian
    initialOrbit = KeplerianOrbit(a, e, i, omega, raan, lM, PositionAngle.MEAN,
                                  inertialFrame, initial_date, mu)

    initial_state = SpacecraftState(initialOrbit)

    # use a numerical propogator
    min_step = 0.001
    max_step = 1000.0
    position_tolerance = 10.0

    propagation_type = OrbitType.KEPLERIAN
    tolerances = NumericalPropagator.tolerances(position_tolerance,
                                                initialOrbit, propagation_type)

    integrator = DormandPrince853Integrator(min_step, max_step, 1e-5, 1e-10)

    propagator = NumericalPropagator(integrator)
    propagator.setOrbitType(propagation_type)

    # force model gravity field
    provider = GravityFieldFactory.getNormalizedProvider(10, 10)
    holmesFeatherstone = HolmesFeatherstoneAttractionModel(
        FramesFactory.getITRF(IERSConventions.IERS_2010, True), provider)

    # SRP
    # ssc = IsotropicRadiationSingleCoefficient(100.0, 0.8)  # Spacecraft surface area (m^2), C_r absorbtion
    # srp = SolarRadiationPressure(CelestialBodyFactory.getSun(), a, ssc)  # sun, semi-major Earth, spacecraft sensitivity

    propagator.addForceModel(holmesFeatherstone)
    # propagator.addForceModel(ThirdBodyAttraction(CelestialBodyFactory.getSun()))
    # propagator.addForceModel(ThirdBodyAttraction(CelestialBodyFactory.getMoon()))
    # propagator.addForceModel(srp)

    propagator.setMasterMode(60.0, TutorialStepHandler())

    propagator.setInitialState(initial_state)

    # propagator.setEphemerisMode()

    finalstate = propagator.propagate(initial_date.shiftedBy(
        10. * 24 * 60**2))  # TIme shift in seconds
Beispiel #20
0
    def propagate(self, t, state0, epoch, **kwargs):
        '''
        **Implementation:**
    
        Units are in meters and degrees.

        Keyword arguments are:

            * float A: Area in m^2
            * float C_D: Drag coefficient
            * float C_R: Radiation pressure coefficient
            * float m: Mass of object in kg

        *NOTE:*
            * If the eccentricity is below 1e-10 the eccentricity will be set to 1e-10 to prevent Keplerian Jacobian becoming singular.
        

        The implementation first checks if the input frame is Pseudo inertial, if this is true this is used as the propagation frame. If not it is automatically converted to EME (ECI-J2000).

        Since there are forces that are dependent on the space-craft parameters, if these parameter has been changed since the last iteration the numerical integrator is re-initialized at every call of this method. The forces that can be initialized without spacecraft parameters (e.g. Earth gravitational field) are done at propagator construction.

        See :func:`propagator_base.PropagatorBase.get_orbit`.
        '''
        if self.profiler is not None:
            self.profiler.start('Orekit:propagate')

        if self.settings['in_frame'].startswith('Orekit-'):
            self.inputFrame = self._get_frame(
                self.settings['in_frame'].replace('Orekit-', ''))
            orekit_in_frame = True
        else:
            self.inputFrame = self._get_frame('GCRF')
            orekit_in_frame = False

        if self.settings['out_frame'].startswith('Orekit-'):
            self.outputFrame = self._get_frame(
                self.settings['out_frame'].replace('Orekit-', ''))
            orekit_out_frame = True
        else:
            self.outputFrame = self._get_frame('GCRF')
            orekit_out_frame = False

        if self.inputFrame.isPseudoInertial():
            self.inertialFrame = self.inputFrame
        else:
            self.inertialFrame = FramesFactory.getEME2000()

        self.body = OneAxisEllipsoid(self.R_earth, self.f_earth,
                                     self.outputFrame)

        if isinstance(state0, pyorb.Orbit):
            state0_cart = np.squeeze(state0.cartesian)
        else:
            state0_cart = state0

        if self.settings['radiation_pressure']:
            if 'C_R' not in kwargs:
                raise Exception(
                    'Radiation pressure force enabled but no coefficient "C_R" given'
                )
        else:
            kwargs['C_R'] = 1.0

        if self.settings['drag_force']:
            if 'C_D' not in kwargs:
                raise Exception(
                    'Drag force enabled but no drag coefficient "C_D" given')
        else:
            kwargs['C_D'] = 1.0

        if 'm' not in kwargs:
            kwargs['m'] = 0.0

        t, epoch = self.convert_time(t, epoch)
        times = epoch + t

        mjd0 = epoch.mjd
        t = t.value
        if not isinstance(t, np.ndarray):
            t = np.array([t])

        if self.logger is not None:
            self.logger.debug(f'Orekit:propagate:len(t) = {len(t)}')

        if not orekit_in_frame:
            state0_cart = frames.convert(
                epoch,
                state0_cart,
                in_frame=self.settings['in_frame'],
                out_frame='GCRS',
                profiler=self.profiler,
                logger=self.logger,
            )

        initialDate = mjd2absdate(mjd0, self.utc)

        pos = org.hipparchus.geometry.euclidean.threed.Vector3D(
            float(state0_cart[0]), float(state0_cart[1]),
            float(state0_cart[2]))
        vel = org.hipparchus.geometry.euclidean.threed.Vector3D(
            float(state0_cart[3]), float(state0_cart[4]),
            float(state0_cart[5]))
        PV_state = PVCoordinates(pos, vel)

        if not self.inputFrame.isPseudoInertial():
            transform = self.inputFrame.getTransformTo(self.inertialFrame,
                                                       initialDate)
            PV_state = transform.transformPVCoordinates(PV_state)

        initialOrbit = CartesianOrbit(
            PV_state,
            self.inertialFrame,
            initialDate,
            self.mu + float(scipy.constants.G * kwargs['m']),
        )

        self._construct_propagator(initialOrbit)
        self._set_forces(kwargs['A'], kwargs['C_D'], kwargs['C_R'])

        initialState = SpacecraftState(initialOrbit)

        self.propagator.setInitialState(initialState)

        tb_inds = t < 0.0
        t_back = t[tb_inds]

        tf_indst = t >= 0.0
        t_forward = t[tf_indst]

        if len(t_forward) == 1:
            if np.any(t_forward == 0.0):
                t_back = t
                t_forward = []
                tb_inds = t <= 0

        state = np.empty((6, len(t)), dtype=np.float)
        step_handler = Orekit.OrekitVariableStep()

        if self.profiler is not None:
            self.profiler.start('Orekit:propagate:steps')

        if self.settings['heartbeat']:
            __heartbeat = self.heartbeat
        else:
            __heartbeat = None

        if len(t_back) > 0:
            _t = t_back
            _t_order = np.argsort(np.abs(_t))
            _t_res = np.argsort(_t_order)
            _t = _t[_t_order]
            _state = np.empty((6, len(_t)), dtype=np.float)

            step_handler.set_params(_t,
                                    initialDate,
                                    _state,
                                    self.outputFrame,
                                    __heartbeat,
                                    profiler=self.profiler)

            self.propagator.setMasterMode(step_handler)

            self.propagator.propagate(initialDate.shiftedBy(float(_t[-1])))

            #now _state is full and in the order of _t
            state[:, tb_inds] = _state[:, _t_res]

        if len(t_forward) > 0:
            _t = t_forward
            _t_order = np.argsort(np.abs(_t))
            _t_res = np.argsort(_t_order)
            _t = _t[_t_order]
            _state = np.empty((6, len(_t)), dtype=np.float)
            step_handler.set_params(_t,
                                    initialDate,
                                    _state,
                                    self.outputFrame,
                                    __heartbeat,
                                    profiler=self.profiler)

            self.propagator.setMasterMode(step_handler)

            self.propagator.propagate(initialDate.shiftedBy(float(_t[-1])))

            #now _state is full and in the order of _t
            state[:, tf_indst] = _state[:, _t_res]

        if not orekit_out_frame:
            state = frames.convert(
                times,
                state,
                in_frame='GCRS',
                out_frame=self.settings['out_frame'],
                profiler=self.profiler,
                logger=self.logger,
            )

        if self.profiler is not None:
            self.profiler.stop('Orekit:propagate:steps')
            self.profiler.stop('Orekit:propagate')

        if self.logger is not None:
            self.logger.debug(f'Orekit:propagate:completed')

        return state
Beispiel #21
0
setup_orekit_curdir()
if os.path.exists('orekit-data.zip')==False:
  orekit.pyhelpers.download_orekit_data_curdir()

from org.orekit.utils import Constants
from org.orekit.time import TimeScalesFactory, AbsoluteDate
from org.orekit.utils import PVCoordinates, AbsolutePVCoordinates, TimeStampedPVCoordinates, IERSConventions
from org.orekit.frames import FramesFactory
from org.hipparchus.geometry.euclidean.threed import Vector3D
from org.orekit.orbits import CartesianOrbit, KeplerianOrbit, PositionAngle, OrbitType, Orbit, CircularOrbit

teme_f = FramesFactory.getTEME()
utc = TimeScalesFactory.getUTC()
itrf_f = FramesFactory.getITRF(IERSConventions.IERS_2010, True)
gcrf_f = FramesFactory.getGCRF()
eme2000_f = FramesFactory.getEME2000()
muearth = Constants.WGS84_EARTH_MU


#Code


__all__ = [
    'itrf_latlon',
    'convert_frame_cart_orekit',
    'gcrf_itrf_astropy',
    'itrf_gcrf_astropy',
    'xyz_to_rsw',
    'xyz_to_ntw',
    'ntw_frame',
    'rsw_frame',
Beispiel #22
0
from org.orekit.propagation.analytical.tle import TLE, TLEPropagator
from org.orekit.frames import FramesFactory
from org.orekit.bodies import OneAxisEllipsoid
from org.orekit.utils import IERSConventions, Constants
from org.orekit.orbits import KeplerianOrbit
from org.orekit.forces.maneuvers import SmallManeuverAnalyticalModel
from org.orekit.propagation.events import DateDetector
from org.orekit.attitudes import LofOffset
from org.orekit.frames import LOFType
from org.hipparchus.geometry.euclidean.threed import Vector3D
from org.orekit.propagation.analytical import AdapterPropagator

print("Initializing Orekit")
orekit.initVM()
setup_orekit_curdir()
INERTIAL_FRAME = FramesFactory.getEME2000()


def propagate(tle_line1, tle_line2, duration, step, maneuvers=[]):
    tle = create_tle(tle_line1, tle_line2)
    tle_propagator = TLEPropagator.selectExtrapolator(tle)
    propagator_with_maneuvers = AdapterPropagator(tle_propagator)

    # TODO works only for chronological maneuvers, because of the "propagate" to get the state
    for maneuver in maneuvers:
        date, frame, deltaV, isp = maneuver
        propagator_with_maneuvers.addEffect(
            SmallManeuverAnalyticalModel(
                propagator_with_maneuvers.propagate(
                    datetime_to_absolutedate(date)), frame, deltaV, isp))
from org.orekit.estimation.measurements import ObservableSatellite

# CSV
import csv



##############################################################################
##############################################################################
# Create the accessory objects and handle the observations
##############################################################################
##############################################################################

# Create the GCRF (ECI) and ITRF (ECEF) Frames
GCRF_Frame = FramesFactory.getGCRF()
J2000_Frame = FramesFactory.getEME2000()
ITRF_Frame = FramesFactory.getITRF(IERSConventions.IERS_2010, True)
earth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                                       Constants.WGS84_EARTH_FLATTENING,
                                       ITRF_Frame)


# CREATE THE GROUND STATION
# First create the Topocentric Frame
station_coord = GeodeticPoint(radians(40), radians(-110), 2000.0)
station_frame = TopocentricFrame(earth, station_coord, 'MyGndStation')

# Now create the Ground station itself and the satellite object
GndStation = GroundStation(station_frame)
Sat = ObservableSatellite(1) # create the observable satellite object, name it 1 as default
Beispiel #24
0
    def __init__(
        self,
        in_frame='EME',
        out_frame='ITRF',
        frame_tidal_effects=False,
        integrator='DormandPrince853',
        min_step=0.001,
        max_step=120.0,
        position_tolerance=10.0,
        earth_gravity='HolmesFeatherstone',
        gravity_order=(10, 10),
        solarsystem_perturbers=['Moon', 'Sun'],
        drag_force=True,
        atmosphere='DTM2000',
        radiation_pressure=True,
        solar_activity='Marshall',
        constants_source='WGS84',
        solar_activity_strength='WEAK',
        logger_func=None,
    ):
        super(PropagatorOrekit, self).__init__()

        self.logger_func = logger_func
        self.__log = {}
        self.__log_tmp = {}
        if self.logger_func is not None:
            self._logger_start('__init__')

        self.solarsystem_perturbers = solarsystem_perturbers
        self.in_frame = in_frame
        self.frame_tidal_effects = frame_tidal_effects
        self.out_frame = out_frame
        self.drag_force = drag_force
        self.gravity_order = gravity_order
        self.atmosphere = atmosphere
        self.radiation_pressure = radiation_pressure
        self.solar_activity = solar_activity
        self.SolarStrengthLevel = getattr(
            org.orekit.forces.drag.atmosphere.data.
            MarshallSolarActivityFutureEstimation.StrengthLevel,
            solar_activity_strength)
        self.integrator = integrator
        self.minStep = min_step
        self.maxStep = max_step
        self.position_tolerance = position_tolerance
        self._tolerances = None

        self.constants_source = constants_source
        if constants_source == 'JPL-IAU':
            self.mu = Constants.JPL_SSD_EARTH_GM
            self.R_earth = Constants.IAU_2015_NOMINAL_EARTH_EQUATORIAL_RADIUS
            self.f_earth = (Constants.IAU_2015_NOMINAL_EARTH_EQUATORIAL_RADIUS
                            - Constants.IAU_2015_NOMINAL_EARTH_POLAR_RADIUS
                            ) / Constants.IAU_2015_NOMINAL_EARTH_POLAR_RADIUS
        else:
            self.mu = Constants.WGS84_EARTH_MU
            self.R_earth = Constants.WGS84_EARTH_EQUATORIAL_RADIUS
            self.f_earth = Constants.WGS84_EARTH_FLATTENING

        self.M_earth = self.mu / scipy.constants.G

        self.earth_gravity = earth_gravity

        self.__params = None

        self.inputFrame = self._get_frame(self.in_frame)
        self.outputFrame = self._get_frame(self.out_frame)

        if self.inputFrame.isPseudoInertial():
            self.inertialFrame = self.inputFrame
        else:
            self.inertialFrame = FramesFactory.getEME2000()

        self.body = OneAxisEllipsoid(self.R_earth, self.f_earth,
                                     self.outputFrame)

        self._forces = {}

        if self.radiation_pressure:
            self._forces['radiation_pressure'] = None
        if self.drag_force:
            self._forces['drag_force'] = None

        if self.earth_gravity == 'HolmesFeatherstone':
            provider = org.orekit.forces.gravity.potential.GravityFieldFactory.getNormalizedProvider(
                self.gravity_order[0], self.gravity_order[1])
            holmesFeatherstone = org.orekit.forces.gravity.HolmesFeatherstoneAttractionModel(
                FramesFactory.getITRF(IERSConventions.IERS_2010, True),
                provider,
            )
            self._forces['earth_gravity'] = holmesFeatherstone

        elif self.earth_gravity == 'Newtonian':
            Newtonian = org.orekit.forces.gravity.NewtonianAttraction(self.mu)
            self._forces['earth_gravity'] = Newtonian

        else:
            raise Exception(
                'Supplied Earth gravity model "{}" not recognized'.format(
                    self.earth_gravity))

        if self.solarsystem_perturbers is not None:
            for body in self.solarsystem_perturbers:
                body_template = getattr(CelestialBodyFactory,
                                        'get{}'.format(body))
                body_instance = body_template()
                perturbation = org.orekit.forces.gravity.ThirdBodyAttraction(
                    body_instance)

                self._forces['perturbation_{}'.format(body)] = perturbation
        if self.logger_func is not None:
            self._logger_record('__init__')
Beispiel #25
0

class Propagator:
    def __init__(self, initial_orbit, initial_date, shifted_date):
        self.shifted_date = shifted_date
        self.initial_orbit = initial_orbit
        self.initial_date = initial_date

    def __str__(self):
        return str(self.__dict__)

    def propagate_keplerian_elements(self):
        propagator = KeplerianPropagator(self.initial_orbit)
        return propagator.propagate(self.initial_date, self.shifted_date)


if __name__ == "__main__":
    instance = KeplerianElements(
        24464560.0, 0.7311, 0.122138, 3.10686, 1.00681, 0.048363,
        PositionAngle.MEAN, FramesFactory.getEME2000(),
        AbsoluteDate(2020, 1, 1, 0, 0, 00.000,
                     TimeScalesFactory.getUTC()), Constants.GRS80_EARTH_MU)
    k = instance.init_keplerian_elements()
    init_date = AbsoluteDate(2020, 1, 1, 0, 0, 00.000,
                             TimeScalesFactory.getUTC())
    shift = init_date.shiftedBy(3600.0 * 48)
    kp = Propagator(k, init_date, shift)
    kp.propagate_keplerian_elements()
    print(k)
    print(kp)
Beispiel #26
0
    def osc_elems_transformation_ore(self, other, dir):

        self._orekit_lock.acquire()

        self.load_orekit()

        KepOrbElem.vm.attachCurrentThread()

        utc = TimeScalesFactory.getUTC()

        orekit_date = AbsoluteDate(2017, 1, 1, 12, 1, 1.0, utc)
        inertialFrame = FramesFactory.getEME2000()
        a = float(other.a)
        e = float(other.e)
        i = float(other.i)
        w = float(other.w)
        O = float(other.O)
        v = float(other.v)

        initialOrbit = KeplerianOrbit(a * 1000.0, e, i, w, O, v,
                                      PositionAngle.TRUE, inertialFrame,
                                      orekit_date, Constants.mu_earth * 1e9)

        initialState = SpacecraftState(initialOrbit, 1.0)

        #zonal_forces= DSSTZonal(provider,2,1,5)
        zonal_forces = DSSTZonal(KepOrbElem.provider, 6, 4, 6)
        forces = ArrayList()
        forces.add(zonal_forces)
        try:
            equinoctial = None
            if dir:

                equinoctial = DSSTPropagator.computeMeanState(
                    initialState, None, forces)
            else:

                equinoctial = DSSTPropagator.computeOsculatingState(
                    initialState, None, forces)

            newOrbit = KeplerianOrbit(equinoctial.getOrbit())

            self.a = newOrbit.getA() / 1000.0
            self.e = newOrbit.getE()
            self.i = newOrbit.getI()
            self.w = newOrbit.getPerigeeArgument()
            self.O = newOrbit.getRightAscensionOfAscendingNode()
            self.v = newOrbit.getAnomaly(PositionAngle.TRUE)

            # correct ranges

            if self.i < 0:
                self.i += 2 * np.pi

            if self.w < 0:
                self.w += 2 * np.pi

            if self.O < 0:
                self.O += 2 * np.pi

            if self.v < 0:
                self.v += 2 * np.pi

        finally:
            self._orekit_lock.release()
Beispiel #27
0
# The COE for the orbit to be defined
a, ecc, inc, raan, argp, nu = (6828137.0, 0.0073, 87.0, 20.0, 10.0, 0)

# Define the orkeit and poliastro orbits to be used for all the event validation
# cases in this script
epoch0_orekit = AbsoluteDate(2020, 1, 1, 0, 0, 00.000,
                             TimeScalesFactory.getUTC())
ss0_orekit = KeplerianOrbit(
    float(a),
    float(ecc),
    float(inc * DEG_TO_RAD),
    float(argp * DEG_TO_RAD),
    float(raan * DEG_TO_RAD),
    float(nu * DEG_TO_RAD),
    PositionAngle.TRUE,
    FramesFactory.getEME2000(),
    epoch0_orekit,
    Constants.WGS84_EARTH_MU,
)
epoch0_poliastro = Time("2020-01-01", scale="utc")
ss0_poliastro = Orbit.from_classical(
    Earth,
    a * u.m,
    ecc * u.one,
    inc * u.deg,
    raan * u.deg,
    argp * u.deg,
    nu * u.deg,
    epoch0_poliastro,
)
Beispiel #28
0
setup_orekit_curdir()

# To activate once if a problem of orekit.Exception appears. (.getUtc())
# orekit.pyhelpers.download_orekit_data_curdir()

utc = TimeScalesFactory.getUTC()

ra = 400 * 1000  #  Apogee
rp = 500 * 1000  #  Perigee
i = numpy.radians(87.0)  # inclination
# FIXME: Use Hipparchus Library instead of numpy
omega = numpy.radians(20.0)  # perigee argument
raan = numpy.radians(10.0)  # right ascension of ascending node
lv = numpy.radians(0.0)  # True anomaly

epochDate = AbsoluteDate(2020, 1, 1, 0, 0, 00.000, utc)

a = (rp + ra + 2 * Constants.WGS84_EARTH_EQUATORIAL_RADIUS) / 2.0
e = 1.0 - (rp + Constants.WGS84_EARTH_EQUATORIAL_RADIUS) / a

# Inertial frame where the satellite is defined
inertialFrame = FramesFactory.getEME2000()

# Orbit construction as Keplerian
initialOrbit = KeplerianOrbit(24464560.0, 0.7311, 0.122138, 3.10686, 1.00681,
                              0.048363, PositionAngle.MEAN,
                              FramesFactory.getEME2000(), epochDate,
                              Constants.GRS80_EARTH_MU)

print(initialOrbit)