''' '''
'''
 ISC License
 Copyright (c) 2016-2018, 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.
'''
import sys, os, inspect
import numpy
import pytest
import math
from Basilisk.utilities import SimulationBaseClass, macros, unitTestSupport
from Basilisk.simulation.coarse_sun_sensor import coarse_sun_sensor
import matplotlib.pyplot as plt
from Basilisk.fswAlgorithms.sunlineSuKF import sunlineSuKF  # import the module that is to be tested
from Basilisk.fswAlgorithms.cssComm import cssComm
from Basilisk.fswAlgorithms.fswMessages import fswMessages
import SunLineSuKF_test_utilities as FilterPlots
def setupFilterData(filterObject, initialized):
    filterObject.navStateOutMsgName = "sunline_state_estimate"
    filterObject.filtDataOutMsgName = "sunline_filter_data"
    filterObject.cssDataInMsgName = "css_sensors_data"
    filterObject.cssConfigInMsgName = "css_config_data"
    filterObject.alpha = 0.02
    filterObject.beta = 2.0
    filterObject.kappa = 0.0
    if initialized:
        filterObject.stateInit = [0.0, 0.0, 1.0, 0.0, 0.0, 1.]
        filterObject.filterInitialized = 1
    else:
        filterObject.filterInitialized = 0
    filterObject.covarInit = [1., 0.0, 0.0, 0.0, 0.0, 0.0,
                          0.0, 1., 0.0, 0.0, 0.0, 0.0,
                          0.0, 0.0, 1., 0.0, 0.0, 0.0,
                          0.0, 0.0, 0.0, 0.02, 0.0, 0.0,
                          0.0, 0.0, 0.0, 0.0, 0.02, 0.0,
                          0.0, 0.0, 0.0, 0.0, 0.0, 1E-4]
    qNoiseIn = numpy.identity(6)
    qNoiseIn[0:3, 0:3] = qNoiseIn[0:3, 0:3]*0.001*0.001
    qNoiseIn[3:5, 3:5] = qNoiseIn[3:5, 3:5]*0.001*0.001
    qNoiseIn[5, 5] = qNoiseIn[5, 5]*0.0000002*0.0000002
    filterObject.qNoise = qNoiseIn.reshape(36).tolist()
    filterObject.qObsVal = 0.002
    filterObject.sensorUseThresh = 0.0
# 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() # need to update how the RW states are defined
# provide a unique test method name, starting with test_
[docs]@pytest.mark.parametrize("kellyOn", [
    (False),
    (True)
])
def test_all_sunline_kf(show_plots, kellyOn):
    """Module Unit Test"""
    [testResults, testMessage] = SwitchMethods()
    assert testResults < 1, testMessage
    [testResults, testMessage] = StatePropSunLine(show_plots)
    assert testResults < 1, testMessage
    [testResults, testMessage] = StateUpdateSunLine(show_plots, kellyOn)
    assert testResults < 1, testMessage
    [testResults, testMessage] = FaultScenarios()
    assert testResults < 1, testMessage 
