#
# ISC License
#
# Copyright (c) 2023, Autonomous Vehicle Systems Lab, University of Colorado 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.
#
#
#
# Thermal Sensor Faults Test
#
# Purpose: Test the proper function of the faulty behaviors of the tempMeasurement module.
# Results are compared to simple truth values.
# To test spiking, percent of spike values compared with expected.
# Creation Date: Feb. 9, 2023
#
import os
import numpy as np
import pytest
from Basilisk.architecture import messaging
from Basilisk.architecture import astroConstants
from Basilisk.simulation import sensorThermal, tempMeasurement
from Basilisk.utilities import SimulationBaseClass
from Basilisk.utilities import macros
from Basilisk.utilities import unitTestSupport
path = os.path.dirname(os.path.abspath(__file__))
# The following 'parametrize' function decorator provides the parameters and expected results for each
# of the multiple test runs for this test.
# Need RNGSeed 464374481
[docs]
@pytest.mark.parametrize(
"tempFault",
[
"TEMP_FAULT_NOMINAL",
"TEMP_FAULT_STUCK_CURRENT",
"TEMP_FAULT_STUCK_VALUE",
"TEMP_FAULT_SPIKING",
"BIASED"
])
# provide a unique test method name, starting with test_
def test_sensorThermalFault(tempFault):
"""Check measurement faults against an independently computed thermal history.
Expected temperatures follow the electrical heating and radiative cooling
heat balance, integrated with one Euler step per task update. The sensor
normal is perpendicular to sunlight, so no solar power is absorbed.
:param tempFault: Measurement fault or bias configuration to exercise.
"""
# each test method requires a single assert method to be called
[testResults, testMessage] = run(tempFault)
assert testResults < 1, testMessage
__tracebackhide__ = True
[docs]
def run(tempFault):
"""Run a measurement fault case using an independent heat-balance reference.
:param tempFault: Measurement fault or bias configuration to exercise.
:return: Failure count and diagnostic message.
"""
testFailCount = 0 # zero unit test result counter
testMessages = [] # create empty list to store test log messages
# Create simulation variable names
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()
# set the simulation time variable used later on
simulationTime = macros.sec2nano(100.) # [ns]
#
# create the simulation process
#
testProcessRate = macros.sec2nano(1.0) # [ns] task update interval
testProc = unitTestSim.CreateNewProcess(unitProcessName)
testProc.addTask(unitTestSim.CreateNewTask(unitTaskName, testProcessRate))
#
# set up the simulation tasks/objects
#
# set device status message
sensorStatusMsgPayload = messaging.DeviceStatusMsgPayload()
sensorStatusMsgPayload.deviceStatus = 1
sensorStatusMsg = messaging.DeviceStatusMsg().write(sensorStatusMsgPayload)
# set the spacecraft message
scStateMsgPayload = messaging.SCStatesMsgPayload()
scStateMsgPayload.r_BN_N = [6378*1000., 0., 0.]
scStateMsgPayload.sigma_BN = [0., 0., 0.]
scStateMsg = messaging.SCStatesMsg().write(scStateMsgPayload)
# set the sun message
sunMsgPayload = messaging.SpicePlanetStateMsgPayload()
sunMsgPayload.PositionVector = [astroConstants.AU*1000., 0., 0.]
sunMsg = messaging.SpicePlanetStateMsg().write(sunMsgPayload)
#
# set up the truth value temperature modeling
#
sensorThermalModel = sensorThermal.SensorThermal()
sensorThermalModel.ModelTag = 'sensorThermalModel'
sensorThermalModel.nHat_B = [0, 0, 1]
sensorThermalModel.sensorArea = 1.0 # m^2
sensorThermalModel.sensorAbsorptivity = 0.25
sensorThermalModel.sensorEmissivity = 0.34
sensorThermalModel.sensorMass = 2.0 # kg
sensorThermalModel.sensorSpecificHeat = 890 # [J/(kg K)]
sensorThermalModel.sensorPowerDraw = 30.0 # W
sensorThermalModel.T_0 = 0 # [ÂșC]
sensorThermalModel.sunInMsg.subscribeTo(sunMsg)
sensorThermalModel.stateInMsg.subscribeTo(scStateMsg)
sensorThermalModel.sensorStatusInMsg.subscribeTo(sensorStatusMsg)
unitTestSim.AddModelToTask(unitTaskName, sensorThermalModel)
#
# set up the tempMeasurement module
#
tempMeasurementModel = tempMeasurement.TempMeasurement()
tempMeasurementModel.tempInMsg.subscribeTo(sensorThermalModel.temperatureOutMsg)
unitTestSim.AddModelToTask(unitTaskName, tempMeasurementModel)
#
# log data
#
# log the RW temperature
tempLog = tempMeasurementModel.tempOutMsg.recorder()
unitTestSim.AddModelToTask(unitTaskName, tempLog)
# Independently integrate m*c_p*dT/dt = P - emissivity*sigma*A*T_K**4.
# Use the 2022 CODATA constant rather than the module's radiation coefficient
# or recorded output. Include the initial sample at t = 0.
stefanBoltzmann = 5.670374419e-8 # [W/(m^2 K^4)]
kelvinOffset = 273.15 # [K]
stepSeconds = testProcessRate*macros.NANO2SEC
heatCapacity = sensorThermalModel.sensorMass*sensorThermalModel.sensorSpecificHeat
nominals = np.empty(simulationTime//testProcessRate + 1)
nominals[0] = sensorThermalModel.T_0
for sample in range(1, len(nominals)):
temperatureKelvin = nominals[sample - 1] + kelvinOffset
radiatedPower = (
sensorThermalModel.sensorArea*sensorThermalModel.sensorEmissivity*stefanBoltzmann*temperatureKelvin**4
)
temperatureChange = (sensorThermalModel.sensorPowerDraw - radiatedPower)*stepSeconds/heatCapacity
nominals[sample] = nominals[sample - 1] + temperatureChange
faultTime = simulationTime//2
#
# initialize Simulation
#
# Truth Values
if tempFault == "TEMP_FAULT_NOMINAL":
truthValue = nominals[-1]
unitTestSim.InitializeSimulation()
unitTestSim.ConfigureStopTime(simulationTime)
unitTestSim.ExecuteSimulation()
elif tempFault == "TEMP_FAULT_STUCK_CURRENT":
truthValue = nominals[faultTime//testProcessRate]
unitTestSim.InitializeSimulation()
unitTestSim.ConfigureStopTime(faultTime)
unitTestSim.ExecuteSimulation()
tempMeasurementModel.faultState = tempMeasurement.TEMP_FAULT_STUCK_CURRENT
unitTestSim.ConfigureStopTime(simulationTime)
unitTestSim.ExecuteSimulation()
elif tempFault == "TEMP_FAULT_STUCK_VALUE":
truthValue = 10.0
tempMeasurementModel.stuckValue = 10.0
unitTestSim.InitializeSimulation()
unitTestSim.ConfigureStopTime(faultTime)
unitTestSim.ExecuteSimulation()
tempMeasurementModel.faultState = tempMeasurement.TEMP_FAULT_STUCK_VALUE
unitTestSim.ConfigureStopTime(simulationTime)
unitTestSim.ExecuteSimulation()
elif tempFault == "TEMP_FAULT_SPIKING":
tempMeasurementModel.faultState = tempMeasurement.TEMP_FAULT_SPIKING
truthValue = 0.1
unitTestSim.InitializeSimulation()
unitTestSim.ConfigureStopTime(simulationTime)
unitTestSim.ExecuteSimulation()
testValue = 0
sensorTemp = np.array(tempLog.temperature)
for ii in range(len(nominals)):
if abs(nominals[ii]) > 0.0001:
if abs(nominals[ii] - sensorTemp[ii]) > 1e-6:
testValue = testValue + 1
else:
if abs(sensorTemp[ii]) > 1e-6:
testValue = testValue + 1
testValue = testValue/len(nominals)
elif tempFault == "BIASED":
biasVal = 1.0 # [K] temperature bias
tempMeasurementModel.senBias = biasVal
truthValue = nominals[-1] + biasVal
unitTestSim.InitializeSimulation()
unitTestSim.ConfigureStopTime(simulationTime)
unitTestSim.ExecuteSimulation()
else:
NotImplementedError("Fault type specified does not exist.")
sensorTemp = np.array(tempLog.temperature)
print(sensorTemp)
#
# compare the module results to the true values
#
if tempFault == "TEMP_FAULT_SPIKING":
if not unitTestSupport.isDoubleEqualRelative(testValue, truthValue, 5E-1): # only 101 values so need this to be relatively relaxed (within 50%)
testFailCount+= 1
elif not unitTestSupport.isDoubleEqualRelative(sensorTemp[-1], truthValue, 1E-12):
testFailCount += 1
return [testFailCount, ''.join(testMessages)]
# each test method requires a single assert method to be called
# this check below just makes sure no sub-test failures were found
if __name__ == "__main__":
run("TEMP_FAULT_NOMINAL")