Source code for test_planetEphemeris


# ISC License
#
# Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#
#   Unit Test Script
#   Module Name:        planetEphemeris
#   Author:             Hanspeter Schaub
#   Creation Date:      April 24, 2019
#

import inspect
import os

import numpy as np
import pytest
from contextlib import nullcontext

filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
bskName = 'Basilisk'
splitPath = path.split(bskName)

# Import all of the modules that we are going to be called in this simulation
from Basilisk.utilities import SimulationBaseClass
from Basilisk.utilities import orbitalMotion
from Basilisk.utilities import RigidBodyKinematics as rbk
from Basilisk.utilities import unitTestSupport                  # general support file with common unit test functions
from Basilisk.simulation import planetEphemeris
from Basilisk.utilities import macros
from Basilisk.utilities import simHelpers
from Basilisk.architecture import bskLogging
from Basilisk.architecture.bskLogging import BasiliskError


def _make_zero_base_test_elements():
    """Create two heliocentric element sets for the zero-base tests.

    Returns:
        planetEphemeris.classicElementVector: Independent Earth and Moon-like
        heliocentric element sets.
    """
    earthElements = planetEphemeris.ClassicElements()
    earthElements.a = orbitalMotion.SMA_EARTH * 1000.0  # [m]
    earthElements.e = 0.01  # [-]
    earthElements.i = 10.0 * macros.D2R  # [deg] -> [rad]
    earthElements.Omega = 30.0 * macros.D2R  # [deg] -> [rad]
    earthElements.omega = 20.0 * macros.D2R  # [deg] -> [rad]
    earthElements.f = 90.0 * macros.D2R  # [deg] -> [rad]

    moonElements = planetEphemeris.ClassicElements()
    moonElements.a = 1.01 * orbitalMotion.SMA_EARTH * 1000.0  # [m]
    moonElements.e = 0.02  # [-]
    moonElements.i = 5.0 * macros.D2R  # [deg] -> [rad]
    moonElements.Omega = 110.0 * macros.D2R  # [deg] -> [rad]
    moonElements.omega = 220.0 * macros.D2R  # [deg] -> [rad]
    moonElements.f = 180.0 * macros.D2R  # [deg] -> [rad]

    return planetEphemeris.classicElementVector(
        [earthElements, moonElements]
    )


def _configure_zero_base_test_module(module):
    """Configure a ``PlanetEphemeris`` module with two oriented bodies.

    Args:
        module (planetEphemeris.PlanetEphemeris): Module to configure.
    """
    module.setPlanetNames(
        planetEphemeris.StringVector(["earth", "moon"])
    )
    module.planetElements = _make_zero_base_test_elements()
    module.rightAscension = planetEphemeris.DoubleVector(
        [0.0, 10.0 * macros.D2R]
    )  # [rad]
    module.declination = planetEphemeris.DoubleVector(
        [90.0 * macros.D2R, 80.0 * macros.D2R]
    )  # [rad]
    module.lst0 = planetEphemeris.DoubleVector(
        [0.0, 30.0 * macros.D2R]
    )  # [rad]
    module.rotRate = planetEphemeris.DoubleVector(
        [1.0e-5, 2.0e-5]
    )  # [rad/s]