def SwitchMethods():
    # The __tracebackhide__ setting influences pytest showing of tracebacks:
    # the mrp_steering_tracking() function will not be shown unless the
    # --fulltrace command line option is specified.
    __tracebackhide__ = True
    testFailCount = 0  # zero unit test result counter
    testMessages = []  # create empty list to store test log messages
    ###################################################################################
    ## Test the sunlineSEKFComputeDCM_BS method
    ###################################################################################
    numStates = 6
    inputStates = [2, 1, 0.75, 0.1, 0.4, 0.]
    sunheading = inputStates[:3]
    bvec1 = [0., 1., 0.]
    b1 = numpy.array(bvec1)
    dcm_BS = [1., 0., 0.,
             0., 1., 0.,
             0., 0., 1.]
    # Fill in expected values for test
    DCM_exp = numpy.zeros([3,3])
    W_exp = numpy.eye(numStates)
    DCM_exp[:, 0] = numpy.array(inputStates[0:3]) / (numpy.linalg.norm(numpy.array(inputStates[0:3])))
    DCM_exp[:, 1] = numpy.cross(DCM_exp[:, 0], b1) / numpy.linalg.norm(numpy.array(numpy.cross(DCM_exp[:, 0], b1)))
    DCM_exp[:, 2] = numpy.cross(DCM_exp[:, 0], DCM_exp[:, 1]) / numpy.linalg.norm(
        numpy.cross(DCM_exp[:, 0], DCM_exp[:, 1]))
    # Fill in the variables for the test
    dcm = sunlineSuKF.new_doubleArray(3 * 3)
    for j in range(9):
        sunlineSuKF.doubleArray_setitem(dcm, j, dcm_BS[j])
    sunlineSuKF.sunlineSuKFComputeDCM_BS(sunheading, bvec1, dcm)
    switchBSout = []
    dcmOut = []
    for j in range(9):
        dcmOut.append(sunlineSuKF.doubleArray_getitem(dcm, j))
    errorNorm = numpy.zeros(1)
    errorNorm[0] = numpy.linalg.norm(DCM_exp - numpy.array(dcmOut).reshape([3, 3]))
    for i in range(len(errorNorm)):
        if (errorNorm[i] > 1.0E-10):
            testFailCount += 1
            testMessages.append("Frame switch failure \n")
    ###################################################################################
    ## Test the Switching method
    ###################################################################################
    inputStates = [2,1,0.75,0.1,0.4, 1.]
    bvec1 = [0.,1.,0.]
    b1 = numpy.array(bvec1)
    covar = [1., 0., 0., 1., 0., 0.,
             0., 1., 0., 0., 1., 0.,
             0., 0., 1., 0., 0., 1.,
             1., 0., 0., 1., 0., 0.,
             0., 1., 0., 0., 1., 0.,
             0., 0., 1., 0., 0., 1.]
    noise =0.01
    # Fill in expected values for test
    DCM_BSold = numpy.zeros([3,3])
    DCM_BSnew = numpy.zeros([3,3])
    Switch = numpy.eye(numStates)
    SwitchBSold = numpy.eye(numStates)
    SwitchBSnew = numpy.eye(numStates)
    DCM_BSold[:,0] = numpy.array(inputStates[0:3])/(numpy.linalg.norm(numpy.array(inputStates[0:3])))
    DCM_BSold[:,1] = numpy.cross(DCM_BSold[:,0], b1)/numpy.linalg.norm(numpy.array(numpy.cross(DCM_BSold[:,0], b1)))
    DCM_BSold[:,2] = numpy.cross(DCM_BSold[:,0], DCM_BSold[:,1])/numpy.linalg.norm(numpy.cross(DCM_BSold[:,0], DCM_BSold[:,1]))
    SwitchBSold[3:5, 3:5] = DCM_BSold[1:3, 1:3]
    b2 = numpy.array([1.,0.,0.])
    DCM_BSnew[:,0] = numpy.array(inputStates[0:3])/(numpy.linalg.norm(numpy.array(inputStates[0:3])))
    DCM_BSnew[:,1] = numpy.cross(DCM_BSnew[:,0], b2)/numpy.linalg.norm(numpy.array(numpy.cross(DCM_BSnew[:,0], b2)))
    DCM_BSnew[:,2] = numpy.cross(DCM_BSnew[:,0], DCM_BSnew[:,1])/numpy.linalg.norm(numpy.cross(DCM_BSnew[:,0], DCM_BSnew[:,1]))
    SwitchBSnew[3:5, 3:5] = DCM_BSnew[1:3, 1:3]
    DCM_newOld = numpy.dot(DCM_BSnew.T, DCM_BSold)
    Switch[3:5, 3:5] = DCM_newOld[1:3,1:3]
    # Fill in the variables for the test
    bvec = sunlineSuKF.new_doubleArray(3)
    states = sunlineSuKF.new_doubleArray(numStates)
    covarMat = sunlineSuKF.new_doubleArray(numStates * numStates)
    for i in range(3):
        sunlineSuKF.doubleArray_setitem(bvec, i, bvec1[i])
    for i in range(numStates):
        sunlineSuKF.doubleArray_setitem(states, i, inputStates[i])
    for j in range(numStates*numStates):
        sunlineSuKF.doubleArray_setitem(covarMat, j, covar[j])
        # sunlineSEKF.doubleArray_setitem(switchBS, j, switchInput[j])
    sunlineSuKF.sunlineSuKFSwitch(bvec, states, covarMat)
    switchBSout = []
    covarOut = []
    stateOut = []
    bvecOut = []
    for i in range(3):
        bvecOut.append(sunlineSuKF.doubleArray_getitem(bvec, i))
    for i in range(numStates):
        stateOut.append(sunlineSuKF.doubleArray_getitem(states, i))
    for j in range(numStates*numStates):
        covarOut.append(sunlineSuKF.doubleArray_getitem(covarMat, j))
    expectedState = numpy.dot(Switch, numpy.array(inputStates))
    Pk = numpy.array(covar).reshape([numStates, numStates])
    expectedP = numpy.dot(Switch, numpy.dot(Pk, Switch.T))
    errorNorm = numpy.zeros(3)
    errorNorm[0] = numpy.linalg.norm(numpy.array(stateOut) - expectedState)
    errorNorm[1] = numpy.linalg.norm(expectedP - numpy.array(covarOut).reshape([numStates, numStates]))
    errorNorm[2] = numpy.linalg.norm(numpy.array(bvecOut) - b2)
    for i in range(len(errorNorm)):
        if (errorNorm[i] > 1.0E-10):
            testFailCount += 1
            testMessages.append("Frame switch failure \n")
    # print out success message if no error were found
    if testFailCount == 0:
        print("PASSED: " + " SuKF switch tests")
    else:
        print(str(testFailCount) + ' tests failed')
        print(testMessages)
    # return fail count and join into a single string all messages in the list
    # testMessage
    return [testFailCount, ''.join(testMessages)]
