Esempio n. 1
0
def orekit_test_data(body,
                     filename,
                     satellite,
                     stations,
                     range_sigma=20.0,
                     range_rate_sigma=0.001,
                     range_base_weight=1.0,
                     range_rate_base_weight=1.0,
                     az_sigma=0.02,
                     el_sigma=0.02):
    """Load test data from W3B.aer"""
    azels = []
    ranges = []
    rates = []

    f = open(filename, 'r')
    for line in f:
        if line[0] == '#':
            continue
        elif len(line) < 25:
            continue

        fields = line.split()
        date_components = DateTimeComponents.parseDateTime(fields[0])
        date = AbsoluteDate(date_components, TimeScalesFactory.getUTC())

        if fields[1] == 'ONEWAY':
            two_way = False
            fields.pop(1)
        elif fields[1] == 'TWOWAY':
            two_way = True
            fields.pop(1)
        else:
            two_way = True

        mode = fields[1]
        station_name = fields[2]
        station = stations[station_name]

        if mode == 'RANGE':
            rho = float(fields[3])
            range_obj = Range(station, True, date, rho, range_sigma,
                              range_base_weight, satellite)
            ranges.append(range_obj)
        elif mode == 'AZ_EL':
            az = float(fields[3]) * math.pi / 180.0
            el = float(fields[4]) * math.pi / 180.0
            azel_obj = AngularAzEl(station, date, [az, el],
                                   [az_sigma, el_sigma],
                                   [az_base_weight, el_base_weight], satellite)
            azels.append(azel_obj)
        elif mode in ('RATE', 'RRATE'):
            rate_obj = RangeRate(station, date, float(fields[3]),
                                 range_rate_sigma, range_rate_base_weight,
                                 two_way, satellite)
            rates.append(rate_obj)
        else:
            raise SyntaxError("unrecognized mode '{}'".format(mode))

    return stations, ranges, rates, azels
Esempio n. 2
0
    def test_visible_above_horizon(self):
        """
        visible_above_horizon test
        """
        #equitorial orbit
        tle_line1 = "1 44235U 19029A   20178.66667824  .02170155  00000-0  40488-1 0  9998"
        tle_line2 = "2 44235  00.0000 163.9509 0005249 306.3756  83.0170 15.45172567 61683"
        #high inclination orbit
        tle2_line1 = "1 44235U 19029A   20178.66667824  .02170155  00000-0  40488-1 0  9998"
        tle2_line2 = "2 44235  70.0000 163.9509 0005249 306.3756  83.0170 15.45172567 61683"
        prop1 = orekit_utils.str_tle_propagator(tle_line1, tle_line2)
        prop2 = orekit_utils.str_tle_propagator(tle2_line1, tle2_line2)
        time = AbsoluteDate(2020, 6, 26, 1, 40, 00.000,
                            TimeScalesFactory.getUTC())

        #verified with graphing overviews
        self.assertFalse(orekit_utils.visible_above_horizon(
            prop1, prop2, time))
        self.assertTrue(
            orekit_utils.visible_above_horizon(prop1, prop2,
                                               time.shiftedBy(60. * 10.)))
        self.assertTrue(
            orekit_utils.visible_above_horizon(
                prop1, prop2, time.shiftedBy(60. * 10. + 45. * 60.)))
        time_period_visible = orekit_utils.visible_above_horizon(
            prop1, prop2, time, 60 * 30)[0]
        self.assertTrue(
            time.shiftedBy(60. * 10.).isBetween(time_period_visible[0],
                                                time_period_visible[1]))
Esempio n. 3
0
def absolute_time_converter_utc_string(time_string):
    """
	turn time_string into orekit absolute time object
	Inputs: time scales in UTC
	Output: absolute time object from orekit
	"""
    return AbsoluteDate(time_string, TimeScalesFactory.getUTC())
