#
# ISC License
#
# Copyright (c) 2021, 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.
#
#
# Unit Test Script
# Module Name: dentonFluxModel
# Author: Julian Hammerl
# Creation Date: December 12, 2021
#
import inspect
import math
import os
import matplotlib.pyplot as plt
import numpy as np
import pytest
from Basilisk import __path__
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
bskPath = __path__[0]
from Basilisk.utilities import SimulationBaseClass
from Basilisk.architecture import bskLogging, messaging
from Basilisk.utilities import macros
from Basilisk.simulation import dentonFluxModel
from Basilisk.utilities.supportDataTools.dataFetcher import get_path, DataFile
Kps = ['0o', '4-', '5+']
LTs = [0.00, 14.73]
z_offsets = [0., 3500e3]
r_EN_Ns = np.array([[0., 0., 0.], [400e3, 300e3, -200e3]])
[docs]
@pytest.mark.parametrize("accuracy", [1e2])
@pytest.mark.parametrize("param1_Kp, param2_LT, param3_z, param4_r_EN", [
(Kps[0], LTs[0], z_offsets[0], r_EN_Ns[0]),
(Kps[1], LTs[1], z_offsets[1], r_EN_Ns[0]),
(Kps[1], LTs[1], z_offsets[0], r_EN_Ns[1]),
(Kps[1], LTs[1], z_offsets[1], r_EN_Ns[1]),
(Kps[1], LTs[0], z_offsets[1], r_EN_Ns[1]),
(Kps[2], LTs[1], z_offsets[1], r_EN_Ns[1]),
(Kps[2], LTs[0], z_offsets[1], r_EN_Ns[1]),
])
def test_dentonFluxModel(show_plots, param1_Kp, param2_LT, param3_z, param4_r_EN, accuracy):
r"""
**Validation Test Description**
The Denton Flux Module is tested for several different Kp indices, local times, and spacecraft/Sun/Earth positions
**Test Parameters**
Args:
show_plots (bool): specify if plots should be shown
param1_Kp (str): Kp Index
param2_LT (float): Local Time (use 2 decimals)
param3_z (float): z-offset to test spacecraft and Sun position with offset to equatorial plane
param4_r_EN (float np.array): r_EN_N position vector of Earth w.r.t. N frame, in N frame components
accuracy (float): absolute accuracy value used in the validation tests
**Description of Variables Being Tested**
The electron and ion energies are compared to make sure the flux data is computed for the same energy. The main
part of the unitTest is to compare the electron and ion flux.
"""
dentonFluxModelTestFunction(show_plots, param1_Kp, param2_LT, param3_z, param4_r_EN,
accuracy)
[docs]
@pytest.fixture(scope="module")
def denton_constant_files(tmp_path_factory):
"""Create complete electron and ion tables with constant logarithmic fluxes."""
directory = tmp_path_factory.mktemp("denton_data")
files = [directory / "electrons.txt", directory / "ions.txt"]
for file_path, token in zip(files, ("2.0", "3.0")):
file_path.write_text(" ".join([token] * (28 * 7 * 40 * 24)), encoding="ascii")
return [str(file_path) for file_path in files]
[docs]
@pytest.fixture
def denton_file_model(denton_constant_files):
"""Configure a model at local noon for testing data-file initialization."""
module = dentonFluxModel.DentonFluxModel()
module.kpIndex = "9o"
module.numOutputEnergies = 6
module.configureDentonFiles(*denton_constant_files)
sc_payload = messaging.SCStatesMsgPayload()
sc_payload.r_BN_N = [42164e3, 0.0, 0.0] # [m]
sun_payload = messaging.SpicePlanetStateMsgPayload()
sun_payload.PositionVector = [1.495978707e11, 0.0, 0.0] # [m]
module.scStateInMsg.subscribeTo(messaging.SCStatesMsg().write(sc_payload))
module.sunStateInMsg.subscribeTo(messaging.SpicePlanetStateMsg().write(sun_payload))
module.earthStateInMsg.subscribeTo(messaging.SpicePlanetStateMsg().write(messaging.SpicePlanetStateMsgPayload()))
return module
[docs]
@pytest.mark.parametrize("species", [0, 1], ids=["electrons", "ions"])
@pytest.mark.parametrize("value_index, replacement", [
(0, None), # Empty file.
(40 * 24, None), # Truncated at the first discarded statistic.
(75264, None), # The issue's file truncated to 40 percent.
(28 * 7 * 40 * 24 - 1, None), # Missing only the last required value.
(0, "invalid"),
(40 * 24, "invalid"),
(27 * 7 * 40 * 24, "invalid"), # First mean value in the last Kp bin.
(28 * 7 * 40 * 24 - 1, "invalid"),
(0, "nan"),
(40 * 24, "inf"),
(28 * 7 * 40 * 24 - 1, "-inf"),
(0, "1e309"),
(28 * 7 * 40 * 24 - 1, "1junk"),
])
def test_dentonFluxModel_invalid_data_file(denton_file_model, denton_constant_files, tmp_path,
species, value_index, replacement):
"""Reject missing or invalid values in either file, including unused statistics."""
tokens = ["2.0"] * (28 * 7 * 40 * 24)
if replacement is None:
tokens = tokens[:value_index]
else:
tokens[value_index] = replacement
bad_file = tmp_path / "bad_%s_%n.txt"
bad_file.write_text(" ".join(tokens), encoding="ascii")
files = list(denton_constant_files)
files[species] = str(bad_file)
denton_file_model.configureDentonFiles(*files)
with pytest.raises(bskLogging.BasiliskError, match=f"value {value_index + 1} from") as error:
denton_file_model.Reset(0)
assert str(bad_file) in str(error.value)
[docs]
@pytest.mark.parametrize("trailing_whitespace", ["", " \t\r\n"])
def test_dentonFluxModel_complete_data_files(denton_file_model, denton_constant_files, tmp_path,
trailing_whitespace):
"""Accept a complete table with or without trailing whitespace and preserve its fluxes."""
files = []
for source, name in zip(denton_constant_files, ("electrons.txt", "ions.txt")):
with open(source, encoding="ascii") as stream:
text = stream.read()
destination = tmp_path / name
destination.write_text(text + trailing_whitespace, encoding="ascii")
files.append(str(destination))
denton_file_model.configureDentonFiles(*files)
denton_file_model.Reset(0)
denton_file_model.UpdateState(0)
output = denton_file_model.fluxOutMsg.read()
expected_electron_flux = 1e6 # [m^-2 s^-1 sr^-1 eV^-1]
expected_ion_flux = 1e7 # [m^-2 s^-1 sr^-1 eV^-1]
np.testing.assert_allclose(output.meanElectronFlux[:6], expected_electron_flux, rtol=1e-12)
np.testing.assert_allclose(output.meanIonFlux[:6], expected_ion_flux, rtol=1e-12)
[docs]
@pytest.fixture(scope="module")
def denton_interpolation_tables():
"""Load the table rows bracketing the endpoint energies used in these tests."""
files = (DataFile.DentonGEOData.model_e_array_all, DataFile.DentonGEOData.model_i_array_all)
# [eV] Electron and ion table energies at indices 16, 17, 38 and 39.
energy_axes = (
[80.120170, 104.563461, 30782.000000, 40326.937500],
[89.082473, 115.585487, 31140.962890, 40649.562500],
)
tables = []
for data_file, energy_axis in zip(files, energy_axes):
file_path = get_path(data_file)
means = np.loadtxt(file_path).reshape(28, 7, 40, 24)[:, 0, [16, 17, 38, 39], :]
tables.append((str(file_path), np.log(energy_axis), means))
return tables
[docs]
def denton_flux_output(tables, kp_index, num_energies, local_time, sun_direction):
"""Evaluate the module once at the requested local time in hours."""
module = dentonFluxModel.DentonFluxModel()
module.kpIndex = kp_index
module.numOutputEnergies = num_energies
module.configureDentonFiles(*(table[0] for table in tables))
sun_direction = np.asarray(sun_direction) / np.linalg.norm(sun_direction)
angle = (local_time - 12.0) * np.pi / 12.0 # [rad]
rotation = np.array([[math.cos(angle), -math.sin(angle)], [math.sin(angle), math.cos(angle)]])
sc_payload = messaging.SCStatesMsgPayload()
sc_payload.r_BN_N = [*(42164e3 * (rotation @ sun_direction)), 0.0] # [m]
sun_payload = messaging.SpicePlanetStateMsgPayload()
sun_payload.PositionVector = [*(1.495978707e11 * sun_direction), 0.0] # [m]
sc_msg = messaging.SCStatesMsg().write(sc_payload)
sun_msg = messaging.SpicePlanetStateMsg().write(sun_payload)
earth_msg = messaging.SpicePlanetStateMsg().write(messaging.SpicePlanetStateMsgPayload())
module.scStateInMsg.subscribeTo(sc_msg)
module.sunStateInMsg.subscribeTo(sun_msg)
module.earthStateInMsg.subscribeTo(earth_msg)
module.Reset(0)
module.UpdateState(0)
return module.fluxOutMsg.read()
[docs]
@pytest.mark.parametrize("kp_index, kp_row", [("0o", 0), ("3o", 9), ("9o", 27)])
@pytest.mark.parametrize(
"local_time", list(range(24)) + [0.01, 11.999, 12.001, 23.01, 23.5, 23.99, 24.0]) # [h]
@pytest.mark.parametrize("sun_direction", [[1.0, 0.0], [1.0, 1.0]]) # [-]
def test_dentonFluxModel_periodic_interpolation(denton_interpolation_tables, kp_index, kp_row,
local_time, sun_direction):
"""Check both species against independent interpolation of the source tables.
Cover every whole hour, both sides of noon and midnight, and the last Kp
and energy bins. Include rotated Sun directions and exactly 24 h, where
rounding can leave the normalized dot product above -1. Expected values
interpolate in log energy first, then periodically in local time.
"""
output = denton_flux_output(denton_interpolation_tables, kp_index, 6, local_time, sun_direction)
energies = np.array([100.0, 33430.0]) # [eV]
np.testing.assert_array_equal(np.asarray(output.energies)[[0, 5]], energies)
for flux, (_, log_energies, means) in zip(
(output.meanElectronFlux, output.meanIonFlux), denton_interpolation_tables):
expected = []
for energy in energies:
hourly_flux = [np.interp(np.log(energy), log_energies, means[kp_row, :, hour])
for hour in range(24)]
log_flux = np.interp(local_time % 24.0, np.arange(25), hourly_flux + hourly_flux[:1])
expected.append(10.0**log_flux * 1e4) # [m^-2 s^-1 sr^-1 eV^-1]
np.testing.assert_allclose(np.asarray(flux)[[0, 5]], expected, rtol=1e-12, atol=0.0)
[docs]
@pytest.mark.parametrize(
"num_energies, last_energy", [(1, 100.0), (40, 39061.0), (41, 39100.0), (50, 39251.0)]) # last_energy [eV]
def test_dentonFluxModel_output_energy_bounds(denton_interpolation_tables, num_energies, last_energy):
"""Check the full output energy grid and endpoint fluxes at the storage boundaries."""
output = denton_flux_output(denton_interpolation_tables, "9o", num_energies, 12.0, [1.0, 0.0])
energies = np.linspace(100.0, last_energy, num_energies) # [eV]
np.testing.assert_array_equal(np.asarray(output.energies)[:num_energies], energies)
np.testing.assert_array_equal(np.asarray(output.energies)[num_energies:], 0.0)
for flux, (_, log_energies, means) in zip(
(output.meanElectronFlux, output.meanIonFlux), denton_interpolation_tables):
log_flux = np.interp(np.log(energies[[0, -1]]), log_energies, means[27, :, 12])
expected = 10.0**log_flux * 1e4 # [m^-2 s^-1 sr^-1 eV^-1]
np.testing.assert_allclose(np.asarray(flux)[[0, num_energies - 1]], expected, rtol=1e-12, atol=0.0)
np.testing.assert_array_equal(np.asarray(flux)[num_energies:], 0.0)
[docs]
@pytest.mark.parametrize("num_energies", [-1, 0, messaging.MAX_PLASMA_FLUX_SIZE + 1])
def test_dentonFluxModel_invalid_output_energy_count(num_energies):
"""Reject invalid counts before dividing by the count or accessing the energy arrays."""
module = dentonFluxModel.DentonFluxModel()
module.numOutputEnergies = num_energies
module.kpIndex = "3o"
module.scStateInMsg.subscribeTo(messaging.SCStatesMsg().write(messaging.SCStatesMsgPayload()))
module.earthStateInMsg.subscribeTo(messaging.SpicePlanetStateMsg().write(messaging.SpicePlanetStateMsgPayload()))
module.sunStateInMsg.subscribeTo(messaging.SpicePlanetStateMsg().write(messaging.SpicePlanetStateMsgPayload()))
with pytest.raises(bskLogging.BasiliskError, match="numOutputEnergies must be between"):
module.Reset(0)
[docs]
def dentonFluxModelTestFunction(show_plots, param1_Kp, param2_LT, param3_z, param4_r_EN, accuracy):
"""Test method"""
unitTaskName = "unitTask"
unitProcessName = "TestProcess"
# Create sim module and test thread
unitTestSim = SimulationBaseClass.SimBaseClass()
testProcessRate = macros.sec2nano(0.5)
testProc = unitTestSim.CreateNewProcess(unitProcessName)
testProc.addTask(unitTestSim.CreateNewTask(unitTaskName, testProcessRate))
# setup module to be tested
module = dentonFluxModel.DentonFluxModel()
module.ModelTag = "dentonFluxModule"
module.kpIndex = param1_Kp
module.numOutputEnergies = 6
e_path = get_path(DataFile.DentonGEOData.model_e_array_all)
i_path = get_path(DataFile.DentonGEOData.model_i_array_all)
# configure DentonFluxModel with explicit file paths
module.configureDentonFiles(str(e_path), str(i_path))
unitTestSim.AddModelToTask(unitTaskName, module)
# Set up position vectors (param3_z is used to offset S/C and sun from equatorial plane)
LT = param2_LT
angle = LT * 360./24. * np.pi/180 - np.pi
orbitRadius = 42000 * 1e3 # GEO orbit
r_BE_N = np.array([orbitRadius * math.cos(angle), orbitRadius * math.sin(angle), param3_z])
r_SE_N = np.array([149000000000.0, 0., -2.73*param3_z])
r_EN_N = param4_r_EN
r_BN_N = r_BE_N + r_EN_N
r_SN_N = r_SE_N + r_EN_N
# Configure input messages
scStateInMsgData = messaging.SCStatesMsgPayload()
scStateInMsgData.r_BN_N = r_BN_N
scStateInMsg = messaging.SCStatesMsg().write(scStateInMsgData)
sunStateInMsgData = messaging.SpicePlanetStateMsgPayload()
sunStateInMsgData.PositionVector = r_SN_N
sunStateInMsg = messaging.SpicePlanetStateMsg().write(sunStateInMsgData)
earthStateInMsgData = messaging.SpicePlanetStateMsgPayload()
earthStateInMsgData.PositionVector = r_EN_N
earthStateInMsg = messaging.SpicePlanetStateMsg().write(earthStateInMsgData)
# subscribe input messages to module
module.scStateInMsg.subscribeTo(scStateInMsg)
module.earthStateInMsg.subscribeTo(earthStateInMsg)
module.sunStateInMsg.subscribeTo(sunStateInMsg)
# setup output message recorder objects
fluxOutMsgRec = module.fluxOutMsg.recorder()
unitTestSim.AddModelToTask(unitTaskName, fluxOutMsgRec)
# run simulation
unitTestSim.InitializeSimulation()
unitTestSim.TotalSim.SingleStepProcesses()
# pull module data
energyData = fluxOutMsgRec.energies[0]
electronFluxData = fluxOutMsgRec.meanElectronFlux[0]
ionFluxData = fluxOutMsgRec.meanIonFlux[0]
# convert Kp index to Kp index counter (between 0 and 27)
kpMain = param1_Kp[0] # main Kp index, between 0 and 9
kpSub = param1_Kp[1] # sub Kp index, either '-', 'o', or '+'
if kpSub == '-':
kpIndexCounter = 3*int(kpMain) - 1
elif kpSub == 'o':
kpIndexCounter = 3*int(kpMain)
elif kpSub == '+':
kpIndexCounter = 3*int(kpMain) + 1
# load true data from corresponding support file (note that Python indexing starts at 0 and Fortran indexing
# starts at 1, relevant for Kp index counter)
# Midnight references were recomputed for #1693 by interpolating the mean table's
# log10(flux) values in log(energy), rather than selecting the lower energy bin.
filename = 'FluxData_' + str(kpIndexCounter+1) + '_' + str("%.2f" % param2_LT) + '.txt'
filepath = path + '/Support/' + filename
trueEnergyData = np.array([0.0] * messaging.MAX_PLASMA_FLUX_SIZE)
trueElectronFluxData = np.array([0.0] * messaging.MAX_PLASMA_FLUX_SIZE)
trueIonFluxData = np.array([0.0] * messaging.MAX_PLASMA_FLUX_SIZE)
with open(filepath, 'r') as file:
rows = np.loadtxt(file, delimiter=",", unpack=False)
# true flux data provided by Denton is in Units of [cm^-2 s^-1 sr^-2 eV^-1], but DentonFluxModel converts it to
# [m^-2 s^-1 sr^-2 eV^-1]. Need to multiply by 1e4
trueEnergyData[0:module.numOutputEnergies] = rows[0]
trueElectronFluxData[0:module.numOutputEnergies] = 10.**(rows[1]) * 1e4
trueIonFluxData[0:module.numOutputEnergies] = 10.**(rows[2]) * 1e4
# make sure module output data is correct
paramsString = ' for Kp-Index={}, LT={}, accuracy={}'.format(
str(param1_Kp),
str(param2_LT),
str(accuracy))
np.testing.assert_allclose(energyData,
trueEnergyData,
rtol=0,
atol=accuracy,
err_msg=('Variable: energyData,' + paramsString),
verbose=True)
np.testing.assert_allclose(electronFluxData,
trueElectronFluxData,
rtol=0,
atol=accuracy,
err_msg=('Variable: electronFluxData,' + paramsString),
verbose=True)
np.testing.assert_allclose(ionFluxData,
trueIonFluxData,
rtol=0,
atol=accuracy,
err_msg=('Variable: ionFluxData,' + paramsString),
verbose=True)
plt.figure(1)
fig = plt.gcf()
ax = fig.gca()
plt.semilogy(energyData[0:module.numOutputEnergies], electronFluxData[0:module.numOutputEnergies])
plt.xlabel('Energy [eV]')
plt.ylabel('Electron Flux [e$^{-}$ cm$^{-2}$ s$^{-1}$ str$^{-1}$ eV$^{-1}$]')
if show_plots:
plt.show()
if __name__ == "__main__":
test_dentonFluxModel(False, '4-', LTs[1], z_offsets[1], r_EN_Ns[1], 1e2)