[docs] def test_zero_base_translation(): """Verify that ``zeroBase`` translates positions and velocities only. Validation Test Description --------------------------- Two identical modules propagate the same oriented bodies. One retains the default heliocentric origin while the other selects Earth as ``zeroBase``. The relative outputs are compared with differences of the heliocentric outputs at three simulation times. Test Parameter Discussion ------------------------- Mixed-case ``"EaRtH"`` verifies case-insensitive body-name matching. The bodies use distinct orbits and attitudes so position, velocity, and orientation behavior are all observable. Description of Variables Being Tested --------------------------------------- The test checks ``PositionVector``, ``VelocityVector``, ``J20002Pfix``, ``J20002Pfix_dot``, ``computeOrient``, and ``PlanetName``. """ simulation = SimulationBaseClass.SimBaseClass() process = simulation.CreateNewProcess("zeroBaseProcess") taskStep = 0.5 # [s] process.addTask( simulation.CreateNewTask( "zeroBaseTask", macros.sec2nano(taskStep), ) ) heliocentricModule = planetEphemeris.PlanetEphemeris() heliocentricModule.ModelTag = "heliocentricPlanetEphemeris" assert heliocentricModule.zeroBase == "" _configure_zero_base_test_module(heliocentricModule) relativeModule = planetEphemeris.PlanetEphemeris() relativeModule.ModelTag = "relativePlanetEphemeris" _configure_zero_base_test_module(relativeModule) relativeModule.zeroBase = "EaRtH" simulation.AddModelToTask("zeroBaseTask", heliocentricModule, 10) simulation.AddModelToTask("zeroBaseTask", relativeModule, 10) heliocentricRecorders = [ message.recorder() for message in heliocentricModule.planetOutMsgs ] relativeRecorders = [ message.recorder() for message in relativeModule.planetOutMsgs ] for recorder in heliocentricRecorders + relativeRecorders: simulation.AddModelToTask("zeroBaseTask", recorder, 0) simulation.InitializeSimulation() simulationDuration = 1.0 # [s] simulation.ConfigureStopTime(macros.sec2nano(simulationDuration)) simulation.ExecuteSimulation() basePosition = heliocentricRecorders[0].PositionVector baseVelocity = heliocentricRecorders[0].VelocityVector positionTolerance = 1.0e-6 # [m] velocityTolerance = 1.0e-10 # [m/s] attitudeTolerance = 1.0e-14 # [-] for bodyIndex in range(2): expectedPosition = ( heliocentricRecorders[bodyIndex].PositionVector - basePosition ) expectedVelocity = ( heliocentricRecorders[bodyIndex].VelocityVector - baseVelocity ) np.testing.assert_allclose( relativeRecorders[bodyIndex].PositionVector, expectedPosition, rtol=0.0, atol=positionTolerance, ) np.testing.assert_allclose( relativeRecorders[bodyIndex].VelocityVector, expectedVelocity, rtol=0.0, atol=velocityTolerance, ) np.testing.assert_allclose( relativeRecorders[bodyIndex].J20002Pfix, heliocentricRecorders[bodyIndex].J20002Pfix, rtol=0.0, atol=attitudeTolerance, ) np.testing.assert_allclose( relativeRecorders[bodyIndex].J20002Pfix_dot, heliocentricRecorders[bodyIndex].J20002Pfix_dot, rtol=0.0, atol=attitudeTolerance, ) np.testing.assert_array_equal( relativeRecorders[bodyIndex].computeOrient, heliocentricRecorders[bodyIndex].computeOrient, ) assert relativeModule.planetOutMsgs[0].read().PlanetName == "earth" assert relativeModule.planetOutMsgs[1].read().PlanetName == "moon"
[docs] def test_zero_base_requires_local_body(): """Verify that ``zeroBase`` rejects bodies owned by another instance. Validation Test Description --------------------------- A module configured with Earth and Moon selects Mars as its translational origin. Initialization must stop with a ``BasiliskError`` because Mars is not propagated by that module instance. """ simulation = SimulationBaseClass.SimBaseClass() process = simulation.CreateNewProcess("invalidZeroBaseProcess") taskStep = 0.5 # [s] process.addTask( simulation.CreateNewTask( "invalidZeroBaseTask", macros.sec2nano(taskStep), ) ) module = planetEphemeris.PlanetEphemeris() _configure_zero_base_test_module(module) module.zeroBase = "mars" simulation.AddModelToTask("invalidZeroBaseTask", module) with pytest.raises(BasiliskError, match="not one of the bodies configured"): simulation.InitializeSimulation()
# Uncomment this line is this test is to be skipped in the global unit test run, adjust message as needed. # @pytest.mark.skipif(conditionstring) # Uncomment this line if this test has an expected failure, adjust message as needed. # @pytest.mark.xfail(conditionstring) # Provide a unique test method name, starting with 'test_'. # The following 'parametrize' function decorator provides the parameters and expected results for each # of the multiple test runs for this test.
[docs] @pytest.mark.parametrize("setRAN", [ True, False]) @pytest.mark.parametrize("setDEC", [ True, False]) @pytest.mark.parametrize("setLST", [ True, False]) @pytest.mark.parametrize("setRate", [ True, False]) # update "module" in this function name to reflect the module name def test_module(show_plots, setRAN, setDEC, setLST, setRate): """Module Unit Test""" # each test method requires a single assert method to be called expect_error = any([setRAN, setDEC, setLST, setRate]) and not all([setRAN, setDEC, setLST, setRate]) with pytest.raises(BasiliskError) if expect_error else nullcontext(): [testResults, testMessage] = planetEphemerisTest(show_plots, setRAN, setDEC, setLST, setRate) assert testResults < 1, testMessage
def planetEphemerisTest(show_plots, setRAN, setDEC, setLST, setRate): bskLogging.setDefaultLogLevel(bskLogging.SILENT) testFailCount = 0 # zero unit test result counter testMessages = [] # create empty array to store test log messages unitTaskName = "unitTask" # arbitrary name (don't change) unitProcessName = "TestProcess" # arbitrary name (don't change) # Create a sim module as an empty container unitTestSim = SimulationBaseClass.SimBaseClass() # Create test thread testProcessRate = macros.sec2nano(0.5) # update process rate update time testProc = unitTestSim.CreateNewProcess(unitProcessName) testProc.addTask(unitTestSim.CreateNewTask(unitTaskName, testProcessRate)) # Construct algorithm and associated C++ container module = planetEphemeris.PlanetEphemeris() module.ModelTag = 'planetEphemeris' # Add test module to runtime call list unitTestSim.AddModelToTask(unitTaskName, module) # Initialize the test module configuration data planetNames = ["earth", "venus"] module.setPlanetNames(planetEphemeris.StringVector(planetNames)) # set gravitational constant of the sun mu = orbitalMotion.MU_SUN*1000.*1000.*1000 # m^3/s^2 # setup planet ephemeris states oeEarth = planetEphemeris.ClassicElements() oeEarth.a = orbitalMotion.SMA_EARTH*1000 # meters oeEarth.e = 0.001 oeEarth.i = 10.0*macros.D2R oeEarth.Omega = 30.0*macros.D2R oeEarth.omega = 20.0*macros.D2R oeEarth.f = 90.0*macros.D2R oeVenus = planetEphemeris.ClassicElements() oeVenus.a = orbitalMotion.SMA_VENUS*1000 # meters oeVenus.e = 0.001 oeVenus.i = 5.0*macros.D2R oeVenus.Omega = 110.0*macros.D2R oeVenus.omega = 220.0*macros.D2R oeVenus.f = 180.0*macros.D2R module.planetElements = planetEphemeris.classicElementVector([oeEarth, oeVenus]) evalAttitude = 1 if setRAN: # setup planet local right ascension angle at epoch RANlist = [0.*macros.D2R, 272.76*macros.D2R] module.rightAscension = planetEphemeris.DoubleVector(RANlist) else: evalAttitude = 0 if setDEC: # setup planet local declination angle at epoch DEClist = [90.*macros.D2R, 67.16*macros.D2R] module.declination = planetEphemeris.DoubleVector(DEClist) else: evalAttitude = 0 if setLST: # setup planet local sidereal time at epoch lstList = [10.*macros.D2R, 30.*macros.D2R] module.lst0 = planetEphemeris.DoubleVector(lstList) else: evalAttitude = 0 if setRate: # setup planet rotation rate about polar axis omegaList = [planetEphemeris.OMEGA_EARTH, planetEphemeris.OMEGA_VENUS] module.rotRate = planetEphemeris.DoubleVector(omegaList) else: evalAttitude = 0 # Setup logging on the test module output message so that we get all the writes to it dataLog = [] for c in range(0, len(planetNames)): dataLog.append(module.planetOutMsgs[c].recorder()) unitTestSim.AddModelToTask(unitTaskName, dataLog[-1]) # Need to call the self-init and cross-init methods unitTestSim.InitializeSimulation() # Set the simulation time. # NOTE: the total simulation time may be longer than this value. The # simulation is stopped at the next logging event on or after the # simulation end time. unitTestSim.ConfigureStopTime(macros.sec2nano(1.0)) # seconds to stop simulation # Begin the simulation time run set above unitTestSim.ExecuteSimulation() accuracy = 1e-3 simHelpers.writeTeXSnippet("toleranceValue", str(accuracy), path) # This pulls the actual data log from the simulation run. # Note that range(3) will provide [0, 1, 2] Those are the elements you get from the vector (all of them) c = 0 for c in range(0, len(planetNames)): planet = planetNames[c] J2000Current = dataLog[c].J2000Current PositionVector = dataLog[c].PositionVector VelocityVector = dataLog[c].VelocityVector J20002Pfix = dataLog[c].J20002Pfix J20002Pfix_dot = dataLog[c].J20002Pfix_dot computeOrient = dataLog[c].computeOrient # check that the proper planet name string is set FinalPlanetMessage = module.planetOutMsgs[c].read() if planet != FinalPlanetMessage.PlanetName: testFailCount += 1 testMessages.append("FAILED: planetEphemeris() didn't set the desired plane name " + planet) # check that the time information is correct timeTrue = [0.0, 0.5, 1.0] testFailCount, testMessages = unitTestSupport.compareDoubleArray( timeTrue, J2000Current, accuracy, "J2000Current", testFailCount, testMessages) # check that the position and velocity vectors are correct if planet == "earth": oe = oeEarth else: oe = oeVenus f0 = oe.f E0 = orbitalMotion.f2E(f0, oe.e) M0 = orbitalMotion.E2M(E0, oe.e) rTrue = [] vTrue = [] for time in timeTrue: Mt = M0 + np.sqrt(mu/oe.a/oe.a/oe.a)*time Et = orbitalMotion.M2E(Mt, oe.e) oe.f = orbitalMotion.E2f(Et, oe.e) rv, vv = orbitalMotion.elem2rv(mu, oe) rTrue.append(rv) vTrue.append(vv) testFailCount, testMessages = unitTestSupport.compareArray(rTrue, PositionVector, accuracy, "Position Vector", testFailCount, testMessages) testFailCount, testMessages = unitTestSupport.compareArray(vTrue, VelocityVector, accuracy, "Velocity Vector", testFailCount, testMessages) # check if the planet DCM and DCM rate is correct dcmTrue = [] dcmRateTrue = [] if evalAttitude: RAN = RANlist[c] DEC = DEClist[c] lst0 = lstList[c] omega_NP_P = np.array([0.0, 0.0, -omegaList[c]]) tilde = rbk.v3Tilde(omega_NP_P) for time in timeTrue: lst = lst0 + omegaList[c]*time DCM = rbk.euler3232C([RAN, np.pi/2.0 - DEC, lst]) dcmTrue.append(DCM) dDCMdt = np.matmul(tilde, DCM) dcmRateTrue.append(dDCMdt) else: for time in timeTrue: dcmTrue.append(np.identity(3)) dcmRateTrue.append([0.0]*9) testFailCount, testMessages = unitTestSupport.compareArrayND(dcmTrue, J20002Pfix, accuracy, "DCM", 9, testFailCount, testMessages) testFailCount, testMessages = unitTestSupport.compareArrayND(dcmRateTrue, J20002Pfix_dot, 1e-10, "DCM Rate", 9, testFailCount, testMessages) # check if the orientation evaluation flag is set correctly flagTrue = [evalAttitude] * 3 testFailCount, testMessages = unitTestSupport.compareDoubleArray( flagTrue, computeOrient, accuracy, "computeOrient", testFailCount, testMessages) c = c+1 # print out success message if no error were found snippentName = "passFail" + str(setRAN) + str(setDEC) + str(setLST) + str(setRate) if testFailCount == 0: colorText = 'ForestGreen' print("PASSED: " + module.ModelTag) passedText = r'\textcolor{' + colorText + '}{' + "PASSED" + '}' else: colorText = 'Red' print("Failed: " + module.ModelTag) passedText = r'\textcolor{' + colorText + '}{' + "Failed" + '}' simHelpers.writeTeXSnippet(snippentName, passedText, path) # each test method requires a single assert method to be called # this check below just makes sure no sub-test failures were found return [testFailCount, ''.join(testMessages)] # # This statement below ensures that the unitTestScript can be run as a # stand-along python script # if __name__ == "__main__": test_zero_base_translation() test_zero_base_requires_local_body() test_module( False, # show plots flag True, # setRAN True, # setDEC True, # setLST True # setRate )