Esempio n. 4
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
Esempio n. 5
0
 def test_field_of_view_detector(self):
     """
     field_of_view_detector tests
     """
     tle = TLE(
         "1 44235U 19029A   20178.66667824  .02170155  00000-0  40488-1 0  9998",
         "2 44235  00.0000 163.9509 0005249 306.3756  83.0170 15.45172567 61683"
     )
     parameters = {"frame": "TEME"}
     attitudeProvider = orekit_utils.nadir_pointing_law(parameters)
     propogator_fov = TLEPropagator.selectExtrapolator(
         tle, attitudeProvider, 4.)
     startDate = AbsoluteDate(2020, 6, 26, 1, 40, 00.000,
                              TimeScalesFactory.getUTC())
     #should have one passes
     self.assertTrue(
         len(
             orekit_utils.field_of_view_detector(propogator_fov, 0, 0, 0,
                                                 startDate, 20, 5400)) == 1)
     #should have zero passes
     self.assertTrue(
         len(
             orekit_utils.field_of_view_detector(propogator_fov, 0, 0, 0,
                                                 startDate, 20, 100)) == 0)
     #test exact time input
     self.assertFalse(
         orekit_utils.field_of_view_detector(propogator_fov, 0, 0, 0,
                                             startDate, 20))
Esempio n. 6
0
File: frame.py Progetto: rev0nat/SMS
def itrs_gcrs_single(itrs):
  """ Transformation ITRS to GCRS.
  """

  utc = TimeScalesFactory.getUTC()
  date = itrs.index[0]
  X = float(itrs['x[m]'][0])
  Y = float(itrs['y[m]'][0])
  Z = float(itrs['z[m]'][0])
  Vx = float(itrs['vx[m/s]'][0])
  Vy = float(itrs['vy[m/s]'][0])
  Vz = float(itrs['vz[m/s]'][0])
  ok_date = AbsoluteDate(date.year, date.month, date.day, date.hour, date.minute,
                         date.second + float(date.microsecond) / 1000000., utc)
  PV_coordinates = PVCoordinates(Vector3D(X, Y, Z), Vector3D(Vx, Vy, Vz))
  start_state = TimeStampedPVCoordinates(ok_date, PV_coordinates)
  state_itrf = AbsolutePVCoordinates(itrf, start_state)
  state_gcrf = AbsolutePVCoordinates(gcrf, state_itrf.getPVCoordinates(gcrf))
  pos = state_gcrf.position
  vel = state_gcrf.velocity
  X = pos.getX()
  Y = pos.getY()
  Z = pos.getZ()
  Vx = vel.getX()
  Vy = vel.getY()
  Vz = vel.getZ()
  dframe = pd.DataFrame({'x[m]': [X], 'y[m]': [Y], 'z[m]': [Z], 'vx[m/s]': [Vx], 'vy[m/s]': [Vy], 'vz[m/s]': [Vz]}, index=itrs.index)

  return dframe
Esempio n. 7
0
    def __init__(self, name, model_file=None):

        self.name = name

        self.timescale = TimeScalesFactory.getTDB()
        self.ref_frame = FramesFactory.getICRF()

        self.trj_date = None
        self.trajectory = None
        self.propagator = None

        self.event_handler = TimingEvent().of_(TimeSampler)
        self.time_sampler = None

        self.model_file = model_file
        self.render_obj = None

        self.pos = None
        self.vel = None

        self.date_history = self.event_handler.date_history
        self.pos_history = self.event_handler.pos_history
        self.vel_history = self.event_handler.vel_history
        self.rot_history = self.event_handler.rot_history

        logger.debug("Init finished")
Esempio n. 8
0
 def test_check_iot_in_range(self):
     """
     check_iot_in_range test
     """
     tle_line1 = "1 44235U 19029A   20178.66667824  .02170155  00000-0  40488-1 0  9998"
     tle_line2 = "2 44235  00.0000 163.9509 0005249 306.3756  270.0170 15.45172567 61683"
     prop1 = orekit_utils.str_tle_propagator(tle_line1, tle_line2)
     lat = 0.
     lon = 0.
     alt = 10.
     time = AbsoluteDate(2020, 6, 26, 1, 40, 00.000, TimeScalesFactory.getUTC())
     self.assertTrue(check_iot_in_range(prop1, lat, lon, alt, time))
     self.assertFalse(check_iot_in_range(prop1, lat, lon, alt, time.shiftedBy(60.*30.)))