def StateUpdateSunLine(show_plots, kellyOn):
    # The __tracebackhide__ setting influences pytest showing of tracebacks:
    # the mrp_steering_tracking() function will not be shown unless the
    # --fulltrace command line option is specified.
    __tracebackhide__ = True
    testFailCount = 0  # zero unit test result counter
    testMessages = []  # create empty list 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
    moduleConfig = sunlineSuKF.SunlineSuKFConfig()
    moduleWrap = unitTestSim.setModelDataWrap(moduleConfig)
    moduleWrap.ModelTag = "sunlineSuKF"
    # Add test module to runtime call list
    unitTestSim.AddModelToTask(unitTaskName, moduleWrap, moduleConfig)
    setupFilterData(moduleConfig, False)
    cssConstelation = fswMessages.CSSConfigFswMsg()
    CSSOrientationList = [
       [0.70710678118654746, -0.5, 0.5],
       [0.70710678118654746, -0.5, -0.5],
       [0.70710678118654746, 0.5, -0.5],
       [0.70710678118654746, 0.5, 0.5],
       [-0.70710678118654746, 0, 0.70710678118654757],
       [-0.70710678118654746, 0.70710678118654757, 0.0],
       [-0.70710678118654746, 0, -0.70710678118654757],
       [-0.70710678118654746, -0.70710678118654757, 0.0],
    ]
    totalCSSList = []
    for CSSHat in CSSOrientationList:
        newCSS = fswMessages.CSSUnitConfigFswMsg()
        newCSS.CBias = 1.0
        newCSS.nHat_B = CSSHat
        totalCSSList.append(newCSS)
    cssConstelation.nCSS = len(CSSOrientationList)
    cssConstelation.cssVals = totalCSSList
    unitTestSupport.setMessage(unitTestSim.TotalSim,
                               unitProcessName,
                               moduleConfig.cssConfigInMsgName,
                               cssConstelation)
    unitTestSim.TotalSim.logThisMessage('sunline_filter_data', testProcessRate)
    # Add the kelly curve coefficients
    if kellyOn:
        kellList = []
        for j in range(len(CSSOrientationList)):
            kellyData = sunlineSuKF.SunlineSuKFCFit()
            kellyData.cssKellFact = 0.05
            kellyData.cssKellPow = 2.
            kellyData.cssRelScale = 1.
            kellList.append(kellyData)
        moduleConfig.kellFits = kellList
    testVector = numpy.array([-0.7, 0.7, 0.0])
    testVector/=numpy.linalg.norm(testVector)
    inputData = cssComm.CSSArraySensorIntMsg()
    dotList = []
    for element in CSSOrientationList:
        dotProd = numpy.dot(numpy.array(element), testVector)/(numpy.linalg.norm(element)*numpy.linalg.norm(testVector))
        dotList.append(dotProd)
    inputData.CosValue = dotList
    inputMessageSize = inputData.getStructSize()
    unitTestSim.TotalSim.CreateNewMessage(unitProcessName,
                                      moduleConfig.cssDataInMsgName,
                                      inputMessageSize,
                                      2)  # number of buffers (leave at 2 as default, don't make zero)
    stateTarget = testVector.tolist()
    stateTarget.extend([0.0, 0.0, 1.])
    # moduleConfig.stateInit = [0.7, 0.7, 0.0, 0.01, 0.001, 1.]
    numStates = len(moduleConfig.stateInit)
    unitTestSim.InitializeSimulation()
    if kellyOn:
        time = 1000
    else:
        time =  500
    for i in range(time):
        unitTestSim.TotalSim.WriteMessageData(moduleConfig.cssDataInMsgName,
                                  inputMessageSize,
                                  unitTestSim.TotalSim.CurrentNanos,
                                  inputData)
        unitTestSim.ConfigureStopTime(macros.sec2nano((i+1)*0.5))
        unitTestSim.ExecuteSimulation()
    stateLog = unitTestSim.pullMessageLogData('sunline_filter_data' + ".state", list(range(numStates)))
    postFitLog = unitTestSim.pullMessageLogData('sunline_filter_data' + ".postFitRes", list(range(8)))
    covarLog = unitTestSim.pullMessageLogData('sunline_filter_data' + ".covar", list(range(numStates*numStates)))
    accuracy = 1.0E-3
    if kellyOn:
        accuracy = 1.0E-2 # 1% Error test for the kelly curves given errors
    for i in range(numStates):
        if(covarLog[-1, i*numStates+1+i] > covarLog[0, i*numStates+1+i]):
            testFailCount += 1
            testMessages.append("Covariance update failure first part")
    if(numpy.arccos(numpy.dot(stateLog[-1, 1:4], stateTarget[0:3])/(numpy.linalg.norm(stateLog[-1, 1:4])*numpy.linalg.norm(stateTarget[0:3]))) > accuracy):
        print(numpy.arccos(numpy.dot(stateLog[-1, 1:4], stateTarget[0:3])/(numpy.linalg.norm(stateLog[-1, 1:4])*numpy.linalg.norm(stateTarget[0:3]))))
        testFailCount += 1
        testMessages.append("Pointing update failure")
    if(numpy.linalg.norm(stateLog[-1, 4:7] - stateTarget[3:6]) > accuracy):
        print(numpy.linalg.norm(stateLog[-1,  4:7] - stateTarget[3:6]))
        testFailCount += 1
        testMessages.append("Rate update failure")
    if(abs(stateLog[-1, 6] - stateTarget[5]) > accuracy):
        print(abs(stateLog[-1, 6] - stateTarget[5]))
        testFailCount += 1
        testMessages.append("Sun Intensity update failure")
    testVector = numpy.array([-0.7, 0.75, 0.0])
    testVector /= numpy.linalg.norm(testVector)
    inputData = cssComm.CSSArraySensorIntMsg()
    dotList = []
    for element in CSSOrientationList:
        dotProd = numpy.dot(numpy.array(element), testVector)
        dotList.append(dotProd)
    inputData.CosValue = dotList
    for i in range(time):
        if i > 20:
            unitTestSim.TotalSim.WriteMessageData(moduleConfig.cssDataInMsgName,
                                      inputMessageSize,
                                      unitTestSim.TotalSim.CurrentNanos,
                                      inputData)
        unitTestSim.ConfigureStopTime(macros.sec2nano((i+time+1)*0.5))
        unitTestSim.ExecuteSimulation()
    stateLog = unitTestSim.pullMessageLogData('sunline_filter_data' + ".state", list(range(numStates)))
    postFitLog = unitTestSim.pullMessageLogData('sunline_filter_data' + ".postFitRes", list(range(8)))
    covarLog = unitTestSim.pullMessageLogData('sunline_filter_data' + ".covar", list(range(numStates*numStates)))
    stateTarget = testVector.tolist()
    stateTarget.extend([0.0, 0.0, 1.0])
    for i in range(numStates):
        if(covarLog[-1, i*numStates+1+i] > covarLog[0, i*numStates+1+i]):
            print(covarLog[-1, i*numStates+1+i] - covarLog[0, i*numStates+1+i])
            testFailCount += 1
            testMessages.append("Covariance update failure")
    if(numpy.arccos(numpy.dot(stateLog[-1, 1:4], stateTarget[0:3])/(numpy.linalg.norm(stateLog[-1, 1:4])*numpy.linalg.norm(stateTarget[0:3]))) > accuracy):
        print(numpy.arccos(numpy.dot(stateLog[-1, 1:4], stateTarget[0:3])/(numpy.linalg.norm(stateLog[-1, 1:4])*numpy.linalg.norm(stateTarget[0:3]))))
        testFailCount += 1
        testMessages.append("Pointing update failure")
    if(numpy.linalg.norm(stateLog[-1, 4:7] - stateTarget[3:6]) > accuracy):
        print(numpy.linalg.norm(stateLog[-1,  4:7] - stateTarget[3:6]))
        testFailCount += 1
        testMessages.append("Rate update failure")
    if(abs(stateLog[-1, 6] - stateTarget[5]) > accuracy):
        print(abs(stateLog[-1, 6] - stateTarget[5]))
        testFailCount += 1
        testMessages.append("Sun Intensity update failure")
    FilterPlots.StateCovarPlot(stateLog, covarLog, show_plots)
    FilterPlots.PostFitResiduals(postFitLog, moduleConfig.qObsVal, show_plots)
    # print out success message if no error were found
    if testFailCount == 0:
        print("PASSED: " + moduleWrap.ModelTag + " state update")
    else:
        print(testMessages)
    # return fail count and join into a single string all messages in the list
    # testMessage
    return [testFailCount, ''.join(testMessages)]
