### Run Integrated Example Script Source: https://avslab.github.io/basilisk/Build/installOnWindows.html After building the project, navigate to the 'basilisk/examples' directory and run an example script to test your setup. This command executes a basic orbit scenario. ```bash (.venv) $ python scenarioBasicOrbit.py ``` -------------------------------- ### Add Optional Examples Dependency Set Source: https://avslab.github.io/basilisk/Support/bskReleaseNotes.html An optional `examples` dependency set is now available for installing example-only Python packages using `pip install "bsk[examples]"`. ```python Added an `examples` optional dependency set so users can install example-only Python packages with `pip install "bsk[examples]"` or `pip install -e ".[examples]"`. ``` -------------------------------- ### Run an integrated example script Source: https://avslab.github.io/basilisk/Build/installOnMacOS.html Execute a tutorial scenario from the examples directory. ```bash (.venv) $ python3 scenarioBasicOrbit.py ``` -------------------------------- ### Run Basilisk Example Script Source: https://avslab.github.io/basilisk/Build/installOnLinux.html Execute an integrated example script to test your Basilisk setup. Ensure you are in the examples directory. ```bash python3 scenarioBasicOrbit.py ``` -------------------------------- ### Install Basilisk with examples Source: https://avslab.github.io/basilisk/Install.html Installs the Basilisk package along with optional Python dependencies required for running example scripts. ```bash pip install "bsk[examples]" ``` -------------------------------- ### Download Basilisk examples Source: https://avslab.github.io/basilisk/Install.html Command to download the repository example files to the local directory. ```bash bskExamples ``` -------------------------------- ### Build and Install Plugin Commands Source: https://avslab.github.io/basilisk/Plugins/writing.html Commands for development installation, wheel creation, and running unit tests. ```bash # Development install pip install --no-build-isolation -e . # Build a distributable wheel python -m build --wheel pip install dist/*.whl # Run unit tests pytest myModule/_UnitTest/ -v ``` -------------------------------- ### bskExamples.main Source: https://avslab.github.io/basilisk/Documentation/utilities/bskExamples.html A script to download all available Basilisk examples from GitHub into a local 'examples' folder. ```APIDOC ## bskExamples.main ### Description Script to download all GitHub Basilisk examples into the local folder called `examples`. ### Method GET (implied) ### Endpoint N/A (Function call) ### Parameters None ### Request Example ```python import bskExamples bskExamples.main() ``` ### Response #### Success Response (200) All example files downloaded to the 'examples' directory. #### Response Example N/A (Function execution) ``` -------------------------------- ### Initialize Environment and Paths Source: https://avslab.github.io/basilisk/_modules/scenarioBskSimAttFeedbackMC.html Setup script environment, file paths, and Basilisk path imports. ```python import inspect import os import matplotlib.pyplot as plt import numpy as np filename = inspect.getframeinfo(inspect.currentframe()).filename fileNameString = os.path.basename(os.path.splitext(__file__)[0]) path = os.path.dirname(os.path.abspath(filename)) from Basilisk import __path__ bskPath = __path__[0] ``` -------------------------------- ### Simulation Results: Basic Setup Source: https://avslab.github.io/basilisk/examples/scenarioAttitudeFeedback2T.html Illustrates simulation results with default parameters, showing initial FSW values and slight performance differences due to message copying. ```python show_plots = True, useUnmodeledTorque = False, useIntGain = False ``` -------------------------------- ### User Guide Example Source: https://avslab.github.io/basilisk/Documentation/fswAlgorithms/opticalNavigation/faultDetection/faultDetection.html Example of how to configure and use the fault detection module in Python. ```APIDOC ## User Guide An example setup is provided here: ```python 1faults = faultDetection.FaultDetectionData() 2faults.sigmaFault = 3 3faults.faultMode = 1 ``` The sigmaFault parameter is the multiplier on the covariances that needs to be passed for the faults to be triggered ``` -------------------------------- ### Run Simulation Setup Source: https://avslab.github.io/basilisk/_modules/scenarioCentralBody.html Initializes a simulation process, adds spacecraft and gravity models, and sets up orbital states. ```python def run(show_plots, useCentral): """ Args: show_plots (bool): Determines if the script should display plots useCentral (bool): Specifies if the planet is the center of the coordinate system """ # Create simulation variable names simTaskName = "simTask" simProcessName = "simProcess" # Create a sim module as an empty container scSim = SimulationBaseClass.SimBaseClass() # # create the simulation process # dynProcess = scSim.CreateNewProcess(simProcessName) # create the dynamics task and specify the integration update time simulationTimeStep = macros.sec2nano(10.) dynProcess.addTask(scSim.CreateNewTask(simTaskName, simulationTimeStep)) # # setup the simulation tasks/objects # # initialize spacecraft object and set properties scObject = spacecraft.Spacecraft() scObject.ModelTag = "spacecraftBody" # add spacecraft object to the simulation process scSim.AddModelToTask(simTaskName, scObject) # setup Gravity Body gravFactory = simIncludeGravBody.gravBodyFactory() planet = gravFactory.createEarth() planet.isCentralBody = useCentral # ensure this is the central gravitational body mu = planet.mu # set up sun gravFactory.createSun() #Set up spice with spice time UTCInit = "2012 MAY 1 00:28:30.0" spiceObject = gravFactory.createSpiceInterface(time=UTCInit, epochInMsg=True) scSim.AddModelToTask(simTaskName, spiceObject) # attach gravity model to spacecraft gravFactory.addBodiesTo(scObject) # # setup orbit and simulation time # # setup the orbit using classical orbit elements oe = orbitalMotion.ClassicElements() rLEO = 7000. * 1000 # meters oe.a = rLEO oe.e = 0.000001 oe.i = 0.0 * macros.D2R oe.Omega = 0.0 * macros.D2R oe.omega = 0.0 * macros.D2R oe.f = 0.0 * macros.D2R rN, vN = orbitalMotion.elem2rv(mu, oe) truth_r = norm(rN) #for test results truth_v = norm(vN) #for test results oe = orbitalMotion.rv2elem(mu, rN, vN) # this stores consistent initial orbit elements wrt ECI frame # # initialize Spacecraft States with the initialization variables # # Spacecraft positions can be input (and integrated) only relative to the "central body" by # using the isCentralBody flag. This is demonstrated in Setup 2. Generally, this is a good # practice because it increases the accuracy of the integration. # # Alternatively, absolute positions and velocities can be input and integrated. # To do so, it is useful to be able to get a planet position and velocity from spice # to be able to modify your spacecraft inputs by these values. This can be done using the # planetStates utility: # ~~~~~~~~~~~~~{.py} # from Basilisk.utilities import planetStates # ~~~~~~~~~~~~~ # Then, the planetPositionVelocity() method can be used to get the needed information if useCentral: scObject.hub.r_CN_NInit = rN # m - r_BN_N scObject.hub.v_CN_NInit = vN # m/s - v_BN_N else: #by default planetstates.planetPositionVelocity returns SSB central ICRS coordinates for the planet at the time # requested. also pck0010.tpc ephemeris file #look in the function for how to use other ephemeris files, reference frames, and observers planetPosition, planetVelocity = planetStates.planetPositionVelocity('EARTH', UTCInit, gravFactory.spiceObject.SPICEDataPath) scObject.hub.r_CN_NInit = rN + array(planetPosition) scObject.hub.v_CN_NInit = vN + array(planetVelocity) # In the above call, the first input is the planet to get the states of and the second is the UTC time # to get the states at. Additional inputs are available in the method documentation. These states can then be added # to the planet-relative states before setting them to the spacecraft initial states # This works without frame rotations because all planet states are given in the spice inertial system relative to the # zero base. Additionally, it is assumed for this script that the Keplerian orbital elements were given relative # to the Earth Centered Inertial Frame which is aligned with the spice inertial frame. # set the simulation time n = np.sqrt(mu / oe.a / oe.a / oe.a) P = 2. * np.pi / n simulationTime = macros.sec2nano(0.75*P) # # Setup data logging before the simulation is initialized # numDataPoints = 100 samplingTime = unitTestSupport.samplingTime(simulationTime, simulationTimeStep, numDataPoints) dataLog = scObject.scStateOutMsg.recorder(samplingTime) plLog = spiceObject.planetStateOutMsgs[0].recorder(samplingTime) scSim.AddModelToTask(simTaskName, dataLog) ``` -------------------------------- ### Initialize scenario_OpNavPointLimb imports Source: https://avslab.github.io/basilisk/_modules/scenario_OpNavPointLimb.html Setup the environment, import Basilisk utilities, and load simulation base classes. ```python # Get current file path import inspect import os import sys import time # Import utilities from Basilisk.utilities import orbitalMotion, macros, unitTestSupport filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) # Import master classes: simulation base class and scenario base class sys.path.append(path + '/..') from BSK_OpNav import BSKSim, BSKScenario import BSK_OpNavDynamics, BSK_OpNavFsw # Import plotting file for your scenario sys.path.append(path + '/../plottingOpNav') import OpNav_Plotting as BSK_plt ``` -------------------------------- ### Manage Basilisk Data and Examples Source: https://avslab.github.io/basilisk/_sources/Build/pipInstall.rst.txt Commands to download large data files or the examples folder after installation. ```bash bskLargeData ``` ```bash .venv/lib/python3.11/site-packages/Basilisk/supportData/EphemerisData ``` ```bash bskExamples ``` -------------------------------- ### Fault Detection Module - User Guide Example Source: https://avslab.github.io/basilisk/_sources/Documentation/fswAlgorithms/opticalNavigation/faultDetection/faultDetection.rst.txt Example of how to set up and use the fault detection module in Python. ```APIDOC ## Fault Detection Module Setup ### Description This section provides an example of how to initialize and configure the `faultDetection` module in Python. ### Method Python Script ### Endpoint N/A (Local Module Usage) ### Parameters #### Request Body - **faults** (object) - Required - An instance of `FaultDetectionData` to configure. - **sigmaFault** (float) - Required - The multiplier on covariances to trigger faults. - **faultMode** (integer) - Required - The fault mode to apply (0, 1, or 2). ### Request Example ```python import faultDetection faults = faultDetection.FaultDetectionData() faults.sigmaFault = 3 faults.faultMode = 1 ``` ### Response This code snippet does not produce a direct API response as it demonstrates local module configuration. ``` -------------------------------- ### Simulation Setup: Basic Configuration Source: https://avslab.github.io/basilisk/_modules/scenarioAttitudeFeedbackRWPower.html Sets up the basic simulation environment, including simulation time and time step. Uses macros for time conversions. ```python simTaskName = "simTask" simProcessName = "simProcess" scSim = SimulationBaseClass.SimBaseClass() simulationTime = macros.min2nano(10.) dynProcess = scSim.CreateNewProcess(simProcessName) simulationTimeStep = macros.sec2nano(.1) dynProcess.addTask(scSim.CreateNewTask(simTaskName, simulationTimeStep)) ``` -------------------------------- ### Skip Optional Example Python Packages Source: https://avslab.github.io/basilisk/Build/installBuild.html Use this command to perform a leaner install by skipping the optional Python dependencies required for Basilisk example scripts. ```bash python3 conanfile.py --examples False ``` -------------------------------- ### Integrate Custom Plugin into Basilisk Simulation Source: https://avslab.github.io/basilisk/_sources/Plugins/overview.rst.txt Example of how to import and use a custom module from an installed plugin within a Basilisk simulation. Ensure the plugin is installed before running. ```python from my_plugin import myModule from Basilisk.utilities import SimulationBaseClass sim = SimulationBaseClass.SimBaseClass() mod = myModule.MyModule() sim.AddModelToTask("task", mod) ``` -------------------------------- ### Run Tutorial Scenario Source: https://avslab.github.io/basilisk/_modules/test_atmoDrag.html Initializes and executes the tutorial simulation scenario. ```python def run(show_plots, orbitCase, planetCase): """Call this routine directly to run the tutorial scenario.""" testFailCount = 0 # zero unit test result counter testMessages = [] # create empty array to store test log messages # Create simulation variable names simTaskName = "simTask" simProcessName = "simProcess" # Create a sim module as an empty container scSim = SimulationBaseClass.SimBaseClass() # create the simulation process dynProcess = scSim.CreateNewProcess(simProcessName) # create the dynamics task and specify the integration update time simulationTimeStep = macros.sec2nano(1.0) dynProcess.addTask(scSim.CreateNewTask(simTaskName, simulationTimeStep)) # Initialize new atmosphere and drag model, add them to task newAtmo = exponentialAtmosphere.ExponentialAtmosphere() atmoTaskName = "atmosphere" newAtmo.ModelTag = "ExpAtmo" projArea = 10.0 # [m^2] dragCoeff = 2.2 # [-] dragEffector = dragDynamicEffector.DragDynamicEffector() dragEffector.ModelTag = "DragEff" ``` -------------------------------- ### Initialize Force and Navigation Modules Source: https://avslab.github.io/basilisk/_modules/scenarioFlybySpice.html Set up the ExtForceTorque and SimpleNav modules. The SimpleNav module requires its input message to be subscribed to the spacecraft's state output message. ```python extFTObject = extForceTorque.ExtForceTorque() sNavObject = simpleNav.SimpleNav() scObject.addDynamicEffector(extFTObject) sNavObject.scStateInMsg.subscribeTo(scObject.scStateOutMsg) ``` -------------------------------- ### Execute Basilisk Example Script Source: https://avslab.github.io/basilisk/examples/scenarioAsteroidArrival.html Run the `scenarioAsteroidArrival.py` script from the command line to start the simulation. ```bash python3 scenarioAsteroidArrival.py ``` -------------------------------- ### SimpleTransmitter User Guide and Setup Source: https://avslab.github.io/basilisk/Documentation/simulation/onboardDataHandling/transmitter/simpleTransmitter.html Instructions on how to set up and use the simpleTransmitter module, including required variables and methods. ```APIDOC ## User Guide This module inherits the user guide from the Module: dataNodeBase base class, but there are several key differences from other Module: dataNodeBase child classes: * Unlike other child classes of Module: dataNodeBase, this module does not require a user to set a nodeDataName * The nodeBaudRate variable should be set to a negative value in order to remove data from the storage unit. * The user must specify a packetSize variable (negative value) in addition to the nodeBaudRate variable * The user must specify the number of buffers numBuffers variable so the transmitter knows how many buffers to search through * The user must specify the storage unit the transmitter should subscribe to using the `addStorageUnitToTransmitter()` method. ### Setup Example 1. **Create a SimpleTransmitter instance:** ```python transmitter = simpleTransmitter.SimpleTransmitter() transmitter.ModelTag = "transmitter" ``` 2. **Set required variables:** ```python transmitter.nodeBaudRate = -16000. # baud transmitter.packetSize = -1E6 # bits transmitter.numBuffers = 2 ``` 3. **Attach storage units:** ```python transmitter.addStorageUnitToTransmitter("msg name") ``` 4. **Add the model to the task:** ```python scenarioSim.AddModelToTask(taskName, transmitter) ``` Follow the Module: partitionedStorageUnit or Module: simpleStorageUnit instructions to add the transmitter to a storage unit. For more information on how to set up and use this module, see the simple data system example: scenarioDataDemo. ``` -------------------------------- ### Initialize Simulation Environment Source: https://avslab.github.io/basilisk/_modules/scenarioSensorThermal.html Sets up the core simulation environment, including the simulation time and process. ```python simTaskName = "simTask" simProcessName = "simProcess" # Create a sim module as an empty container scSim = SimulationBaseClass.SimBaseClass() # Set the simulation time variable used later on simulationTime = macros.min2nano(20.0) # Create the simulation process dynProcess = scSim.CreateNewProcess(simProcessName) # create the dynamics task and specify the integration update time simulationTimeStep = macros.sec2nano(1.0) dynProcess.addTask(scSim.CreateNewTask(simTaskName, simulationTimeStep)) ``` -------------------------------- ### Initialize Simulation Environment Source: https://avslab.github.io/basilisk/_modules/test_PrescribedMotionStateEffector.html Sets up the simulation environment by creating a new process and task. The process rate determines the simulation time step. ```python task_name = "unitTask" process_name = "testProcess" sim = SimulationBaseClass.SimBaseClass() process_rate = macros.sec2nano(0.001) process = sim.CreateNewProcess(process_name) process.addTask(sim.CreateNewTask(task_name, process_rate)) ``` -------------------------------- ### Python Requirements Source: https://avslab.github.io/basilisk/_sources/Build/installOnWindows.rst.txt This file lists the Python package dependencies required for Basilisk. These are automatically checked and installed during the setup process. ```python astropy pytest pytest-cov pytest-mock scipy numpy matplotlib scikit-image scikit-learn shapely pyyaml sphinx sphinx-rtd-theme black flake8 cmake conan conan-center-index requests packaging pybind11 pygubu qtpy PyQt5 PyQt6 PySide2 PySide6 networkx openpyxl xlrd xlwt open3d opencv-python opencv-contrib-python imageio imageio-ffmpeg ffmpeg-python pyglet pyopengl pyqtgraph pyqt-plugins pyqt-tools pyqt-webengine pyqt-datavisualization pyqt-svg pyqt-sip pyqt-uic pyqt-rcc pyqt-designer pyqt-help pyqt-qml pyqt-qml-models pyqt-qml-plugins pyqt-qml-tools pyqt-qml-webengine pyqt-qml-datavisualization pyqt-qml-svg pyqt-qml-sip pyqt-qml-uic pyqt-qml-rcc pyqt-qml-designer pyqt-qml-help PyQt5-sip PyQt5-tools PyQt5-webengine PyQt5-datavisualization PyQt5-svg PyQt5-uic PyQt5-rcc PyQt5-designer PyQt5-help PyQt6-sip PyQt6-tools PyQt6-webengine PyQt6-datavisualization PyQt6-svg PyQt6-uic PyQt6-rcc PyQt6-designer PyQt6-help PySide2-sip PySide2-tools PySide2-webengine PySide2-datavisualization PySide2-svg PySide2-uic PySide2-rcc PySide2-designer PySide2-help PySide6-sip PySide6-tools PySide6-webengine PySide6-datavisualization PySide6-svg PySide6-uic PySide6-rcc PySide6-designer PySide6-help ``` -------------------------------- ### Configure Camera Module in Python Source: https://avslab.github.io/basilisk/Documentation/simulation/sensors/camera/camera.html Example setup for the Camera module, including message subscription and noise parameter configuration. ```python 1moduleConfig.imageInMsg.subscribeTo(inputCamMsg) 2 3moduleConfig.filename = "" 4moduleConfig.saveImages = 0 5# If images are to be saved, add the directory to which they 6should be saved 7#moduleConfig.saveDir = '/'.join(imagePath.split('/')[:-1]) + '/' 8 9#Camera config values 10moduleConfig.cameraIsOn = 1 11moduleConfig.sigma_CB = [0,0,1] 12 13#Noise Values 14moduleConfig.gaussian = 2 15moduleConfig.darkCurrent = 1 16moduleConfig.saltPepper = 2 17moduleConfig.cosmicRays = 1 18moduleConfig.blurParam = 3 19moduleConfig.hsv = [30*macros.D2R, 0, 0] ``` -------------------------------- ### Run Simulation Setup Source: https://avslab.github.io/basilisk/_modules/scenarioRendezVous.html Sets up the simulation environment, including creating processes, tasks, spacecraft objects, and gravitational bodies. This function initializes the simulation parameters and adds models to the simulation task. ```python def run(show_plots): """ The scenarios can be run with the followings setups parameters: Args: show_plots (bool): Determines if the script should display plots """ # Create simulation variable names simTaskName = "simTask" simProcessName = "simProcess" # Create a sim module as an empty container scSim = SimulationBaseClass.SimBaseClass() scSim.SetProgressBar(True) # set the simulation time variable used later on simulationTime = 0 # # create the simulation process # dynProcess = scSim.CreateNewProcess(simProcessName) # create the dynamics task and specify the integration update time simulationTimeStep = macros.sec2nano(1) dynProcess.addTask(scSim.CreateNewTask(simTaskName, simulationTimeStep)) # # setup the simulation tasks/objects # # initialize servicer spacecraft object and set properties scObject = spacecraft.Spacecraft() scObject.ModelTag = "servicer" # define the simulation inertia I = [900., 0., 0., 0., 800., 0., 0., 0., 600.] scObject.hub.mHub = 750.0 # kg - spacecraft mass scObject.hub.IHubPntBc_B = unitTestSupport.np2EigenMatrix3d(I) # create the debris object states scObject2 = spacecraft.Spacecraft() scObject2.ModelTag = "debris" I2 = [600., 0., 0., 0., 650., 0., 0., 0, 450.] scObject2.hub.mHub = 350.0 # kg scObject2.hub.IHubPntBc_B = unitTestSupport.np2EigenMatrix3d(I2) # add spacecraft object to the simulation process scSim.AddModelToTask(simTaskName, scObject, 1) scSim.AddModelToTask(simTaskName, scObject2, 2) # clear prior gravitational body and SPICE setup definitions gravFactory = simIncludeGravBody.gravBodyFactory() # setup Earth Gravity Body # earth = gravFactory.createEarth() # earth.isCentralBody = True # ensure this is the central gravitational body gravBodies = gravFactory.createBodies('sun', 'earth') gravBodies['earth'].isCentralBody = True mu = gravBodies['earth'].mu sunIdx = 0 earthIdx = 1 # attach gravity model to spacecraft gravFactory.addBodiesTo(scObject) gravFactory.addBodiesTo(scObject2) # setup SPICE interface for celestial objects timeInitString = "2022 MAY 1 00:28:30.0" spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) spiceObject.zeroBase = 'Earth' scSim.AddModelToTask(simTaskName, spiceObject) # # add RW devices # # Make a fresh RW factory instance, this is critical to run multiple times ``` -------------------------------- ### Run Basilisk Tutorial Scenario Source: https://avslab.github.io/basilisk/_sources/Build/installOnWindows.rst.txt Executes a basic orbit scenario to verify the installation. ```bash (.venv) $ python scenarioBasicOrbit.py ``` -------------------------------- ### Get Basilisk Module Path Source: https://avslab.github.io/basilisk/_modules/scenarioBskLog.html This Python code snippet determines the absolute path of the Basilisk installation directory by inspecting the current script's file path. It's useful for locating Basilisk modules or resources relative to the installation. ```python # # 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. # r""" Overview -------- This scenario demonstrates how to set up run a Basilisk simulation and change the default verbosity of ``bskLog`` methods. The default verbosity is set to DEBUG, which means all ``bskLog`` call print the associated information. More information about using ``bskLog`` and changing its verbosity can be found in :ref:`bskLogging`. """ # # Unit Test Script # Module Name: cModuleTemplateParametrized # Author: (First Name) (Last Name) # Creation Date: Month Day, Year # import inspect import os filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) bskName = 'Basilisk' splitPath = path.split(bskName) ``` -------------------------------- ### Get Basilisk Path Source: https://avslab.github.io/basilisk/_modules/scenarioSpacecraftLocation.html Retrieves the installation path of the Basilisk library. This is often used to locate supporting data files or modules. ```python from Basilisk import __path__ bskPath = __path__[0] ``` -------------------------------- ### Windows Direct Build Example Source: https://avslab.github.io/basilisk/Build/installBuildConan.html This example shows a direct build on Windows using Visual Studio. Replace placeholders with your specific MSVC version and architecture. ```bash cmake -G "Visual Studio Win" ../src -DCMAKE_BUILD_TYPE=Release cmake --build . --target ALL_BUILD --config Release ``` -------------------------------- ### Setup Simulation Environment Source: https://avslab.github.io/basilisk/_modules/test_gravitySpacecraft.html Initializes a simulation environment, including creating a process and a task with a specified integration time. This sets up the basic structure for running simulations. ```python testFailCount = 0 # zero unit test result counter testMessages = [] # create empty list to store test log messages ``` ```python unitTaskName = "unitTask" # arbitrary name (don't change) unitProcessName = "TestProcess" # arbitrary name (don't change) unitTestSim = SimulationBaseClass.SimBaseClass() DynUnitTestProc = unitTestSim.CreateNewProcess(unitProcessName) intTime = 30.0 DynUnitTestProc.addTask( unitTestSim.CreateNewTask(unitTaskName, macros.sec2nano(intTime)) ) ``` -------------------------------- ### Main Script to Download Basilisk Examples in Python Source: https://avslab.github.io/basilisk/_modules/bskExamples.html The main function to initiate the download of all Basilisk examples from GitHub. It sets the API URL and destination folder, then calls the recursive processing function. Provides status messages and a note about installing 'pytest'. ```python def main(): """ Script to download all GitHub Basilisk examples into the local folder called ``examples``. """ # Display the task message print(f"{statusColor}Task:{endColor} Downloading BSK examples folder") # GitHub API URL for the target folder github_api_url = "https://api.github.com/repos/AVSLab/basilisk/contents/examples" destination_folder = "./examples" process_github_folder(github_api_url, destination_folder) print(f"{statusColor}Status:{endColor} Download completed") print(f"{warningColor}Note:{endColor} Ensure you have the python package {warningColor}pytest{endColor} installed to be able to run the example scripts.") # Main execution if __name__ == "__main__": main() ``` -------------------------------- ### Setup SPICE Interface Source: https://avslab.github.io/basilisk/_modules/scenarioPowerDemo.html Configures the SPICE interface for solar system body ephemeris data. The 'timeInitString' defines the simulation start time. ```python # setup Spice interface for some solar system bodies timeInitString = '2021 MAY 04 07:47:48.965 (UTC)' spiceObject = gravFactory.createSpiceInterface(time=timeInitString) scenarioSim.AddModelToTask(taskName, spiceObject, -1) # store planet and sun msgs plMsg = spiceObject.planetStateOutMsgs[0] sunMsg = spiceObject.planetStateOutMsgs[1] ``` -------------------------------- ### Get Thruster Configuration Message Source: https://avslab.github.io/basilisk/_modules/simIncludeThruster.html Generates and returns a configuration message payload (FSW THRArrayConfigMsg) that reflects the current setup of all thruster devices. ```APIDOC ## GET /thruster/configMessage ### Description Retrieves a configuration message (THRArrayConfigMsgPayload) summarizing the current state and parameters of all configured thruster devices. ### Method GET ### Endpoint /thruster/configMessage ### Parameters None ### Request Example ``` GET /thruster/configMessage ``` ### Response #### Success Response (200) - **thrMessage** (object) - A THRArrayConfigMsgPayload object containing the configuration details of all thrusters. #### Response Example ```json { "thrMessage": { "numThrusters": 5, "thrusterSettings": [ { ... settings for thruster 1 ... }, { ... settings for thruster 2 ... }, ... ] } } ``` ``` -------------------------------- ### Initialize Simulation Environment Source: https://avslab.github.io/basilisk/_modules/scenarioAlbedo.html Sets up the core simulation environment by creating a simulation process and task with a specified time step. Handles default time step if none is provided. ```python simTaskName = "simTask" simProcessName = "simProcess" # Create a sim module as an empty container scSim = SimulationBaseClass.SimBaseClass() # Create the simulation process if simTimeStep is None: simulationTimeStep = macros.sec2nano(10.0) else: simulationTimeStep = macros.sec2nano(simTimeStep) dynProcess = scSim.CreateNewProcess(simProcessName) dynProcess.addTask(scSim.CreateNewTask(simTaskName, simulationTimeStep)) ``` -------------------------------- ### Clear Thruster Setup Source: https://avslab.github.io/basilisk/_modules/fswSetupThrusters.html Resets the global thruster list, effectively clearing all previously configured thrusters. Use this to start a new thruster configuration. ```python def clearSetup(): global thrList thrList = [] return ``` -------------------------------- ### Initialize Simulation Environment Source: https://avslab.github.io/basilisk/_modules/scenarioCustomGravBody.html Sets up the simulation environment by creating a simulation base class instance, defining process and task names, and setting simulation time parameters. ```python simTaskName = "simTask" simProcessName = "simProcess" scSim = SimulationBaseClass.SimBaseClass() dynProcess = scSim.CreateNewProcess(simProcessName) simulationTimeStep = macros.sec2nano(10.0) simulationTime = macros.min2nano(1120.0) dynProcess.addTask(scSim.CreateNewTask(simTaskName, simulationTimeStep)) ``` -------------------------------- ### Update Thruster Setup Script Source: https://avslab.github.io/basilisk/_sources/Support/bskReleaseNotes.rst.txt This example shows how to update a script to use the new factory class for setting up Thrusters. This is necessary due to changes in the simIncludeThruster helper function. ```python from Basilisk.simulation import simIncludeThruster # Old method (will break) # thrusterFactory.createThruster(thrusterConf) # New method thrusterFactory = simIncludeThruster.thrusterFactory() thrusterConf = thrusterFactory.loadThrusterConfig(thrusterName) thrusterFactory.createThruster(thrusterConf) ``` -------------------------------- ### Hinged Rigid Body Motor API Source: https://avslab.github.io/basilisk/Documentation/simulation/dynamics/hingedRigidBodyMotor/hingedRigidBodyMotor.html This section details the hingedRigidBodyMotor module, including its executive summary, message connections, detailed model description, and user guide for setup and configuration. ```APIDOC ## Module: hingedRigidBodyMotor ### Executive Summary Calculates a motor torque given a sensed and reference hinged rigid body state using a simple PD control law. ### Message Connection Descriptions The following table lists all the module input and output messages. The module msg connection is set by the user from python. The msg type contains a link to the message structure definition, while the description provides information on what this message is used for. Module I/O Messages | Msg Variable Name | Msg Type | Description | | ----------------------------- | ------------------------- | -------------------------------------------- | | hingedBodyStateSensedInMsg | HingedRigidBodyMsgPayload | sensed rigid body state (theta, theta dot) | | hingedBodyStateReferenceInMsg | HingedRigidBodyMsgPayload | reference hinged rigid body state (theta, theta dot) | | motorTorqueOutMsg | ArrayMotorTorqueMsgPayload| motor torque on hinged rigid body | ### Detailed Model Description This module takes in a reference angle and angle rate, as well as a sensed angle and angle rate, and calculates the motor torque according to: u = -K(θs - θr) - P(θ̇s - θ̇r) K and P are the constant gains. Both should be set to positive values. ### User Guide This section contains a conceptual overview of the code and an example for the prospective user. #### Module Setup The interface module is created in python using: ```python 1testModule = hingedRigidBodyMotor.hingedRigidBodyMotor() 2testModule.ModelTag = "hingedRigidBodyMotor" ``` A sample setup is done using: ```python 1testModule.K = 1 # proportional gain constant 2testModule.P = 1 # derivative gain constant ``` If K and P are not set, they default to 0. ### Class Definition: HingedRigidBodyMotor ```cpp class HingedRigidBodyMotor : public SysModel { // ... public: HingedRigidBodyMotor(); ~HingedRigidBodyMotor(); void Reset(uint64_t CurrentSimNanos); void UpdateState(uint64_t CurrentSimNanos); double K; // gain on theta double P; // gain on theta dot ReadFunctor hingedBodyStateSensedInMsg; ReadFunctor hingedBodyStateReferenceInMsg; Message motorTorqueOutMsg; BSKLogger bskLogger; // BSK Logging }; ``` **Constructor:** `HingedRigidBodyMotor()` Initializes the module with default variable values. **Destructor:** `~HingedRigidBodyMotor()` Cleans up module resources. **Reset Method:** `Reset(uint64_t CurrentSimNanos)` Resets the module and checks for required input message connections. **Update State Method:** `UpdateState(uint64_t CurrentSimNanos)` Calculates the motor torque on a hinged rigid body using a simple PD control law. ``` -------------------------------- ### Initialize scenario environment Source: https://avslab.github.io/basilisk/_modules/scenario_FaultList.html Setup script paths and import necessary Basilisk modules for dynamics, flight software, and fault handling. ```python # Get current file path import inspect import os import sys import numpy as np from Basilisk.utilities import macros, orbitalMotion filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) # Import master classes: simulation base class and scenario base class sys.path.append(path + '/../') sys.path.append(path + '/../models') sys.path.append(path + '/../plotting') import BSK_Dynamics import BSK_Fsw import BSK_Plotting as BSK_plt from BSK_masters import BSKScenario, BSKSim import BSK_Faults ``` -------------------------------- ### Configure Basilisk Camera Module Source: https://avslab.github.io/basilisk/_sources/Documentation/simulation/sensors/camera/camera.rst.txt Example setup for the camera module, including input message subscription and various corruption parameter settings. Values of 0 disable specific corruption types. ```python moduleConfig.imageInMsg.subscribeTo(inputCamMsg) moduleConfig.filename = "" moduleConfig.saveImages = 0 # If images are to be saved, add the directory to which they should be saved #moduleConfig.saveDir = '/'.join(imagePath.split('/')[:-1]) + '/' #Camera config values moduleConfig.cameraIsOn = 1 moduleConfig.sigma_CB = [0,0,1] #Noise Values moduleConfig.gaussian = 2 moduleConfig.darkCurrent = 1 moduleConfig.saltPepper = 2 moduleConfig.cosmicRays = 1 moduleConfig.blurParam = 3 moduleConfig.hsv = [30*macros.D2R, 0, 0] ``` -------------------------------- ### Simulation Setup and Execution Source: https://avslab.github.io/basilisk/_modules/scenarioAttitudeConstrainedManeuver.html Initial imports and the run function definition for the simulation. ```python import os import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms import numpy as np from Basilisk import __path__ from Basilisk.architecture import messaging from Basilisk.fswAlgorithms import (mrpFeedback, attTrackingError, constrainedAttitudeManeuver, rwMotorTorque) from Basilisk.simulation import (reactionWheelStateEffector, simpleNav, spacecraft, boreAngCalc) from Basilisk.utilities import (SimulationBaseClass, macros, orbitalMotion, simIncludeGravBody, simIncludeRW, unitTestSupport, vizSupport) bskPath = __path__[0] fileName = os.path.basename(os.path.splitext(__file__)[0]) def run(show_plots, use2SunSensors, starTrackerFov, sunSensorFov, attitudeSetCase): # Create simulation variable names simTaskName = "simTask" simProcessName = "simProcess" # Create a sim module as an empty container scSim = SimulationBaseClass.SimBaseClass() scSim.SetProgressBar(False) # create the simulation process dynProcess = scSim.CreateNewProcess(simProcessName) # create the dynamics task and specify the simulation time and integration update time simulationTime = macros.min2nano(3.5) simulationTimeStep = macros.sec2nano(0.01) dynProcess.addTask(scSim.CreateNewTask(simTaskName, simulationTimeStep)) # # setup the simulation tasks/objects ``` -------------------------------- ### Get Current File Path and Basilisk Directory Source: https://avslab.github.io/basilisk/_modules/test_simpleInstrument.html This snippet retrieves the absolute path of the current file and determines the directory of the Basilisk installation by splitting the path. It requires the 'inspect' and 'os' modules. ```python # # 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. # import inspect import os import pytest filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) bskName = 'Basilisk' splitPath = path.split(bskName) ``` -------------------------------- ### Reset mrpPD Module Source: https://avslab.github.io/basilisk/Documentation/fswAlgorithms/attControl/mrpPD/mrpPD.html This C function performs a complete reset of the mrpPD module, returning its internal states to their default values. This is useful for re-initializing the control system, for example, after a system anomaly or during simulation setup. ```c void Reset_mrpPD(MrpPDConfig *configData, uint64_t callTime, int64_t moduleID) ``` -------------------------------- ### Build HTML Documentation Source: https://avslab.github.io/basilisk/Support/Developer/createHtmlDocumentation.html Execute the make command to generate the HTML documentation files. ```bash make html ``` -------------------------------- ### Basilisk Scenario Setup and Imports Source: https://avslab.github.io/basilisk/_modules/scenarioAttitudeFeedback2T_TH.html This script sets up a Basilisk simulation scenario. It imports necessary modules for spacecraft dynamics, FSW algorithms, and simulation support utilities. Ensure Basilisk is installed and its path is correctly set. ```python import os import matplotlib.pyplot as plt import numpy as np # The path to the location of Basilisk # Used to get the location of supporting data. from Basilisk import __path__ # import message declarations from Basilisk.architecture import messaging from Basilisk.fswAlgorithms import attTrackingError from Basilisk.fswAlgorithms import inertial3D # import FSW Algorithm related support from Basilisk.fswAlgorithms import mrpFeedback from Basilisk.fswAlgorithms import thrFiringSchmitt from Basilisk.fswAlgorithms import thrForceMapping from Basilisk.simulation import extForceTorque from Basilisk.simulation import simpleNav # import simulation related support from Basilisk.simulation import spacecraft from Basilisk.simulation import thrusterDynamicEffector # import general simulation support files from Basilisk.utilities import SimulationBaseClass from Basilisk.utilities import fswSetupThrusters from Basilisk.utilities import macros from Basilisk.utilities import orbitalMotion from Basilisk.utilities import simIncludeGravBody from Basilisk.utilities import simIncludeThruster from Basilisk.utilities import unitTestSupport # general support file with common unit test functions # attempt to import vizard from Basilisk.utilities import vizSupport bskPath = __path__[0] fileName = os.path.basename(os.path.splitext(__file__)[0]) ``` -------------------------------- ### Initialize scenario_AttSteering environment Source: https://avslab.github.io/basilisk/_modules/scenario_AttSteering.html Imports and path configurations required to set up the simulation environment. ```python # Get current file path import inspect import os import sys import numpy as np # Import utilities from Basilisk.utilities import orbitalMotion, macros, vizSupport filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) # Import master classes: simulation base class and scenario base class sys.path.append(path + '/..') from BSK_masters import BSKSim, BSKScenario import BSK_Dynamics, BSK_Fsw # Import plotting file for your scenario sys.path.append(path + '/../plotting') import BSK_Plotting as BSK_plt ``` -------------------------------- ### Get Repository Root Source: https://avslab.github.io/basilisk/_modules/BSK_OpNavFsw.html Recursively searches for the repository root directory starting from the given path. It checks for the presence of a .git directory or pyproject.toml/setup.cfg file to identify the root. This is useful for locating project-specific configuration files or data. ```python def get_repo_root(start: Path = Path(__file__).resolve()) -> Path: for parent in [start] + list(start.parents): if (parent / ".git").exists(): return parent if (parent / "pyproject.toml").exists() or (parent / "setup.cfg").exists(): return parent raise RuntimeError("Repo root not found") ``` -------------------------------- ### Setup Simulation and Execute Source: https://avslab.github.io/basilisk/_modules/test_faultDetection.html Configures the simulation by adding a data logger for the navigation output message, initializing the simulation, setting a stop time, and executing the simulation to generate test data. ```python dataLog = faults.opNavOutMsg.recorder() unitTestSim.AddModelToTask(unitTaskName, dataLog) # Initialize the simulation unitTestSim.InitializeSimulation() # The result isn't going to change with more time. The module will continue to produce the same result unitTestSim.ConfigureStopTime(testProcessRate) # seconds to stop simulation unitTestSim.ExecuteSimulation() ``` -------------------------------- ### Install Build Tools and Build Wheel Source: https://avslab.github.io/basilisk/_sources/Plugins/overview.rst.txt Install the required Python packages for building and then build the plugin wheel. This is a prerequisite for installing the custom plugin. ```bash pip install scikit-build-core build python -m build --wheel pip install dist/*.whl ```