Esempio n. 9
0
def absolute_time_converter_utc_manual(year,
                                       month,
                                       day,
                                       hour=0,
                                       minute=0,
                                       second=0.0):
    """
	turn time into orekit absolute time object
	Inputs: time scales in UTC
	Output: absolute time object from orekit
	"""
    return AbsoluteDate(int(year), int(month), int(day), int(hour),
                        int(minute), float(second), TimeScalesFactory.getUTC())
Esempio n. 10
0
def to_orekit_date(epoch):
    """Convert UTC simulation time from python's datetime object to Orekit's AbsoluteDate object.

    Args:
        epoch (datetime.datetime): UTC simulation time

    Returns:
        AbsoluteDate: simulation time in UTC

    """
    seconds = float(epoch.second) + float(epoch.microsecond) / 1e6
    orekit_date = AbsoluteDate(epoch.year,
                               epoch.month,
                               epoch.day,
                               epoch.hour,
                               epoch.minute,
                               seconds,
                               TimeScalesFactory.getUTC())

    return orekit_date
Esempio n. 11
0
    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)
Esempio n. 12
0
    def get_sun_max_elevation(self, year, month, day):
        """
        Returns the maximum elevation angle (in radians) of the Sun (that is the zenith) a given day.

        Parameters
        ----------
        year : int
            Year.
        month : int
            Month.
        day : int
            Day.

        Returns
        -------
        current_ele0 : TYPE
            DESCRIPTION.
        currentutc_date : TYPE
            DESCRIPTION.

        """
        currentutc_date = AbsoluteDate(year, month, day, 0, 0, 0.0,
                                       TimeScalesFactory.getUTC())
        is_max_elevation = False
        time_step = 10.0
        current_ele0 = self.get_sun_elevation(currentutc_date)
        current_ele1 = self.get_sun_elevation(
            currentutc_date.shiftedBy(time_step))
        if current_ele0 > current_ele1:
            is_max_elevation = True
        while not is_max_elevation:
            current_ele0 = current_ele1
            current_ele1 = self.get_sun_elevation(
                currentutc_date.shiftedBy(time_step))
            if current_ele0 > current_ele1:
                is_max_elevation = True
                currentutc_date.shiftedBy(-time_step)
            currentutc_date = currentutc_date.shiftedBy(time_step)
        return current_ele0, currentutc_date
Esempio n. 13
0
def validate_event_detector(event_name):

    # Unpack orekit and poliastro events
    orekit_event, poliastro_event = DICT_OF_EVENTS[event_name]

    # Time of fliht for propagating the orbit
    tof = float(2 * 24 * 3600)

    # Build the orekit propagator and add the event to it.
    propagator = KeplerianPropagator(ss0_orekit)
    propagator.addEventDetector(orekit_event)

    # Propagate orekit's orbit
    state = propagator.propagate(epoch0_orekit, epoch0_orekit.shiftedBy(tof))
    orekit_event_epoch_raw = state.orbit.getPVCoordinates().getDate()
    # Convert orekit epoch to astropy Time instance
    orekit_event_epoch_str = orekit_event_epoch_raw.toString(
        TimeScalesFactory.getUTC())
    orekit_event_epoch = Time(orekit_event_epoch_str,
                              scale="utc",
                              format="isot")
    orekit_event_epoch.format = "iso"
    print(f"{orekit_event_epoch}")

    # Propagate poliastro's orbit
    _, _ = cowell(
        Earth.k,
        ss0_poliastro.r,
        ss0_poliastro.v,
        # Generate a set of tofs, each one for each propagation second
        np.linspace(0, tof, 100) * u.s,
        events=[poliastro_event],
    )
    poliastro_event_epoch = ss0_poliastro.epoch + poliastro_event.last_t
    print(f"{poliastro_event_epoch}")

    # Test both event epochs by checking the distance in seconds between them
    dt = np.abs((orekit_event_epoch - poliastro_event_epoch).to(u.s))
    assert_quantity_allclose(dt, 0 * u.s, atol=5 * u.s, rtol=1e-7)