def StatePropSunLine(show_plots):
    # The __tracebackhide__ setting influences pytest showing of tracebacks:
    # the mrp_steering_tracking() function will not be shown unless the
    # --fulltrace command line option is specified.
    __tracebackhide__ = True
    testFailCount = 0  # zero unit test result counter
    testMessages = []  # create empty list 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
    moduleConfig = sunlineSuKF.SunlineSuKFConfig()
    moduleWrap = unitTestSim.setModelDataWrap(moduleConfig)
    moduleWrap.ModelTag = "sunlineSuKF"
    # Add test module to runtime call list
    unitTestSim.AddModelToTask(unitTaskName, moduleWrap, moduleConfig)
    setupFilterData(moduleConfig, True)
    numStates = 6
    unitTestSim.TotalSim.logThisMessage('sunline_filter_data', testProcessRate)
    unitTestSim.InitializeSimulation()
    unitTestSim.ConfigureStopTime(macros.sec2nano(8000.0))
    unitTestSim.ExecuteSimulation()
    stateLog = unitTestSim.pullMessageLogData('sunline_filter_data' + ".state", list(range(numStates)))
    postFitLog = unitTestSim.pullMessageLogData('sunline_filter_data' + ".postFitRes", list(range(8)))
    covarLog = unitTestSim.pullMessageLogData('sunline_filter_data' + ".covar", list(range(numStates*numStates)))
    FilterPlots.StateCovarPlot(stateLog, covarLog, show_plots)
    FilterPlots.PostFitResiduals(postFitLog, moduleConfig.qObsVal, show_plots)
    for i in range(numStates):
        if(abs(stateLog[-1, i+1] - stateLog[0, i+1]) > 1.0E-10):
            print(abs(stateLog[-1, i+1] - stateLog[0, i+1]))
            testFailCount += 1
            testMessages.append("State propagation failure")
    # print out success message if no error were found
    if testFailCount == 0:
        print("PASSED: " + moduleWrap.ModelTag + " state propagation")
    # return fail count and join into a single string all messages in the list
    # testMessage
    return [testFailCount, ''.join(testMessages)]