Esempio n. 14
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()
                                       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

# SET THE DAY OF THE OBSERVATIONS
yr_mo_day = (2012, 8, 20)
utc = TimeScalesFactory.getUTC()

# OPEN THE CSV FILE CONTAINING THE OBSERVATIONS
data = open('Observations.csv')

csv_data = csv.reader(data)

data_lines = list(csv_data)

# LOOP OVER THE FILE AND CREATE THE OBSERVATION OBJECTS
# AngularRaDec objects hold Ra and Dec in this order

dates = []
obs = []

# I use the list method here to append rows and then transpose it, the next for
Esempio n. 16
0
    def __init__(self,
                 res_dir,
                 starcat_dir,
                 instrument,
                 with_infobox,
                 with_clipping,
                 sssb,
                 sun,
                 lightref,
                 encounter_date,
                 duration,
                 frames,
                 encounter_distance,
                 relative_velocity,
                 with_sunnyside,
                 with_terminator,
                 timesampler_mode,
                 slowmotion_factor,
                 exposure,
                 samples,
                 device,
                 tile_size,
                 oneshot=False,
                 spacecraft=None,
                 opengl_renderer=False):

        self.opengl_renderer = opengl_renderer
        self.brdf_params = sssb.get('brdf_params', None)

        self.root_dir = Path(__file__).parent.parent.parent
        data_dir = self.root_dir / "data"
        self.models_dir = utils.check_dir(data_dir / "models")

        self.res_dir = res_dir
        
        self.starcat_dir = starcat_dir

        self.inst = sc.Instrument(instrument)

        self.ts = TimeScalesFactory.getTDB()
        self.ref_frame = FramesFactory.getICRF()
        self.mu_sun = Constants.IAU_2015_NOMINAL_SUN_GM

        encounter_date = encounter_date
        self.encounter_date = AbsoluteDate(int(encounter_date["year"]),
                                           int(encounter_date["month"]),
                                           int(encounter_date["day"]),
                                           int(encounter_date["hour"]),
                                           int(encounter_date["minutes"]),
                                           float(encounter_date["seconds"]),
                                           self.ts)
        self.duration = duration
        self.start_date = self.encounter_date.shiftedBy(-self.duration / 2.)
        self.end_date = self.encounter_date.shiftedBy(self.duration / 2.)

        self.frames = frames

        self.minimum_distance = encounter_distance
        self.relative_velocity = relative_velocity
        self.with_terminator = bool(with_terminator)
        self.with_sunnyside = bool(with_sunnyside)
        self.timesampler_mode = timesampler_mode
        self.slowmotion_factor = slowmotion_factor

        self.render_settings = dict()
        self.render_settings["exposure"] = exposure
        self.render_settings["samples"] = samples
        self.render_settings["device"] = device
        self.render_settings["tile"] = tile_size

        self.sssb_settings = sssb
        self.with_infobox = with_infobox
        self.with_clipping = with_clipping

        # Setup rendering engine (renderer)
        self.setup_renderer()

        # Setup SSSB
        self.setup_sssb(sssb)

        # Setup SC
        self.setup_spacecraft(spacecraft, oneshot=oneshot)

        if not self.opengl_renderer:
            # Setup Sun
            self.setup_sun(sun)

            # Setup Lightref
            self.setup_lightref(lightref)

        logger.debug("Init finished")