def FaultScenarios():
    # The __tracebackhide__ setting influences pytest showing of tracebacks:
    # the mrp_steering_tracking() function will not be shown unless the
    # --fulltrace command line option is specified.
    __tracebackhide__ = True
    testFailCount = 0  # zero unit test result counter
    testMessages = []  # create empty list 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))
    # Clean methods for Measurement and Time Updates
    moduleConfigClean1 = sunlineSuKF.SunlineSuKFConfig()
    moduleConfigClean1.numStates = 6
    moduleConfigClean1.countHalfSPs = moduleConfigClean1.numStates
    moduleConfigClean1.state = [0., 0., 0., 0., 0., 0.]
    moduleConfigClean1.statePrev = [0., 0., 0., 0., 0., 0.]
    moduleConfigClean1.sBar = [0., 0., 0., 0., 0., 0.,
                               0., 0., 0., 0., 0., 0.,
                               0., 0., 0., 0., 0., 0.,
                               0., 0., 0., 0., 0., 0.,
                               0., 0., 0., 0., 0., 0.,
                               0., 0., 0., 0., 0., 0.]
    moduleConfigClean1.sBarPrev = [1., 0., 0., 0., 0., 0.,
                                   0., 1., 0., 0., 0., 0.,
                                   0., 0., 1., 0., 0., 0.,
                                   0., 0., 0., 1., 0., 0.,
                                   0., 0., 0., 0., 1., 0.,
                                   0., 0., 0., 0., 0., 1.]
    moduleConfigClean1.covar = [0., 0., 0., 0., 0., 0.,
                                0., 0., 0., 0., 0., 0.,
                                0., 0., 0., 0., 0., 0.,
                                0., 0., 0., 0., 0., 0.,
                                0., 0., 0., 0., 0., 0.,
                                0., 0., 0., 0., 0., 0.]
    moduleConfigClean1.covarPrev = [2., 0., 0., 0., 0., 0.,
                                    0., 2., 0., 0., 0., 0.,
                                    0., 0., 2., 0., 0., 0.,
                                    0., 0., 0., 2., 0., 0.,
                                    0., 0., 0., 0., 2., 0.,
                                    0., 0., 0., 0., 0., 2.]
    sunlineSuKF.sunlineSuKFCleanUpdate(moduleConfigClean1)
    if numpy.linalg.norm(numpy.array(moduleConfigClean1.covarPrev) - numpy.array(moduleConfigClean1.covar)) > 1E10:
        testFailCount += 1
        testMessages.append("sunlineSuKFClean Covar failed")
    if numpy.linalg.norm(numpy.array(moduleConfigClean1.statePrev) - numpy.array(moduleConfigClean1.state)) > 1E10:
        testFailCount += 1
        testMessages.append("sunlineSuKFClean States failed")
    if numpy.linalg.norm(numpy.array(moduleConfigClean1.sBar) - numpy.array(moduleConfigClean1.sBarPrev)) > 1E10:
        testFailCount += 1
        testMessages.append("sunlineSuKFClean sBar failed")
    moduleConfigClean1.navStateOutMsgName = "sunline_state_estimate"
    moduleConfigClean1.filtDataOutMsgName = "sunline_filter_data"
    moduleConfigClean1.cssDataInMsgName = "css_sensors_data"
    moduleConfigClean1.cssConfigInMsgName = "css_config_data"
    moduleConfigClean1.alpha = 0.02
    moduleConfigClean1.beta = 2.0
    moduleConfigClean1.kappa = 0.0
    moduleConfigClean1.wC = [-1] * (moduleConfigClean1.numStates * 2 + 1)
    moduleConfigClean1.wM = [-1] * (moduleConfigClean1.numStates * 2 + 1)
    retTime = sunlineSuKF.sunlineSuKFTimeUpdate(moduleConfigClean1, 1)
    retMease = sunlineSuKF.sunlineSuKFMeasUpdate(moduleConfigClean1, 1)
    if retTime == 0:
        testFailCount += 1
        testMessages.append("Failed to catch bad Update and clean in Time update")
    if retMease == 0:
        testFailCount += 1
        testMessages.append("Failed to catch bad Update and clean in Meas update")
    # print out success message if no error were found
    if testFailCount == 0:
        print("PASSED: fault detection test")
    # return fail count and join into a single string all messages in the list
    # testMessage
    return [testFailCount, ''.join(testMessages)]
if __name__ == "__main__":
    # test_all_sunline_kf(True)
    # StateUpdateSunLine(True, True)
    FaultScenarios()