Esempio n. 17
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)
Esempio n. 18
0
    def create_data_validity_checklist():
        """Get files loader by DataProvider and create dict() with valid dates for loaded data.

        Creates a list with valid start and ending date for data loaded by the
        DataProvider during building. The method looks for follwing folders
        holding the correspoding files:

            Earth-Orientation-Parameters: EOP files using IERS2010 convetions
            MSAFE: NASA Marshall Solar Activity Future Estimation files
            Magnetic-Field-Models: magentic field model data files

        The list should be used before every propagation step, to check if data
        is loaded/still exists for current simulation time. Otherwise
        simulation could return results with coarse accuracy. If e.g. no
        EOP data is available, null correction is used, which could worsen the
        propagators accuracy.
        """
        checklist = dict()
        start_dates = []
        end_dates = []

        EOP_file = _get_name_of_loaded_files('Earth-Orientation-Parameters')
        if EOP_file:
            EOPHist = FramesFactory.getEOPHistory(IERS.IERS_2010, False)
            EOP_start_date = EOPHist.getStartDate()
            EOP_end_date = EOPHist.getEndDate()
            checklist['EOP_dates'] = [EOP_start_date, EOP_end_date]
            start_dates.append(EOP_start_date)
            end_dates.append(EOP_end_date)

        CelesTrack_file = _get_name_of_loaded_files('CELESTRACK')
        if CelesTrack_file:
            ctw = CelesTrackWeather("(?:sw|SW)\\p{Digit}+\\.(?:txt|TXT)")
            ctw_start_date = ctw.getMinDate()
            ctw_end_date = ctw.getMaxDate()
            checklist['CTW_dates'] = [ctw_start_date, ctw_end_date]
            start_dates.append(ctw_start_date)
            end_dates.append(ctw_end_date)

        MSAFE_file = _get_name_of_loaded_files('MSAFE')
        if MSAFE_file:
            msafe = MarshallSolarActivityFutureEstimation(
                "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)" +
                "\\p{Digit}\\p{Digit}\\p{Digit}\\p{Digit}F10\\" +
                ".(?:txt|TXT)",
                MarshallSolarActivityFutureEstimation.StrengthLevel.AVERAGE)
            MS_start_date = msafe.getMinDate()
            MS_end_date = msafe.getMaxDate()
            checklist['MSAFE_dates'] = [MS_start_date, MS_end_date]
            start_dates.append(MS_start_date)
            end_dates.append(MS_end_date)

        if FileDataHandler._mag_field_coll:
            coll_iterator = FileDataHandler._mag_field_coll.iterator()
            first = coll_iterator.next()
            GM_start_date = first.validFrom()
            GM_end_date = first.validTo()
            for GM in coll_iterator:
                if GM_start_date > GM.validFrom():
                    GM_start_date = GM.validFrom()
                if GM_end_date < GM.validTo():
                    GM_end_date = GM.validTo()

            # convert to absolute date for later comparison
            dec_year = GM_start_date
            base = datetime(int(dec_year), 1, 1)
            dec = timedelta(seconds=(base.replace(year=base.year + 1) -
                                     base).total_seconds() * (dec_year-int(dec_year)))
            GM_start_date = to_orekit_date(base + dec)
            dec_year = GM_end_date
            base = datetime(int(dec_year), 1, 1)
            dec = timedelta(seconds=(base.replace(year=base.year + 1) -
                                     base).total_seconds() * (dec_year-int(dec_year)))
            GM_end_date = to_orekit_date(base + dec)
            checklist['MagField_dates'] = [GM_start_date, GM_end_date]
            start_dates.append(GM_start_date)
            end_dates.append(GM_end_date)

        if checklist:  # if any data loaded define first and last date
            # using as date zero 01.01.1850. Assuming no data before.
            absolute_zero = AbsoluteDate(1850, 1, 1, TimeScalesFactory.getUTC())
            first_date = min(start_dates, key=lambda p: p.durationFrom(absolute_zero))
            last_date = min(end_dates, key=lambda p: p.durationFrom(absolute_zero))

            checklist['MinMax_dates'] = [first_date, last_date]

        mesg = "[INFO]: Simulation can run between epochs: " + \
            str(first_date) + " & " + str(last_date) + \
            " (based on loaded files)."
        print mesg

        FileDataHandler._data_checklist = checklist
Esempio n. 19
0
    def __init__(self, orekit_data, settings=None, **kwargs):

        super(Orekit, self).__init__(settings=settings, **kwargs)

        if self.logger is not None:
            self.logger.debug(f'sorts.propagator.Orekit:init')
        if self.profiler is not None:
            self.profiler.start('Orekit:init')

        setup_orekit_curdir(filename=orekit_data)

        if self.logger is not None:
            self.logger.debug(f'Orekit:init:orekit-data = {orekit_data}')

        self.utc = TimeScalesFactory.getUTC()

        self.__settings = dict()
        self.__settings['SolarStrengthLevel'] = getattr(
            org.orekit.forces.drag.atmosphere.data.
            MarshallSolarActivityFutureEstimation.StrengthLevel,
            self.settings['solar_activity_strength'])
        self._tolerances = None

        if self.settings['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.__params = None

        self._forces = {}

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

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

        elif self.settings['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.settings['earth_gravity']))

        if self.settings['solarsystem_perturbers'] is not None:
            for body in self.settings['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 is not None:
            for key in self._forces:
                if self._forces[key] is not None:
                    self.logger.debug(
                        f'Orekit:init:_forces:{key} = {type(self._forces[key])}'
                    )
                else:
                    self.logger.debug(f'Orekit:init:_forces:{key} = None')

        if self.profiler is not None:
            self.profiler.stop('Orekit:init')
Esempio n. 20
0
def dlAndParseCpfData(username_edc, password_edc, url, datasetIdList,
                      startDate, endDate):
    """
    Downloads and parses CPF prediction data. A CPF file usually contains one week of data. Using both startDate and
    endDate parameters, it is possible to truncate this data.
    :param username_edc: str, username for the EDC API
    :param password_edc: str, password for the EDC API
    :param url: str, URL for the EDC API
    :param datasetIdList: list of dataset ids to download.
    :param startDate: datetime object. Data prior to this date will be removed
    :param endDate: datetime object. Data after this date will be removed
    :return: pandas DataFrame containing:
        - index: datetime object of the data point, in UTC locale
        - columns 'x', 'y', and 'z': float, satellite position in ITRF frame in meters
    """
    import requests
    import json
    from org.orekit.time import AbsoluteDate
    from org.orekit.time import TimeScalesFactory
    from orekit.pyhelpers import absolutedate_to_datetime
    utc = TimeScalesFactory.getUTC()

    dl_args = {}
    dl_args['username'] = username_edc
    dl_args['password'] = password_edc
    dl_args['action'] = 'data-download'
    dl_args['data_type'] = 'CPF'

    import pandas as pd
    cpfDataFrame = pd.DataFrame(columns=['x', 'y', 'z'])

    for datasetId in datasetIdList:
        dl_args['id'] = str(datasetId)
        dl_response = requests.post(url, data=dl_args)

        if dl_response.status_code == 200:
            """ convert json string in python list """
            data = json.loads(dl_response.text)

            currentLine = ''
            i = 0
            n = len(data)

            while (not currentLine.startswith('10')
                   ) and i < n:  # Reading lines until the H4 header
                currentLine = data[i]
                i += 1

            while currentLine.startswith('10') and i < n:
                lineData = currentLine.split()
                mjd_day = int(lineData[2])
                secondOfDay = float(lineData[3])
                position_ecef = [
                    float(lineData[5]),
                    float(lineData[6]),
                    float(lineData[7])
                ]
                absolutedate = AbsoluteDate.createMJDDate(
                    mjd_day, secondOfDay, utc)
                currentdatetime = absolutedate_to_datetime(absolutedate)

                if (currentdatetime >= startDate) and (currentdatetime <=
                                                       endDate):
                    cpfDataFrame.loc[currentdatetime] = position_ecef

                currentLine = data[i]
                i += 1

        else:
            print(dl_response.status_code)
            print(dl_response.text)

    return cpfDataFrame
Esempio n. 21
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