From 9753381bdfcb14a9743999fb594f27a34956904e Mon Sep 17 00:00:00 2001 From: Juan Garcia Bonilla Date: Sat, 25 Nov 2023 12:42:12 -0800 Subject: [PATCH 1/5] Add missing override specifier --- .../dynamics/_GeneralModuleFiles/pointMassGravityModel.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/simulation/dynamics/_GeneralModuleFiles/pointMassGravityModel.h b/src/simulation/dynamics/_GeneralModuleFiles/pointMassGravityModel.h index 1961d058a5..f7dcfbefd7 100644 --- a/src/simulation/dynamics/_GeneralModuleFiles/pointMassGravityModel.h +++ b/src/simulation/dynamics/_GeneralModuleFiles/pointMassGravityModel.h @@ -48,7 +48,7 @@ class PointMassGravityModel : public GravityModel { * The position is given relative to the body and in the inertial * reference frame. */ - double computePotentialEnergy(const Eigen::Vector3d& positionWrtPlanet_N) const; + double computePotentialEnergy(const Eigen::Vector3d& positionWrtPlanet_N) const override; public: double muBody = 0; /**< [m^3/s^2] Gravitation parameter for the planet */ From 7fa2d828593579a83d94451f2a1d4ad147dd6435 Mon Sep 17 00:00:00 2001 From: Juan Garcia Bonilla Date: Sat, 25 Nov 2023 12:43:03 -0800 Subject: [PATCH 2/5] Allow set SpiceInterface::planetFrames with list --- .../environment/spiceInterface/spiceInterface.i | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/simulation/environment/spiceInterface/spiceInterface.i b/src/simulation/environment/spiceInterface/spiceInterface.i index d8a1d46c71..dd4f92a5bb 100755 --- a/src/simulation/environment/spiceInterface/spiceInterface.i +++ b/src/simulation/environment/spiceInterface/spiceInterface.i @@ -28,6 +28,18 @@ from Basilisk.architecture.swig_common_model import * %include "std_string.i" %include "std_vector.i" +%template() std::vector; + +// Declaring planetFrames %naturalvar removes the need for the StringVector wrapper: +// mySpiceInterface.planetFrames = ["a", "b", "c"] +// is allowed, which is more pythonic than: +// mySpiceInterface.planetFrames = spiceInterface.StringVector(["a", "b", "c"]) +// (which is also allowed) +// However, modifiying in place is forbidden: +// mySpiceInterface.planetFrames[2] = "bb" +// this raises an error because mySpiceInterface.planetFrames is returned by value +%naturalvar SpiceInterface::planetFrames; + %include "sys_model.i" %include "spiceInterface.h" From a8e6432508ed795e74cadb720de91f84789f1d43 Mon Sep 17 00:00:00 2001 From: Juan Garcia Bonilla Date: Sat, 25 Nov 2023 12:43:17 -0800 Subject: [PATCH 3/5] Refactor simIncludeGravBody --- src/utilities/simIncludeGravBody.py | 758 ++++++++++++++++------------ 1 file changed, 434 insertions(+), 324 deletions(-) diff --git a/src/utilities/simIncludeGravBody.py b/src/utilities/simIncludeGravBody.py index 694a475906..45f3711d33 100644 --- a/src/utilities/simIncludeGravBody.py +++ b/src/utilities/simIncludeGravBody.py @@ -1,7 +1,6 @@ - # ISC License # -# Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder +# Copyright (c) 2023, 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 @@ -15,399 +14,510 @@ # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - - -from collections import OrderedDict - +from typing import Optional +from typing import Dict +from typing import Iterable +from typing import Union +from typing import overload +from typing import Sequence +from typing import List +from typing import Protocol +from typing import runtime_checkable +from typing import Any +from dataclasses import dataclass + +from Basilisk import __path__ +from Basilisk.architecture import messaging from Basilisk.simulation import gravityEffector from Basilisk.simulation import spiceInterface -from Basilisk.simulation.gravityEffector import loadGravFromFile as loadGravFromFile_python -from Basilisk.simulation.gravityEffector import loadPolyFromFile as loadPolyFromFile_python +from Basilisk.simulation.gravityEffector import ( + loadGravFromFile as loadGravFromFile_python, +) +from Basilisk.simulation.gravityEffector import ( + loadPolyFromFile as loadPolyFromFile_python, +) from Basilisk.utilities import unitTestSupport +from Basilisk.utilities.deprecated import deprecationWarn + +@dataclass +class BodyData: + """A class that contains information about a body in the simulation. + + Args: + identifier (str): The SPICE identifier of the body. + planetName (str): The name that identifies the body within the simulation. + displayName (str): The name for the body in the Vizard display. + modelDictionaryKey (str): Vizard model key name. + mu (float): Gravitational parameter in m^3/s^2. + radEquator (float): Equatorial radius of the body in meters. + spicePlanetFrame (str): The name of the SPICE frame (attitude provider). + radiusRatio (float, optional): Used to compute ellipticity. It is + provided for bodies in the basic Vizard body dictionary. Defaults to 1. + """ -class gravBodyFactory(object): - """Factory cass to create gravitational bodies.""" - def __init__(self, bodyNames=None): - self.spicePlanetNames = [] - self.spicePlanetFrames = [] - self.gravBodies = OrderedDict() - self.spiceObject = None - self.spiceKernelFileNames = [] - self.epochMsg = None + identifier: str + planetName: str + displayName: str + modelDictionaryKey: str + mu: float + radEquator: float + spicePlanetFrame: str + radiusRatio: float = 1 + + +BODY_DATA = { + "sun": BodyData( + identifier="sun", + planetName="sun_planet_data", + displayName="sun", + modelDictionaryKey="", + mu=1.32712440018e20, + radEquator=695508000.0, + spicePlanetFrame="IAU_sun", + ), + "mercury": BodyData( + identifier="mercury", + planetName="mercury_planet_data", + displayName="mercury", + modelDictionaryKey="", + mu=0.022032e15, + radEquator=2439700.0, + spicePlanetFrame="IAU_mercury", + ), + "venus": BodyData( + identifier="venus", + planetName="venus_planet_data", + displayName="venus", + modelDictionaryKey="", + mu=3.24858599e14, + radEquator=6051800.0, + spicePlanetFrame="IAU_venus", + ), + "earth": BodyData( + identifier="earth", + planetName="earth_planet_data", + displayName="earth", + modelDictionaryKey="", + mu=0.3986004415e15, + radEquator=6378136.6, + spicePlanetFrame="IAU_earth", + ), + "moon": BodyData( + identifier="moon", + planetName="moon_planet_data", + displayName="moon", + modelDictionaryKey="", + mu=4.902799e12, + radEquator=1738100.0, + spicePlanetFrame="IAU_moon", + ), + "mars": BodyData( + identifier="mars", + planetName="mars_planet_data", + displayName="mars", + modelDictionaryKey="", + mu=4.28283100e13, + radEquator=3396190.0, + spicePlanetFrame="IAU_mars", + ), + "mars barycenter": BodyData( + identifier="mars barycenter", + planetName="mars barycenter_planet_data", + displayName="mars barycenter", + modelDictionaryKey="", + mu=4.28283100e13, + radEquator=3396190.0, + spicePlanetFrame="IAU_mars", + ), + "jupiter barycenter": BodyData( + identifier="jupiter barycenter", + planetName="jupiter barycenter_planet_data", + displayName="jupiter", + modelDictionaryKey="", + mu=1.266865349093058e17, + radEquator=71492000.0, + spicePlanetFrame="IAU_jupiter", + ), + "saturn": BodyData( + identifier="saturn", + planetName="saturn barycenter_planet_data", + displayName="saturn", + modelDictionaryKey="", + mu=3.79395000e16, + radEquator=60268000.0, + spicePlanetFrame="IAU_saturn", + ), + "uranus": BodyData( + identifier="uranus", + planetName="uranus barycenter_planet_data", + displayName="uranus", + modelDictionaryKey="", + mu=5.79396566e15, + radEquator=25559000.0, + spicePlanetFrame="IAU_uranus", + ), + "neptune": BodyData( + identifier="neptune", + planetName="neptune barycenter_planet_data", + displayName="neptune", + modelDictionaryKey="", + mu=6.83509920e15, + radEquator=24764000.0, + spicePlanetFrame="IAU_neptune", + ), +} + + +@runtime_checkable +class WithGravField(Protocol): + gravField: Any # cannot be GravityEffector because SWIG classes dont give type info + + +class gravBodyFactory: + """Class to create gravitational bodies.""" + + def __init__(self, bodyNames: Iterable[str] = []): + self.spicePlanetFrames: List[str] = [] + self.gravBodies: Dict[str, gravityEffector.GravBodyData] = {} + self.spiceObject: Optional[spiceInterface.SpiceInterface] = None + self.spiceKernelFileNames: List[str] = [] + self.epochMsg: Optional[messaging.EpochMsg] = None if bodyNames: self.createBodies(bodyNames) - def createBodies(self, bodyNames): + def addBodiesTo( + self, + objectToAddTheBodies: Union[gravityEffector.GravityEffector, WithGravField], + ): + """Can be called with a GravityEffector or an object that has a gravField + variable to set the gravity bodies used in the object. """ - A convenience function to create multiple typical solar system bodies. + bodies = gravityEffector.GravBodyVector(list(self.gravBodies.values())) + if isinstance(objectToAddTheBodies, WithGravField): + objectToAddTheBodies = objectToAddTheBodies.gravField + objectToAddTheBodies.setGravBodies(bodies) # type: ignore + + # Note, in the `create` functions below the `isCentralBody` and `useSphericalHarmParams` are + # all set to False in the `GravGodyData()` constructor. + + def createBody( + self, bodyData: Union[str, BodyData] + ) -> gravityEffector.GravBodyData: + """Convenience function to create a body given its name. - Parameters - ---------- - bodyNames : array_like + Args: + bodyData (Union[str, BodyData]): + A valid SPICE celestial body string or a BodyData class with + the relevant data. + + Returns: + gravityEffector.GravBodyData: The body object with corresponding data. + """ + if not isinstance(bodyData, BodyData): + key = bodyData.lower().replace("_", " ") + if key not in BODY_DATA: + raise ValueError( + f"Body {bodyData} is unkown. " + f"Valid options are: {', '.join(BODY_DATA)}" + ) + + bodyData = BODY_DATA[key] + + body = gravityEffector.GravBodyData() + body.planetName = bodyData.planetName + body.displayName = bodyData.displayName + body.modelDictionaryKey = bodyData.modelDictionaryKey + body.mu = bodyData.mu + body.radEquator = bodyData.radEquator + body.radiusRatio = bodyData.radiusRatio + self.gravBodies[bodyData.identifier] = body + self.spicePlanetFrames.append(bodyData.spicePlanetFrame) + return body + + def createBodies( + self, *bodyNames: Union[str, Iterable[str]] + ) -> Dict[str, gravityEffector.GravBodyData]: + """A convenience function to create multiple typical solar system bodies. + + Args: + bodyNames (Union[str, Iterable[str]]): Planet name strings. Each planet name must be a valid SPICE celestial body string. - Returns - ------- - gravBodies : array_like - A list of gravity body objects held by the gravity factory. + Returns: + Dict[str, gravityEffector.GravBodyData]: + A dictionary of gravity body objects held by the gravity factory. """ - for name in bodyNames: - if name == 'mercury': - self.createMercury() - elif name == 'venus': - self.createVenus() - elif name == "earth": - self.createEarth() - elif name == "moon": - self.createMoon() - elif name == "mars": - self.createMars() - elif name == "mars barycenter": - self.createMarsBarycenter() - elif name == "jupiter barycenter": - self.createJupiter() - elif name == "saturn": - self.createSaturn() - elif name == 'uranus': - self.createUranus() - elif name == 'neptune': - self.createNeptune() - elif name == "sun": - self.createSun() + for nameOrIterableOfNames in bodyNames: + if isinstance(nameOrIterableOfNames, str): + self.createBody(nameOrIterableOfNames) else: - print("gravBody " + name + " not found in gravBodyUtilities.py") + for name in nameOrIterableOfNames: + self.createBody(name) return self.gravBodies - # Note, in the `create` functions below the `isCentralBody` and `useSphericalHarmParams` are - # all set to False in the `GravGodyData()` constructor. - def createSun(self): - """Create gravity body with sun mass properties.""" - sun = gravityEffector.GravBodyData() - sun.planetName = "sun_planet_data" - sun.displayName = "sun" - sun.modelDictionaryKey = "" - sun.mu = 1.32712440018E20 # meters^3/s^2 - sun.radEquator = 695508000.0 # meters - self.gravBodies['sun'] = sun - self.spicePlanetFrames.append("IAU_sun") - sun.this.disown() - return sun + return self.createBody("sun") def createMercury(self): - """Create gravity body with Mercury mass properties.""" - mercury = gravityEffector.GravBodyData() - mercury.planetName = "mercury_planet_data" - mercury.displayName = "mercury" - mercury.modelDictionaryKey = "" - mercury.mu = 4.28283100e13 # meters^3/s^2 - mercury.radEquator = 2439700.0 # meters - self.gravBodies['mercury'] = mercury - self.spicePlanetFrames.append("IAU_mercury") - mercury.this.disown() - return mercury + return self.createBody("mercury") def createVenus(self): - """Create gravity body with Venus mass properties.""" - venus = gravityEffector.GravBodyData() - venus.planetName = "venus_planet_data" - venus.displayName = "venus" - venus.modelDictionaryKey = "" - venus.mu = 3.24858599e14 # meters^3/s^2 - venus.radEquator = 6051800.0 # meters - self.gravBodies['venus'] = venus - self.spicePlanetFrames.append("IAU_venus") - venus.this.disown() - return venus + return self.createBody("venus") def createEarth(self): - """Create gravity body with Earth mass properties.""" - earth = gravityEffector.GravBodyData() - earth.planetName = "earth_planet_data" - earth.displayName = "earth" - earth.modelDictionaryKey = "" - earth.mu = 0.3986004415E+15 # meters^3/s^2 - earth.radEquator = 6378136.6 # meters - self.gravBodies['earth'] = earth - self.spicePlanetFrames.append("IAU_earth") - earth.this.disown() - return earth + return self.createBody("earth") def createMoon(self): - """Create gravity body with Moon mass properties.""" - moon = gravityEffector.GravBodyData() - moon.planetName = "moon_planet_data" - moon.displayName = "moon" - moon.modelDictionaryKey = "" - moon.mu = 4.902799E12 # meters^3/s^2 - moon.radEquator = 1738100.0 # meters - self.gravBodies['moon'] = moon - self.spicePlanetFrames.append("IAU_moon") - moon.this.disown() - return moon + return self.createBody("moon") def createMars(self): - """Create gravity body with Mars mass properties.""" - mars = gravityEffector.GravBodyData() - mars.planetName = "mars_planet_data" - mars.displayName = "mars" - mars.modelDictionaryKey = "" - mars.mu = 4.28283100e13 # meters^3/s^2 - mars.radEquator = 3396190 # meters - self.gravBodies['mars'] = mars - self.spicePlanetFrames.append("IAU_mars") - mars.this.disown() - return mars + return self.createBody("mars") def createMarsBarycenter(self): - """Create gravity body with Mars mass properties.""" - mars_barycenter = gravityEffector.GravBodyData() - mars_barycenter.planetName = "mars barycenter_planet_data" - mars_barycenter.displayName = "mars" - mars_barycenter.modelDictionaryKey = "" - mars_barycenter.mu = 4.28283100e13 # meters^3/s^2 - mars_barycenter.radEquator = 3396190 # meters - self.gravBodies['mars barycenter'] = mars_barycenter - self.spicePlanetFrames.append("IAU_mars") - mars_barycenter.this.disown() - return mars_barycenter + return self.createBody("mars barycenter") def createJupiter(self): - """Create gravity body with Jupiter mass properties.""" - jupiter = gravityEffector.GravBodyData() - jupiter.planetName = "jupiter barycenter_planet_data" - jupiter.displayName = "jupiter" - jupiter.modelDictionaryKey = "" - jupiter.mu = 1.266865349093058E17 # meters^3/s^2 - jupiter.radEquator = 71492000.0 # meters - self.gravBodies['jupiter barycenter'] = jupiter - self.spicePlanetFrames.append("IAU_jupiter") - jupiter.this.disown() - return jupiter + return self.createBody("jupiter barycenter") def createSaturn(self): - """Create gravity body with Saturn mass properties.""" - saturn = gravityEffector.GravBodyData() - saturn.planetName = "saturn barycenter_planet_data" - saturn.displayName = "saturn" - saturn.modelDictionaryKey = "" - saturn.mu = 3.79395000E16 # meters^3/s^2 - saturn.radEquator = 60268000.0 # meters - self.gravBodies['saturn'] = saturn - self.spicePlanetFrames.append("IAU_saturn") - saturn.this.disown() - return saturn + return self.createBody("saturn") def createUranus(self): - """Create gravity body with Uranus mass properties.""" - uranus = gravityEffector.GravBodyData() - uranus.planetName = "uranus barycenter_planet_data" - uranus.displayName = "uranus" - uranus.modelDictionaryKey = "" - uranus.mu = 5.79396566E15 # meters^3/s^2 - uranus.radEquator = 25559000.0 # meters - self.gravBodies['uranus'] = uranus - self.spicePlanetFrames.append("IAU_uranus") - uranus.this.disown() - return uranus + return self.createBody("uranus") def createNeptune(self): - """Create gravity body with Neptune mass properties.""" - neptune = gravityEffector.GravBodyData() - neptune.planetName = "neptune barycenter_planet_data" - neptune.displayName = "neptune" - neptune.modelDictionaryKey = "" - neptune.mu = 6.83509920E15 # meters^3/s^2 - neptune.radEquator = 24764000.0 # meters - self.gravBodies['neptune'] = neptune - self.spicePlanetFrames.append("IAU_neptune") - neptune.this.disown() - return neptune - - def createCustomGravObject(self, label, mu, **kwargs): + return self.createBody("neptune") + + def createCustomGravObject( + self, + label: str, + mu: float, + displayName: Optional[str] = None, + modelDictionaryKey: Optional[str] = None, + radEquator: Optional[float] = None, + radiusRatio: Optional[float] = None, + planetFrame: Optional[str] = None, + ) -> gravityEffector.GravBodyData: + """Create a custom gravity body object. + + Args: + label (str): Gravity body name + mu (float): Gravity constant in m^3/s^2 + displayName (Optional[str], optional): Vizard celestial body name, if not + provided then planetFrame becomes the Vizard name. Defaults to None. + modelDictionaryKey (Optional[str], optional): Vizard model key name. + If not set, then either the displayName or planetName is used to + set the model. Defaults to None. + radEquator (Optional[float], optional): Equatorial radius in meters. + Defaults to None. + radiusRatio (Optional[float], optional): Ratio of the polar radius to + the equatorial radius. Defaults to None. + planetFrame (Optional[str], optional): Name of the spice planet + frame. Defaults to None. + + Returns: + gravityEffector.GravBodyData: The body object with the given data. """ - Create a custom gravity body object. - - Parameters - ---------- - label : string - Gravity body name - mu : double - Gravity constant - - Other Parameters - ---------------- - kwargs : - radEquator : double - Equatorial radius in meters - radiusRatio : double - Ratio of the polar radius to the equatorial radius. - planetFrame : string - Name of the spice planet frame - displayName: string - Vizard celestial body name, if not provided then planetFrame becomes the Vizard name - modelDictionaryKey: string - Vizard model key name. if not set, then either the displayName or planetName is used to set the model - - """ - unitTestSupport.checkMethodKeyword( - ['radEquator', 'radiusRatio', 'planetFrame', 'displayName', 'modelDictionaryKey'], - kwargs) - - if not isinstance(label, str): - print('ERROR: label must be a string') - exit(1) - gravBody = gravityEffector.GravBodyData() gravBody.planetName = label gravBody.mu = mu - if 'radEquator' in kwargs: - gravBody.radEquator = kwargs['radEquator'] - if 'radiusRatio' in kwargs: - gravBody.radiusRatio = kwargs['radiusRatio'] - if 'displayName' in kwargs: - gravBody.displayName = kwargs['displayName'] - gravBody.modelDictionaryKey = "" - if 'modelDictionaryKey' in kwargs: - gravBody.modelDictionaryKey = kwargs['modelDictionaryKey'] + if radEquator is not None: + gravBody.radEquator = radEquator + if radiusRatio is not None: + gravBody.radiusRatio = radiusRatio + if displayName is not None: + gravBody.displayName = displayName + if modelDictionaryKey is None: + gravBody.modelDictionaryKey = "" + else: + gravBody.modelDictionaryKey = modelDictionaryKey self.gravBodies[label] = gravBody - planetFrame = "" - if 'planetFrame' in kwargs: - planetFrame = kwargs['planetFrame'] - self.spicePlanetFrames.append(planetFrame) - gravBody.this.disown() + if planetFrame is not None: + self.spicePlanetFrames.append(planetFrame) return gravBody - def createSpiceInterface(self, path, time, **kwargs): + @overload + def createSpiceInterface( + self, + path: str, + time: str, + spiceKernelFileNames: Iterable[str] = [ + "de430.bsp", + "naif0012.tls", + "de-403-masses.tpc", + "pck00010.tpc", + ], + spicePlanetNames: Optional[Sequence[str]] = None, + spicePlanetFrames: Optional[Sequence[str]] = None, + epochInMsg: bool = False, + ) -> spiceInterface.SpiceInterface: + """A convenience function to configure a NAIF Spice module for the simulation. + It connects the gravBodyData objects to the spice planet state messages. Thus, + it must be run after the gravBodyData objects are created. + + Args: + path (str): The absolute path to the folder that contains the + kernels to be loaded. + time (str): The time string in a format that SPICE recognizes. + spiceKernelFileNames (Iterable[str], optional): A list of spice kernel file + names including file extension. Defaults to + `['de430.bsp', 'naif0012.tls', 'de-403-masses.tpc', 'pck00010.tpc']`. + spicePlanetNames (Optional[Sequence[str]], optional): A list of planet names + whose Spice data is loaded. If this is not provided, Spice data is + loaded for the bodies created with this factory object. Defaults to None. + spicePlanetFrames (Optional[Sequence[str]], optional): A list of planet + frame names to load in Spice. If this is not provided, frames are loaded + for the bodies created with this factory function. Defaults to None. + epochInMsg (bool, optional): Flag to set an epoch input message for the + spice interface. Defaults to False. + + Returns: + spiceInterface.SpiceInterface: The generated SpiceInterface, which is the + same as the stored `self.spiceObject` """ - A convenience function to configure a NAIF Spice module for the simulation. - It connects the gravBodyData objects to the spice planet state messages. Thus, - it must be run after the gravBodyData objects are created. - - Parameters - ---------- - path : string - The absolute path to the Basilisk source directory (default ''). - time : string - The time string. - - Other Parameters - ---------------- - kwargs : - spiceKernalFileNames : - A list of spice kernel file names including file extension. - spicePlanetNames : - A list of planet names whose Spice data is loaded, overriding the gravBodies list. - spicePlanetFrames : - A list of strings for the planet frame names. If left empty for a planet, then - ``IAU_`` + planetName is assumed for the planet frame. - epochInMsg: bool - Flag to set an epoch input message for the spice interface + @overload + def createSpiceInterface( + self, + *, + path: str = "%BSK_PATH%/supportData/EphemerisData/", + time: str, + spiceKernelFileNames: Iterable[str] = [ + "de430.bsp", + "naif0012.tls", + "de-403-masses.tpc", + "pck00010.tpc", + ], + spicePlanetNames: Optional[Sequence[str]] = None, + spicePlanetFrames: Optional[Sequence[str]] = None, + epochInMsg: bool = False, + ) -> spiceInterface.SpiceInterface: + """A convenience function to configure a NAIF Spice module for the simulation. + It connect the gravBodyData objects to the spice planet state messages. Thus, + it must be run after the gravBodyData objects are created. + + Unless the 'path' input is provided, the kernels are loaded from the folder: + `%BSK_PATH%/supportData/EphemerisData/`, where `%BSK_PATH%` is replaced by + the Basilisk directory. + + Args: + path (str): The absolute path to the folder that contains the + kernels to be loaded. + time (str): The time string in a format that SPICE recognizes. + spiceKernelFileNames (Iterable[str], optional): A list of spice kernel file + names including file extension. Defaults to + `['de430.bsp', 'naif0012.tls', 'de-403-masses.tpc', 'pck00010.tpc']`. + spicePlanetNames (Optional[Sequence[str]], optional): A list of planet names + whose Spice data is loaded. If this is not provided, Spice data is + loaded for the bodies created with this factory object. Defaults to None. + spicePlanetFrames (Optional[Sequence[str]], optional): A list of planet + frame names to load in Spice. If this is not provided, frames are loaded + for the bodies created with this factory function. Defaults to None. + epochInMsg (bool, optional): Flag to set an epoch input message for the + spice interface. Defaults to False. + + Returns: + spiceInterface.SpiceInterface: The generated SpiceInterface, which is the + same as the stored `self.spiceObject` """ - if 'spiceKernalFileNames' in kwargs: - try: - for fileName in kwargs['spiceKernalFileNames']: - self.spiceKernelFileNames.append(fileName) - except TypeError: - raise TypeError('spiceKernalFileNames expects a list') - else: - self.spiceKernelFileNames.extend(['de430.bsp', 'naif0012.tls', 'de-403-masses.tpc', 'pck00010.tpc']) - - self.spicePlanetNames = [] - if 'spicePlanetNames' in kwargs: - try: - for planetName in kwargs['spicePlanetNames']: - self.spicePlanetNames.append(planetName) - except TypeError: - raise TypeError('spicePlanetNames expects a list') - else: - self.spicePlanetNames = list(self.gravBodies.keys()) - - if 'spicePlanetFrames' in kwargs: - try: - self.spicePlanetFrames = [] - for planetFrame in kwargs['spicePlanetFrames']: - self.spicePlanetFrames.append(planetFrame) - except TypeError: - raise TypeError('spicePlanetFrames expects a list') + def createSpiceInterface( + self, + path: str = "%BSK_PATH%/supportData/EphemerisData/", + time: str = "", + spiceKernelFileNames: Iterable[str] = [ + "de430.bsp", + "naif0012.tls", + "de-403-masses.tpc", + "pck00010.tpc", + ], + spicePlanetNames: Optional[Sequence[str]] = None, + spicePlanetFrames: Optional[Sequence[str]] = None, + epochInMsg: bool = False, + spiceKernalFileNames = None, + ) -> spiceInterface.SpiceInterface: + if time == "": + raise ValueError( + "'time' argument must be provided and a valid SPICE time string" + ) + + if spiceKernalFileNames is not None: + spiceKernelFileNames = spiceKernalFileNames + deprecationWarn( + f"{gravBodyFactory.createSpiceInterface.__qualname__}.spiceKernalFileNames" + "2024/11/24", + "The argument 'spiceKernalFileNames' is deprecated, as it is a " + "misspelling of 'spiceKernelFileNames'" + ) + + path = path.replace("%BSK_PATH%", list(__path__)[0]) + + self.spiceKernelFileNames.extend(spiceKernelFileNames) + self.spicePlanetNames = list(spicePlanetNames or self.gravBodies) + if spicePlanetFrames is not None: + self.spicePlanetFrames = list(spicePlanetFrames) self.spiceObject = spiceInterface.SpiceInterface() self.spiceObject.ModelTag = "SpiceInterfaceData" self.spiceObject.SPICEDataPath = path - self.spiceObject.addPlanetNames(spiceInterface.StringVector(self.spicePlanetNames)) + self.spiceObject.addPlanetNames(self.spicePlanetNames) self.spiceObject.UTCCalInit = time if len(self.spicePlanetFrames) > 0: - self.spiceObject.planetFrames = spiceInterface.StringVector(self.spicePlanetFrames) + self.spiceObject.planetFrames = list(self.spicePlanetFrames) - for fileName in self.spiceKernelFileNames: + for fileName in set(self.spiceKernelFileNames): self.spiceObject.loadSpiceKernel(fileName, path) self.spiceObject.SPICELoaded = True # subscribe Grav Body data to the spice state message - c = 0 - for key, gravBodyDataItem in self.gravBodies.items(): - gravBodyDataItem.planetBodyInMsg.subscribeTo(self.spiceObject.planetStateOutMsgs[c]) - c += 1 + for c, gravBodyDataItem in enumerate(self.gravBodies.values()): + gravBodyDataItem.planetBodyInMsg.subscribeTo( + self.spiceObject.planetStateOutMsgs[c] + ) # create and connect to an epoch input message - if 'epochInMsg' in kwargs: - if kwargs['epochInMsg']: - self.epochMsg = unitTestSupport.timeStringToGregorianUTCMsg(time, dataPath=path) - self.spiceObject.epochInMsg.subscribeTo(self.epochMsg) + if epochInMsg: + self.epochMsg = unitTestSupport.timeStringToGregorianUTCMsg( + time, dataPath=path + ) + self.spiceObject.epochInMsg.subscribeTo(self.epochMsg) - return + return self.spiceObject def unloadSpiceKernels(self): """Method to unload spice kernals at the end of a simulation.""" - for fileName in self.spiceKernelFileNames: + if self.spiceObject is None: + return + for fileName in set(self.spiceKernelFileNames): self.spiceObject.unloadSpiceKernel(fileName, self.spiceObject.SPICEDataPath) - return +def loadGravFromFile( + fileName: str, + spherHarm: gravityEffector.SphericalHarmonicsGravityModel, + maxDeg: int = 2, +): + """Load the gravitational body spherical harmonics coefficients from a file. -def loadGravFromFile(fileName, spherHarm, maxDeg=2): - """ - Load the gravitational body spherical harmonics coefficients from a file. - - Parameters - ---------- - fileName : string - The full path to the specified data file. - spherHarm: - The spherical harmonics container of the gravity body. - maxDeg : integer - maximum degree of spherical harmonics to load - - - Notes - ----- - This function is a convenience utility for loading in the spherical harmonics - coefficients from a data file. The default harmonic degree is 2 unless specified. - Note that this function calls the gravityEffector function loadGravFromFile(). + Note that this function calls the `gravityEffector` function `loadGravFromFile()`. + + Args: + fileName (str): The full path to the specified data file. + spherHarm (gravityEffector.SphericalHarmonicsGravityModel): + The spherical harmonics container of the gravity body. + maxDeg (int, optional): Maximum degree of spherical harmonics to load. + Defaults to 2. """ loadGravFromFile_python(fileName, spherHarm, maxDeg) -def loadPolyFromFile(fileName, poly): - """ - Load the gravitational body spherical harmonics coefficients from a file. - - Parameters - ---------- - fileName : string - The full path to the specified data file. - spherHarm: - The spherical harmonics container of the gravity body. - maxDeg : integer - maximum degree of spherical harmonics to load - - - Notes - ----- - This function is a convenience utility for loading in the spherical harmonics - coefficients from a data file. The default harmonic degree is 2 unless specified. - Note that this function calls the gravityEffector function loadGravFromFile(). + +def loadPolyFromFile(fileName: str, poly: gravityEffector.PolyhedralGravityModel): + """Load the gravitational body polyhedral coefficients from a file. + + Args: + fileName (str): The full path to the specified data file. + poly (gravityEffector.PolyhedralGravityModel): + The polyhedarl gravity model container of the body. """ loadPolyFromFile_python(fileName, poly) From dfdf44b489bcb8161efa3967aa224fa744ecdf8e Mon Sep 17 00:00:00 2001 From: Juan Garcia Bonilla Date: Sat, 25 Nov 2023 12:43:35 -0800 Subject: [PATCH 4/5] Update scenarios to use new syntax --- examples/BskSim/models/BSK_Dynamics.py | 2 +- .../BskSim/models/BSK_FormationDynamics.py | 4 +- .../modelsMultiSat/BSK_MultiSatDynamics.py | 2 +- .../modelsOpNav/BSK_OpNavDynamics.py | 6 +-- .../CNN_ImageGen/scenario_CNNImages.py | 2 +- .../OpNavMC/scenario_OpNavAttODMC.py | 2 +- examples/scenarioAerocapture.py | 7 +-- examples/scenarioAlbedo.py | 2 +- examples/scenarioAsteroidArrival.py | 15 +++--- examples/scenarioAttGuideHyperbolic.py | 2 +- examples/scenarioAttLocPoint.py | 2 +- .../scenarioAttitudeConstrainedManeuver.py | 24 +++++----- .../scenarioAttitudeConstraintViolation.py | 22 ++++----- examples/scenarioAttitudeFeedback.py | 2 +- examples/scenarioAttitudeFeedback2T.py | 2 +- examples/scenarioAttitudeFeedback2T_TH.py | 2 +- .../scenarioAttitudeFeedback2T_stateEffTH.py | 2 +- examples/scenarioAttitudeFeedbackRW.py | 2 +- examples/scenarioAttitudeFeedbackRWPower.py | 2 +- examples/scenarioAttitudeGG.py | 2 +- examples/scenarioAttitudeGuidance.py | 2 +- examples/scenarioAttitudePrescribed.py | 2 +- examples/scenarioAttitudeSteering.py | 2 +- examples/scenarioBasicOrbit.py | 2 +- examples/scenarioBasicOrbitStream.py | 2 +- examples/scenarioCentralBody.py | 10 ++-- examples/scenarioCustomGravBody.py | 2 +- examples/scenarioDataDemo.py | 8 ++-- examples/scenarioDataToViz.py | 2 +- examples/scenarioDebrisReorbitET.py | 4 +- examples/scenarioDeployingPanel.py | 16 +++---- examples/scenarioDragDeorbit.py | 2 +- examples/scenarioDragRendezvous.py | 37 +++++++------- examples/scenarioFlybySpice.py | 48 +++++++++---------- examples/scenarioFormationBasic.py | 6 +-- examples/scenarioFormationMeanOEFeedback.py | 14 +++--- examples/scenarioFormationReconfig.py | 12 ++--- examples/scenarioFuelSlosh.py | 2 +- examples/scenarioGroundDownlink.py | 13 +++-- examples/scenarioGroundLocationImaging.py | 4 +- examples/scenarioGroundMapping.py | 20 ++++---- examples/scenarioHelioTransSpice.py | 26 +++++----- examples/scenarioHingedRigidBody.py | 2 +- examples/scenarioHohmann.py | 2 +- examples/scenarioInertialSpiral.py | 2 +- examples/scenarioIntegrators.py | 4 +- examples/scenarioIntegratorsComparison.py | 4 +- examples/scenarioJupiterArrival.py | 2 +- examples/scenarioLagrangePointOrbit.py | 28 +++++------ .../scenarioMagneticFieldCenteredDipole.py | 2 +- examples/scenarioMagneticFieldWMM.py | 2 +- examples/scenarioMomentumDumping.py | 16 +++---- examples/scenarioMonteCarloAttRW.py | 2 +- examples/scenarioMtbMomentumManagement.py | 2 +- .../scenarioMtbMomentumManagementSimple.py | 2 +- examples/scenarioOrbitManeuver.py | 2 +- examples/scenarioOrbitMultiBody.py | 35 +++++++------- examples/scenarioPatchedConics.py | 2 +- examples/scenarioPowerDemo.py | 11 ++--- examples/scenarioRendezVous.py | 18 ++++--- examples/scenarioRotatingPanel.py | 2 +- examples/scenarioSensorThermal.py | 18 ++++--- examples/scenarioSmallBodyFeedbackControl.py | 2 +- examples/scenarioSmallBodyLandmarks.py | 2 +- examples/scenarioSmallBodyNav.py | 2 +- examples/scenarioSmallBodyNavUKF.py | 5 +- examples/scenarioSpacecraftLocation.py | 4 +- examples/scenarioSpiceSpacecraft.py | 18 ++++--- examples/scenarioTAM.py | 2 +- examples/scenarioTAMcomparison.py | 2 +- examples/scenarioTwoChargedSC.py | 4 +- .../scenarioVariableTimeStepIntegrators.py | 2 +- examples/scenarioVizPoint.py | 12 ++--- 73 files changed, 253 insertions(+), 302 deletions(-) diff --git a/examples/BskSim/models/BSK_Dynamics.py b/examples/BskSim/models/BSK_Dynamics.py index 92256a2633..b27c28bf84 100644 --- a/examples/BskSim/models/BSK_Dynamics.py +++ b/examples/BskSim/models/BSK_Dynamics.py @@ -116,7 +116,7 @@ def SetGravityBodies(self): self.earth = 1 self.moon = 2 - self.scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(self.gravFactory.gravBodies.values())) + self.gravFactory.addBodiesTo(self.scObject) self.gravFactory.createSpiceInterface(bskPath + '/supportData/EphemerisData/', timeInitString, epochInMsg=True) diff --git a/examples/BskSim/models/BSK_FormationDynamics.py b/examples/BskSim/models/BSK_FormationDynamics.py index e7c1c9e2ba..449de3f504 100644 --- a/examples/BskSim/models/BSK_FormationDynamics.py +++ b/examples/BskSim/models/BSK_FormationDynamics.py @@ -57,8 +57,8 @@ def __init__(self, SimBase, dynRate): self.gravFactory = simIncludeGravBody.gravBodyFactory() planet = self.gravFactory.createEarth() planet.isCentralBody = True # ensure this is the central gravitational body - self.scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(self.gravFactory.gravBodies.values())) - self.scObject2.gravField.gravBodies = spacecraft.GravBodyVector(list(self.gravFactory.gravBodies.values())) + self.gravFactory.addBodiesTo(self.scObject) + self.gravFactory.addBodiesTo(self.scObject2) # Initialize all modules and write init one-time messages self.InitAllDynObjects() diff --git a/examples/MultiSatBskSim/modelsMultiSat/BSK_MultiSatDynamics.py b/examples/MultiSatBskSim/modelsMultiSat/BSK_MultiSatDynamics.py index 49d7d94463..d86e181a85 100644 --- a/examples/MultiSatBskSim/modelsMultiSat/BSK_MultiSatDynamics.py +++ b/examples/MultiSatBskSim/modelsMultiSat/BSK_MultiSatDynamics.py @@ -100,7 +100,7 @@ def SetGravityBodies(self, SimBase): Specify what gravitational bodies to include in the simulation """ # Attach the gravity body - self.scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(SimBase.EnvModel.gravFactory.gravBodies.values())) + SimBase.EnvModel.gravFactory.addBodiesTo(self.scObject) def SetGroundLocations(self, SimBase): """ diff --git a/examples/OpNavScenarios/modelsOpNav/BSK_OpNavDynamics.py b/examples/OpNavScenarios/modelsOpNav/BSK_OpNavDynamics.py index 142b5c9270..c242720d87 100644 --- a/examples/OpNavScenarios/modelsOpNav/BSK_OpNavDynamics.py +++ b/examples/OpNavScenarios/modelsOpNav/BSK_OpNavDynamics.py @@ -215,7 +215,7 @@ def SetGravityEffector(self): gravBodies['mars barycenter'].useSphericalHarmonicsGravityModel( bskPath + '/supportData/LocalGravData/GGM2BData.txt', 2) - self.scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(self.gravFactory.gravBodies.values())) + self.gravFactory.addBodiesTo(self.scObject) self.gravFactory.createSpiceInterface(bskPath + '/supportData/EphemerisData/', timeInitString, epochInMsg=True) @@ -369,8 +369,8 @@ def SetEphemConvert(self): def SetSimpleGrav(self): planet = self.gravFactory.createMarsBarycenter() planet.isCentralBody = True - self.scObject.gravField.gravBodies = \ - spacecraft.GravBodyVector(list(self.gravFactory.gravBodies.values())) + + self.gravFactory.addBodiesTo(self.scObject) # Global call to initialize every module def InitAllDynObjects(self, SimBase): diff --git a/examples/OpNavScenarios/scenariosOpNav/CNN_ImageGen/scenario_CNNImages.py b/examples/OpNavScenarios/scenariosOpNav/CNN_ImageGen/scenario_CNNImages.py index 7e99225a70..2b90dbdd4f 100644 --- a/examples/OpNavScenarios/scenariosOpNav/CNN_ImageGen/scenario_CNNImages.py +++ b/examples/OpNavScenarios/scenariosOpNav/CNN_ImageGen/scenario_CNNImages.py @@ -184,7 +184,7 @@ def run(TheScenario, runLog): TheScenario.vizard.kill() - spice = TheScenario.get_DynModel().gravFactory.spiceObject + spice = TheScenario.get_DynModel().spiceObject spice.unloadSpiceKernel(spice.SPICEDataPath, 'de430.bsp') spice.unloadSpiceKernel(spice.SPICEDataPath, 'naif0012.tls') spice.unloadSpiceKernel(spice.SPICEDataPath, 'de-403-masses.tpc') diff --git a/examples/OpNavScenarios/scenariosOpNav/OpNavMC/scenario_OpNavAttODMC.py b/examples/OpNavScenarios/scenariosOpNav/OpNavMC/scenario_OpNavAttODMC.py index 2b84190802..22ab30b91e 100644 --- a/examples/OpNavScenarios/scenariosOpNav/OpNavMC/scenario_OpNavAttODMC.py +++ b/examples/OpNavScenarios/scenariosOpNav/OpNavMC/scenario_OpNavAttODMC.py @@ -141,7 +141,7 @@ def run(TheScenario): vizard.kill() - spice = TheScenario.get_DynModel().gravFactory.spiceObject + spice = TheScenario.get_DynModel().spiceObject spice.unloadSpiceKernel(spice.SPICEDataPath, 'de430.bsp') spice.unloadSpiceKernel(spice.SPICEDataPath, 'naif0012.tls') spice.unloadSpiceKernel(spice.SPICEDataPath, 'de-403-masses.tpc') diff --git a/examples/scenarioAerocapture.py b/examples/scenarioAerocapture.py index a7ebb2d53d..15a4aa6849 100644 --- a/examples/scenarioAerocapture.py +++ b/examples/scenarioAerocapture.py @@ -233,15 +233,12 @@ def run(show_plots, planetCase): # setup Gravity Body gravFactory = simIncludeGravBody.gravBodyFactory() - if planetCase == 'Earth': - planet = gravFactory.createEarth() - else: - planet = gravFactory.createMars() + planet = gravFactory.createBody(planetCase) planet.isCentralBody = True # ensure this is the central gravitational body mu = planet.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) if planetCase == 'Earth': r = 6503 * 1000 diff --git a/examples/scenarioAlbedo.py b/examples/scenarioAlbedo.py index 89bd70ea83..1a666a7540 100644 --- a/examples/scenarioAlbedo.py +++ b/examples/scenarioAlbedo.py @@ -250,7 +250,7 @@ def run(show_plots, albedoData, multipleInstrument, multiplePlanet, useEclipse, scObject.hub.v_CN_NInit = vN # m - v_CN_N scObject.hub.sigma_BNInit = [[0.0], [0.0], [0.0]] # sigma_BN_B scObject.hub.omega_BN_BInit = [[0.0], [0.0], [.5 * macros.D2R]] # rad/s - omega_BN_B - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Add spacecraft object to the simulation process scSim.AddModelToTask(simTaskName, scObject) diff --git a/examples/scenarioAsteroidArrival.py b/examples/scenarioAsteroidArrival.py index c86eba5df2..9723774872 100755 --- a/examples/scenarioAsteroidArrival.py +++ b/examples/scenarioAsteroidArrival.py @@ -290,8 +290,7 @@ def run(show_plots): # Create additional gravitational bodies gravFactory = simIncludeGravBody.gravBodyFactory() - gravFactory.createBodies(["earth", "sun"]) - sun = gravFactory.gravBodies["sun"] + gravFactory.createBodies("earth", "sun") # Set gravity body index values earthIdx = 0 @@ -300,12 +299,10 @@ def run(show_plots): # Create and configure the default SPICE support module. The first step is to store # the date and time of the start of the simulation. - gravFactory.createSpiceInterface(bskPath + '/supportData/EphemerisData/', - timeInitString, - epochInMsg=True) + spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) # Add the SPICE object to the simulation task list - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject) + scSim.AddModelToTask(simTaskName, spiceObject) # Create the asteroid custom gravitational body asteroid = gravFactory.createCustomGravObject("bennu", mu @@ -320,15 +317,15 @@ def run(show_plots): scObject.ModelTag = "bskSat" # Connect all gravitational bodies to the spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) scSim.AddModelToTask(simTaskName, scObject) # Create an ephemeris converter to convert messages of type # 'SpicePlanetStateMsgPayload' to 'EphemerisMsgPayload' ephemObject = ephemerisConverter.EphemerisConverter() ephemObject.ModelTag = 'EphemData' - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[earthIdx]) - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[sunIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[earthIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[sunIdx]) # Recall the asteroid was not created with Spice. ephemObject.addSpiceInputMsg(gravBodyEphem.planetOutMsgs[0]) scSim.AddModelToTask(simTaskName, ephemObject) diff --git a/examples/scenarioAttGuideHyperbolic.py b/examples/scenarioAttGuideHyperbolic.py index 87b86206b4..0b2b3668ed 100755 --- a/examples/scenarioAttGuideHyperbolic.py +++ b/examples/scenarioAttGuideHyperbolic.py @@ -262,7 +262,7 @@ def run(show_plots, useAltBodyFrame): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # initialize Spacecraft States with initialization variables diff --git a/examples/scenarioAttLocPoint.py b/examples/scenarioAttLocPoint.py index 5c5ad731f5..a98b281215 100755 --- a/examples/scenarioAttLocPoint.py +++ b/examples/scenarioAttLocPoint.py @@ -189,7 +189,7 @@ def run(show_plots): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # initialize Spacecraft States with initialization variables diff --git a/examples/scenarioAttitudeConstrainedManeuver.py b/examples/scenarioAttitudeConstrainedManeuver.py index f6b8c5896b..e1cbac1448 100644 --- a/examples/scenarioAttitudeConstrainedManeuver.py +++ b/examples/scenarioAttitudeConstrainedManeuver.py @@ -143,30 +143,28 @@ def run(show_plots, use2SunSensors, starTrackerFov, sunSensorFov, attitudeSetCas gravFactory = simIncludeGravBody.gravBodyFactory() # Next a series of gravitational bodies are included - gravBodies = gravFactory.createBodies(['earth', 'sun']) + gravBodies = gravFactory.createBodies('earth', 'sun') planet = gravBodies['earth'] planet.isCentralBody = True mu = planet.mu # The configured gravitational bodies are added to the spacecraft dynamics with the usual command: - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Next, the default SPICE support module is created and configured. timeInitString = "2021 JANUARY 15 00:28:30.0" - # The following is a support macro that creates a `gravFactory.spiceObject` instance - gravFactory.createSpiceInterface(bskPath +'/supportData/EphemerisData/', - timeInitString, - epochInMsg=True) + # The following is a support macro that creates a `spiceObject` instance + spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) # Earth is gravity center - gravFactory.spiceObject.zeroBase = 'Earth' + spiceObject.zeroBase = 'Earth' # The SPICE object is added to the simulation task list. scSim.AddModelToTask(simTaskName, gravFactory.spiceObject, 2) # The gravitational body is connected to the spacecraft object - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # setup the orbit using classical orbit elements oe = orbitalMotion.ClassicElements() @@ -356,8 +354,8 @@ def run(show_plots, use2SunSensors, starTrackerFov, sunSensorFov, attitudeSetCas sNavObject.scStateInMsg.subscribeTo(scObject.scStateOutMsg) CAM.scStateInMsg.subscribeTo(scObject.scStateOutMsg) CAM.vehicleConfigInMsg.subscribeTo(vcMsg) - CAM.keepOutCelBodyInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[1]) - CAM.keepInCelBodyInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[1]) + CAM.keepOutCelBodyInMsg.subscribeTo(spiceObject.planetStateOutMsgs[1]) + CAM.keepInCelBodyInMsg.subscribeTo(spiceObject.planetStateOutMsgs[1]) attError.attNavInMsg.subscribeTo(sNavObject.attOutMsg) attError.attRefInMsg.subscribeTo(CAM.attRefOutMsg) mrpControl.guidInMsg.subscribeTo(attError.attGuidOutMsg) @@ -370,12 +368,12 @@ def run(show_plots, use2SunSensors, starTrackerFov, sunSensorFov, attitudeSetCas # Boresight modules stBACObject.scStateInMsg.subscribeTo(scObject.scStateOutMsg) - stBACObject.celBodyInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[1]) + stBACObject.celBodyInMsg.subscribeTo(spiceObject.planetStateOutMsgs[1]) ssyBACObject.scStateInMsg.subscribeTo(scObject.scStateOutMsg) - ssyBACObject.celBodyInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[1]) + ssyBACObject.celBodyInMsg.subscribeTo(spiceObject.planetStateOutMsgs[1]) if use2SunSensors: sszBACObject.scStateInMsg.subscribeTo(scObject.scStateOutMsg) - sszBACObject.celBodyInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[1]) + sszBACObject.celBodyInMsg.subscribeTo(spiceObject.planetStateOutMsgs[1]) # Vizard Visualization Option # --------------------------- diff --git a/examples/scenarioAttitudeConstraintViolation.py b/examples/scenarioAttitudeConstraintViolation.py index 7b509dafb2..4fb062b249 100644 --- a/examples/scenarioAttitudeConstraintViolation.py +++ b/examples/scenarioAttitudeConstraintViolation.py @@ -189,32 +189,30 @@ def run(show_plots, use2SunSensors, starTrackerFov, sunSensorFov, attitudeSetCas gravFactory = simIncludeGravBody.gravBodyFactory() # Next a series of gravitational bodies are included - gravBodies = gravFactory.createBodies(['earth', 'sun']) + gravBodies = gravFactory.createBodies('earth', 'sun') planet = gravBodies['earth'] planet.isCentralBody = True mu = planet.mu # The configured gravitational bodies are added to the spacecraft dynamics with the usual command: - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Next, the default SPICE support module is created and configured. timeInitString = "2021 JANUARY 15 00:28:30.0" spiceTimeStringFormat = '%Y %B %d %H:%M:%S.%f' timeInit = datetime.strptime(timeInitString, spiceTimeStringFormat) - # The following is a support macro that creates a `gravFactory.spiceObject` instance - gravFactory.createSpiceInterface(bskPath +'/supportData/EphemerisData/', - timeInitString, - epochInMsg=True) + # The following is a support macro that creates a `spiceObject` instance + spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) # Earth is gravity center - gravFactory.spiceObject.zeroBase = 'Earth' + spiceObject.zeroBase = 'Earth' # The SPICE object is added to the simulation task list. - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject, 2) + scSim.AddModelToTask(simTaskName, spiceObject, 2) # The gravitational body is connected to the spacecraft object - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # setup the orbit using classical orbit elements oe = orbitalMotion.ClassicElements() @@ -404,12 +402,12 @@ def run(show_plots, use2SunSensors, starTrackerFov, sunSensorFov, attitudeSetCas # Boresight modules stBACObject.scStateInMsg.subscribeTo(scObject.scStateOutMsg) - stBACObject.celBodyInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[1]) + stBACObject.celBodyInMsg.subscribeTo(spiceObject.planetStateOutMsgs[1]) ssyBACObject.scStateInMsg.subscribeTo(scObject.scStateOutMsg) - ssyBACObject.celBodyInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[1]) + ssyBACObject.celBodyInMsg.subscribeTo(spiceObject.planetStateOutMsgs[1]) if use2SunSensors: sszBACObject.scStateInMsg.subscribeTo(scObject.scStateOutMsg) - sszBACObject.celBodyInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[1]) + sszBACObject.celBodyInMsg.subscribeTo(spiceObject.planetStateOutMsgs[1]) # Vizard Visualization Option # --------------------------- diff --git a/examples/scenarioAttitudeFeedback.py b/examples/scenarioAttitudeFeedback.py index de0de90ac6..8d6170cfac 100755 --- a/examples/scenarioAttitudeFeedback.py +++ b/examples/scenarioAttitudeFeedback.py @@ -247,7 +247,7 @@ def run(show_plots, useUnmodeledTorque, useIntGain, useKnownTorque, useCMsg): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # setup extForceTorque module # the control torque is read in through the messaging system diff --git a/examples/scenarioAttitudeFeedback2T.py b/examples/scenarioAttitudeFeedback2T.py index 7d3fd37da4..2d28d8f33a 100755 --- a/examples/scenarioAttitudeFeedback2T.py +++ b/examples/scenarioAttitudeFeedback2T.py @@ -211,7 +211,7 @@ def run(show_plots, useUnmodeledTorque, useIntGain): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # setup extForceTorque module # the control torque is read in through the messaging system diff --git a/examples/scenarioAttitudeFeedback2T_TH.py b/examples/scenarioAttitudeFeedback2T_TH.py index 4770dfc7bd..19300a2441 100755 --- a/examples/scenarioAttitudeFeedback2T_TH.py +++ b/examples/scenarioAttitudeFeedback2T_TH.py @@ -358,7 +358,7 @@ def run(show_plots, useDVThrusters): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # setup extForceTorque module # the control torque is read in through the messaging system diff --git a/examples/scenarioAttitudeFeedback2T_stateEffTH.py b/examples/scenarioAttitudeFeedback2T_stateEffTH.py index be314ecaf5..e2bcc7ddf5 100644 --- a/examples/scenarioAttitudeFeedback2T_stateEffTH.py +++ b/examples/scenarioAttitudeFeedback2T_stateEffTH.py @@ -260,7 +260,7 @@ def run(show_plots, useDVThrusters): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # setup extForceTorque module # the control torque is read in through the messaging system diff --git a/examples/scenarioAttitudeFeedbackRW.py b/examples/scenarioAttitudeFeedbackRW.py index 00d943a722..3c8ba6c906 100755 --- a/examples/scenarioAttitudeFeedbackRW.py +++ b/examples/scenarioAttitudeFeedbackRW.py @@ -424,7 +424,7 @@ def run(show_plots, useJitterSimple, useRWVoltageIO): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # add RW devices diff --git a/examples/scenarioAttitudeFeedbackRWPower.py b/examples/scenarioAttitudeFeedbackRWPower.py index 074a0d7c1f..5030381394 100755 --- a/examples/scenarioAttitudeFeedbackRWPower.py +++ b/examples/scenarioAttitudeFeedbackRWPower.py @@ -196,7 +196,7 @@ def run(show_plots, useRwPowerGeneration): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # add RW devices diff --git a/examples/scenarioAttitudeGG.py b/examples/scenarioAttitudeGG.py index d321779c15..e38aa6fa02 100755 --- a/examples/scenarioAttitudeGG.py +++ b/examples/scenarioAttitudeGG.py @@ -152,7 +152,7 @@ def run(show_plots): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # initialize Spacecraft States with initialization variables diff --git a/examples/scenarioAttitudeGuidance.py b/examples/scenarioAttitudeGuidance.py index a8885400a7..ec7ea3670f 100755 --- a/examples/scenarioAttitudeGuidance.py +++ b/examples/scenarioAttitudeGuidance.py @@ -280,7 +280,7 @@ def run(show_plots, useAltBodyFrame): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # initialize Spacecraft States with initialization variables diff --git a/examples/scenarioAttitudePrescribed.py b/examples/scenarioAttitudePrescribed.py index eb801085af..77a772567e 100755 --- a/examples/scenarioAttitudePrescribed.py +++ b/examples/scenarioAttitudePrescribed.py @@ -164,7 +164,7 @@ def run(show_plots, useAltBodyFrame): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # initialize Spacecraft States with initialization variables diff --git a/examples/scenarioAttitudeSteering.py b/examples/scenarioAttitudeSteering.py index dd6ecea8ab..c8d88b0297 100755 --- a/examples/scenarioAttitudeSteering.py +++ b/examples/scenarioAttitudeSteering.py @@ -309,7 +309,7 @@ def run(show_plots, simCase): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # add RW devices rwFactory = simIncludeRW.rwFactory() diff --git a/examples/scenarioBasicOrbit.py b/examples/scenarioBasicOrbit.py index 915d4448e6..78af5b50fe 100644 --- a/examples/scenarioBasicOrbit.py +++ b/examples/scenarioBasicOrbit.py @@ -305,7 +305,7 @@ def run(show_plots, orbitCase, useSphericalHarmonics, planetCase): mu = planet.mu # Finally, the gravitational body must be connected to the spacecraft object. This is done with - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Here the complete list of gravitational bodies is automatically assigned to the spacecraft, regardless if # it is only one body like Earth or Mars, or a list of multiple bodies. diff --git a/examples/scenarioBasicOrbitStream.py b/examples/scenarioBasicOrbitStream.py index 200ffeea0d..38f3a9ff4b 100644 --- a/examples/scenarioBasicOrbitStream.py +++ b/examples/scenarioBasicOrbitStream.py @@ -156,7 +156,7 @@ def run(show_plots, liveStream, timeStep, orbitCase, useSphericalHarmonics, plan mu = planet.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # setup orbit and simulation time diff --git a/examples/scenarioCentralBody.py b/examples/scenarioCentralBody.py index ea4690a52c..f82cc161bb 100644 --- a/examples/scenarioCentralBody.py +++ b/examples/scenarioCentralBody.py @@ -146,13 +146,11 @@ def run(show_plots, useCentral): #Set up spice with spice time UTCInit = "2012 MAY 1 00:28:30.0" - gravFactory.createSpiceInterface(bskPath +'/supportData/EphemerisData/', - UTCInit, - epochInMsg=True) - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject) + spiceObject = gravFactory.createSpiceInterface(time=UTCInit, epochInMsg=True) + scSim.AddModelToTask(simTaskName, spiceObject) # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # setup orbit and simulation time @@ -216,7 +214,7 @@ def run(show_plots, useCentral): numDataPoints = 100 samplingTime = unitTestSupport.samplingTime(simulationTime, simulationTimeStep, numDataPoints) dataLog = scObject.scStateOutMsg.recorder(samplingTime) - plLog = gravFactory.spiceObject.planetStateOutMsgs[0].recorder(samplingTime) + plLog = spiceObject.planetStateOutMsgs[0].recorder(samplingTime) scSim.AddModelToTask(simTaskName, dataLog) scSim.AddModelToTask(simTaskName, plLog) diff --git a/examples/scenarioCustomGravBody.py b/examples/scenarioCustomGravBody.py index b8c4225bcf..5a6db0c27d 100755 --- a/examples/scenarioCustomGravBody.py +++ b/examples/scenarioCustomGravBody.py @@ -173,7 +173,7 @@ def run(show_plots): # create SC object scObject = spacecraft.Spacecraft() scObject.ModelTag = "bskSat" - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) scSim.AddModelToTask(simTaskName, scObject) # setup orbit initial conditions about the asteroid diff --git a/examples/scenarioDataDemo.py b/examples/scenarioDataDemo.py index 0c240ed691..53cca25f56 100644 --- a/examples/scenarioDataDemo.py +++ b/examples/scenarioDataDemo.py @@ -112,14 +112,12 @@ def run(show_plots): mu = planet.mu sun = gravFactory.createSun() # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # setup Spice interface for some solar system bodies timeInitString = '2021 MAY 04 07:47:48.965 (UTC)' - gravFactory.createSpiceInterface(bskPath + '/supportData/EphemerisData/' - , timeInitString - ) - scenarioSim.AddModelToTask(taskName, gravFactory.spiceObject, -1) + spiceObject = gravFactory.createSpiceInterface(time=timeInitString) + scenarioSim.AddModelToTask(taskName, spiceObject, -1) # setup orbit using orbitalMotion library oe = orbitalMotion.ClassicElements() diff --git a/examples/scenarioDataToViz.py b/examples/scenarioDataToViz.py index bb6aadfa8a..046388b2bd 100755 --- a/examples/scenarioDataToViz.py +++ b/examples/scenarioDataToViz.py @@ -140,7 +140,7 @@ def run(show_plots, attType): # to show up in Vizard scObject1 = spacecraft.Spacecraft() scObject1.ModelTag = "servicer" - scObject1.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject1) scObject2 = spacecraft.Spacecraft() scObject2.ModelTag = "target" scList = [scObject1, scObject2] diff --git a/examples/scenarioDebrisReorbitET.py b/examples/scenarioDebrisReorbitET.py index fc2e3a9c2e..95d0cc49e4 100644 --- a/examples/scenarioDebrisReorbitET.py +++ b/examples/scenarioDebrisReorbitET.py @@ -152,8 +152,8 @@ def run(show_plots): mu = earth.mu # attach gravity model to spaceCraftPlus - scObjectServicer.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) - scObjectDebris.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObjectServicer) + gravFactory.addBodiesTo(scObjectDebris) # setup MSM module MSMmodule = msmForceTorque.MsmForceTorque() diff --git a/examples/scenarioDeployingPanel.py b/examples/scenarioDeployingPanel.py index ce7a1c16ea..c5d56bb8fd 100644 --- a/examples/scenarioDeployingPanel.py +++ b/examples/scenarioDeployingPanel.py @@ -127,18 +127,16 @@ def run(show_plots): # setup Earth Gravity Body gravFactory = simIncludeGravBody.gravBodyFactory() - gravBodies = gravFactory.createBodies(['earth', 'sun']) + gravBodies = gravFactory.createBodies('earth', 'sun') gravBodies['earth'].isCentralBody = True mu = gravBodies['earth'].mu sun = 1 - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) timeInitString = "2012 MAY 1 00:28:30.0" - gravFactory.createSpiceInterface(bskPath +'/supportData/EphemerisData/', - timeInitString, - epochInMsg=True) - gravFactory.spiceObject.zeroBase = 'earth' - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject) + spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) + spiceObject.zeroBase = 'earth' + scSim.AddModelToTask(simTaskName, spiceObject) # setup the orbit using classical orbit elements oe = orbitalMotion.ClassicElements() @@ -234,7 +232,7 @@ def run(show_plots): solarPanel1.panelArea = 2.0 # m^2 solarPanel1.panelEfficiency = 0.9 # 90% efficiency in power generation solarPanel1.stateInMsg.subscribeTo(panel1.hingedRigidBodyConfigLogOutMsg) - solarPanel1.sunInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[sun]) + solarPanel1.sunInMsg.subscribeTo(spiceObject.planetStateOutMsgs[sun]) solarPanel2 = simpleSolarPanel.SimpleSolarPanel() solarPanel2.ModelTag = "pwr2" @@ -242,7 +240,7 @@ def run(show_plots): solarPanel2.panelArea = 2.0 # m^2 solarPanel2.panelEfficiency = 0.9 # 90% efficiency in power generation solarPanel2.stateInMsg.subscribeTo(panel2.hingedRigidBodyConfigLogOutMsg) - solarPanel2.sunInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[sun]) + solarPanel2.sunInMsg.subscribeTo(spiceObject.planetStateOutMsgs[sun]) # # add modules to simulation task list # diff --git a/examples/scenarioDragDeorbit.py b/examples/scenarioDragDeorbit.py index 9ed54c4f0f..64d205d8d6 100644 --- a/examples/scenarioDragDeorbit.py +++ b/examples/scenarioDragDeorbit.py @@ -222,7 +222,7 @@ def run(show_plots, initialAlt=250, deorbitAlt=100, model="exponential"): gravFactory = simIncludeGravBody.gravBodyFactory() planet = gravFactory.createEarth() mu = planet.mu - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Set up a circular orbit using classical orbit elements oe = orbitalMotion.ClassicElements() diff --git a/examples/scenarioDragRendezvous.py b/examples/scenarioDragRendezvous.py index 990b8cf8be..c736bf8e09 100644 --- a/examples/scenarioDragRendezvous.py +++ b/examples/scenarioDragRendezvous.py @@ -190,20 +190,20 @@ def drag_simulator(altOffset, trueAnomOffset, densMultiplier, ctrlType='lqr', us ## Configure environmental parameters # Gravity; includes 2-body plus J2. gravFactory = simIncludeGravBody.gravBodyFactory() - gravBodies = gravFactory.createBodies(['earth']) - gravBodies['earth'].isCentralBody = True + earth = gravFactory.createEarth() + earth.isCentralBody = True + mu = earth.mu if useJ2: - gravBodies['earth'].useSphericalHarmonicsGravityModel(bskPath + '/supportData/LocalGravData/GGM03S.txt', 2) + earth.useSphericalHarmonicsGravityModel(bskPath + '/supportData/LocalGravData/GGM03S.txt', 2) + # timeInitString = '2021 MAY 04 07:47:48.965 (UTC)' - # gravFactory.createSpiceInterface(bskPath + '/supportData/EphemerisData/' - # , timeInitString - # ) - # gravFactory.spiceObject.zeroBase = 'earth' + # spiceObject = gravFactory.createSpiceInterface(time=timeInitString) + # spiceObject.zeroBase = 'earth' # Density atmosphere = exponentialAtmosphere.ExponentialAtmosphere() atmosphere.ModelTag = 'atmosphere' - # atmosphere.planetPosInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[0]) + # atmosphere.planetPosInMsg.subscribeTo(spiceObject.planetStateOutMsgs[0]) atmosphere.planetRadius = orbitalMotion.REQ_EARTH*1e3 + 300e3 # m atmosphere.envMinReach = -300e3 atmosphere.envMaxReach = +300e3 @@ -211,7 +211,6 @@ def drag_simulator(altOffset, trueAnomOffset, densMultiplier, ctrlType='lqr', us atmosphere.baseDensity = 2.022E-14 * 1000 * densMultiplier # kg/m^3 ## Set up chief, deputy orbits: - mu = gravFactory.gravBodies['earth'].mu chief_oe = orbitalMotion.ClassicElements() chief_oe.a = orbitalMotion.REQ_EARTH * 1e3 + 300e3 # meters chief_oe.e = 0. @@ -236,9 +235,9 @@ def drag_simulator(altOffset, trueAnomOffset, densMultiplier, ctrlType='lqr', us depSc, depDrag, depNav = setup_spacecraft_plant(dep_rN,dep_vN, 'lou') # Connect s/c to environment (gravity, density) - chiefSc.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) - depSc.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) - + gravFactory.addBodiesTo(chiefSc) + gravFactory.addBodiesTo(depSc) + atmosphere.addSpacecraftToModel(depSc.scStateOutMsg) depDrag.atmoDensInMsg.subscribeTo(atmosphere.envOutMsgs[-1]) atmosphere.addSpacecraftToModel(chiefSc.scStateOutMsg) @@ -247,13 +246,13 @@ def drag_simulator(altOffset, trueAnomOffset, densMultiplier, ctrlType='lqr', us # Add all dynamics stuff to dynamics task scSim.AddModelToTask(dynTaskName, atmosphere,920) # scSim.AddModelToTask(dynTaskName, ephemConverter, 921) - scSim.AddModelToTask(dynTaskName, chiefDrag,890) - scSim.AddModelToTask(dynTaskName, depDrag,891) - scSim.AddModelToTask(dynTaskName, chiefSc,810) - scSim.AddModelToTask(dynTaskName, depSc,811) - scSim.AddModelToTask(dynTaskName, chiefNav,800) - scSim.AddModelToTask(dynTaskName, depNav,801) - # scSim.AddModelToTask(dynTaskName, gravFactory.spiceObject, 999) + scSim.AddModelToTask(dynTaskName, chiefDrag, 890) + scSim.AddModelToTask(dynTaskName, depDrag, 891) + scSim.AddModelToTask(dynTaskName, chiefSc, 810) + scSim.AddModelToTask(dynTaskName, depSc, 811) + scSim.AddModelToTask(dynTaskName, chiefNav, 800) + scSim.AddModelToTask(dynTaskName, depNav, 801) + # scSim.AddModelToTask(dynTaskName, spiceObject, 999) ## FSW setup # Chief S/C diff --git a/examples/scenarioFlybySpice.py b/examples/scenarioFlybySpice.py index 687e2ae435..33aa98346c 100644 --- a/examples/scenarioFlybySpice.py +++ b/examples/scenarioFlybySpice.py @@ -50,18 +50,18 @@ Next the custom Spice file must be loaded. The ``loadSpiceKernel()`` method of class ``SpiceInterface`` is called to load the file. This method accepts the file name and the path to the desired file to load:: - gravFactory.spiceObject.loadSpiceKernel("max_21T01.bsp", os.path.join(path, "dataForExamples", "Spice/")) + spiceObject.loadSpiceKernel("max_21T01.bsp", os.path.join(path, "dataForExamples", "Spice/")) Note that setting up the orbital elements and initial conditions using the ``orbitalMotion`` module is no longer needed. After the Spice file is loaded, connect the configured Spice translational output message to the spacecraft object's ``transRefInMsg`` input message:: - scObject.transRefInMsg.subscribeTo(gravFactory.spiceObject.transRefStateOutMsgs[0]) + scObject.transRefInMsg.subscribeTo(spiceObject.transRefStateOutMsgs[0]) Finally, add the Spice object to the simulation task list:: - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject) + scSim.AddModelToTask(simTaskName, spiceObject) Implementing Attitude Pointing Modes ------------------------------------ @@ -74,11 +74,11 @@ ephemObject = ephemerisConverter.EphemerisConverter() ephemObject.ModelTag = 'EphemData' - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[earthIdx]) - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[sunIdx]) - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[moonIdx]) - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[venusIdx]) - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[marsIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[earthIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[sunIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[moonIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[venusIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[marsIdx]) scSim.AddModelToTask(simTaskName, ephemObject) Next, the ``extForceTorque`` and ``simpleNav`` modules must be set configured:: @@ -214,7 +214,7 @@ def runVelocityPointing(simTime, planetMsg): Ensure to unload the Spice kernel at the end of each simulation:: - gravFactory.spiceObject.unloadSpiceKernel("max_21T01.bsp", os.path.join(path, "Data", "Spice/")) + spiceObject.unloadSpiceKernel("max_21T01.bsp", os.path.join(path, "Data", "Spice/")) Simulation Visualization In Vizard @@ -295,10 +295,10 @@ def run(planetCase): # Create gravitational bodies gravFactory = simIncludeGravBody.gravBodyFactory() - gravFactory.createBodies(["earth", "sun", "moon", "venus", "mars barycenter"]) + gravFactory.createBodies("earth", "sun", "moon", "venus", "mars barycenter") earth = gravFactory.gravBodies["earth"] earth.isCentralBody = True - scObject.gravField.setGravBodies(gravityEffector.GravBodyVector(list(gravFactory.gravBodies.values()))) + gravFactory.addBodiesTo(scObject) # Define planet gravitational parameters needed for the attitude pointing modes earthMu = earth.mu @@ -325,34 +325,32 @@ def run(planetCase): exit(1) # Create the Spice interface and add the correct path to the ephemeris data - gravFactory.createSpiceInterface(bskPath + '/supportData/EphemerisData/', - timeInitString, - epochInMsg=True) - gravFactory.spiceObject.zeroBase = 'Earth' + spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) + spiceObject.zeroBase = 'Earth' # Specify Spice spacecraft name scNames = ["-60000"] - gravFactory.spiceObject.addSpacecraftNames(messaging.StringVector(scNames)) + spiceObject.addSpacecraftNames(messaging.StringVector(scNames)) # Load the custom spacecraft trajectory Spice file using the SpiceInterface class loadSpiceKernel() method - gravFactory.spiceObject.loadSpiceKernel("spacecraft_21T01.bsp", os.path.join(path, "dataForExamples", "Spice/")) + spiceObject.loadSpiceKernel("spacecraft_21T01.bsp", os.path.join(path, "dataForExamples", "Spice/")) # Connect the configured Spice translational output message to spacecraft object's transRefInMsg input message - scObject.transRefInMsg.subscribeTo(gravFactory.spiceObject.transRefStateOutMsgs[0]) + scObject.transRefInMsg.subscribeTo(spiceObject.transRefStateOutMsgs[0]) # Add the Spice and spacecraft objects to the simulation task list. - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject) + scSim.AddModelToTask(simTaskName, spiceObject) scSim.AddModelToTask(simTaskName, scObject) # Create an ephemeris converter to convert Spice messages of type plantetStateOutMsgs to ephemeris messages # of type ephemOutMsgs. This converter is required for the velocityPoint and locationPointing modules. ephemObject = ephemerisConverter.EphemerisConverter() ephemObject.ModelTag = 'EphemData' - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[earthIdx]) - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[sunIdx]) - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[moonIdx]) - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[venusIdx]) - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[marsIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[earthIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[sunIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[moonIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[venusIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[marsIdx]) scSim.AddModelToTask(simTaskName, ephemObject) # Define the simulation inertia @@ -564,7 +562,7 @@ def runSensorSciencePointing(simTime): # Unload custom Spice kernel at the end of each simulation gravFactory.unloadSpiceKernels() - gravFactory.spiceObject.unloadSpiceKernel("spacecraft_21T01.bsp", os.path.join(path, "Data", "Spice/")) + spiceObject.unloadSpiceKernel("spacecraft_21T01.bsp", os.path.join(path, "Data", "Spice/")) return diff --git a/examples/scenarioFormationBasic.py b/examples/scenarioFormationBasic.py index 2fc7487220..87819450a3 100755 --- a/examples/scenarioFormationBasic.py +++ b/examples/scenarioFormationBasic.py @@ -277,9 +277,9 @@ def run(show_plots): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) - scObject2.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) - scObject3.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) + gravFactory.addBodiesTo(scObject2) + gravFactory.addBodiesTo(scObject3) # # add RW devices diff --git a/examples/scenarioFormationMeanOEFeedback.py b/examples/scenarioFormationMeanOEFeedback.py index 66b54a1631..b09b72e357 100644 --- a/examples/scenarioFormationMeanOEFeedback.py +++ b/examples/scenarioFormationMeanOEFeedback.py @@ -127,13 +127,12 @@ def run(show_plots, useClassicElem, numOrbits): # grav gravFactory = simIncludeGravBody.gravBodyFactory() - gravBodies = gravFactory.createBodies(['earth']) - gravBodies['earth'].isCentralBody = True - gravBodies['earth'].useSphericalHarmonicsGravityModel(bskPath + '/supportData/LocalGravData/GGM03S.txt', 2) - scObject.gravField.gravBodies = spacecraft.GravBodyVector( - list(gravFactory.gravBodies.values())) - scObject2.gravField.gravBodies = spacecraft.GravBodyVector( - list(gravFactory.gravBodies.values())) + earth = gravFactory.createEarth() + earth.isCentralBody = True + mu = earth.mu + earth.useSphericalHarmonicsGravityModel(bskPath + '/supportData/LocalGravData/GGM03S.txt', 2) + gravFactory.addBodiesTo(scObject) + gravFactory.addBodiesTo(scObject2) # extObj extFTObject2 = extForceTorque.ExtForceTorque() @@ -179,7 +178,6 @@ def run(show_plots, useClassicElem, numOrbits): scSim.AddModelToTask(fswTaskName, meanOEFeedbackObj, 1) # ----- Setup spacecraft initial states ----- # - mu = gravFactory.gravBodies['earth'].mu oe = orbitalMotion.ClassicElements() oe.a = 11000 * 1e3 # meters oe.e = 0.4 diff --git a/examples/scenarioFormationReconfig.py b/examples/scenarioFormationReconfig.py index 083b58a593..ad6866f2d4 100644 --- a/examples/scenarioFormationReconfig.py +++ b/examples/scenarioFormationReconfig.py @@ -136,12 +136,11 @@ def run(show_plots, useRefAttitude): # grav gravFactory = simIncludeGravBody.gravBodyFactory() - gravBodies = gravFactory.createBodies(['earth']) - gravBodies['earth'].isCentralBody = True - scObject.gravField.gravBodies = spacecraft.GravBodyVector( - list(gravFactory.gravBodies.values())) - scObject2.gravField.gravBodies = spacecraft.GravBodyVector( - list(gravFactory.gravBodies.values())) + earth = gravFactory.createEarth() + earth.isCentralBody = True + mu = earth.mu + gravFactory.addBodiesTo(scObject) + gravFactory.addBodiesTo(scObject2) # thruster thrusterEffector2 = thrusterDynamicEffector.ThrusterDynamicEffector() @@ -229,7 +228,6 @@ def run(show_plots, useRefAttitude): mrpControl.integralLimit = 2. / mrpControl.Ki * 0.1 # ----- Setup spacecraft initial states ----- # - mu = gravFactory.gravBodies['earth'].mu oe = orbitalMotion.ClassicElements() oe.a = 11000*1e3 # meters oe.e = 0.4 diff --git a/examples/scenarioFuelSlosh.py b/examples/scenarioFuelSlosh.py index 35e1b64a3f..057b87ff47 100755 --- a/examples/scenarioFuelSlosh.py +++ b/examples/scenarioFuelSlosh.py @@ -290,7 +290,7 @@ def run(show_plots, damping_parameter, timeStep): mu = planet.mu # attach gravity to the spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # initialize orbital elements oe = orbitalMotion.ClassicElements() diff --git a/examples/scenarioGroundDownlink.py b/examples/scenarioGroundDownlink.py index 09e12e0f45..e6dae0b29b 100644 --- a/examples/scenarioGroundDownlink.py +++ b/examples/scenarioGroundDownlink.py @@ -104,14 +104,13 @@ def run(show_plots): gravFactory = simIncludeGravBody.gravBodyFactory() planet = gravFactory.createEarth() planet.isCentralBody = True # ensure this is the central gravitational body + planet.useSphericalHarmonicsGravityModel(bskPath + '/supportData/LocalGravData/GGM03S-J2-only.txt', 2) mu = planet.mu # setup Spice interface for some solar system bodies timeInitString = '2020 MAY 21 18:28:03 (UTC)' - gravFactory.createSpiceInterface(bskPath + '/supportData/EphemerisData/' - , timeInitString - ) - scenarioSim.AddModelToTask(taskName, gravFactory.spiceObject, -1) + spiceObject = gravFactory.createSpiceInterface(time=timeInitString) + scenarioSim.AddModelToTask(taskName, spiceObject, -1) # setup orbit using orbitalMotion library @@ -136,14 +135,14 @@ def run(show_plots): scenarioSim.AddModelToTask(taskName, scObject, 1) # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Create the ground location groundStation = groundLocation.GroundLocation() groundStation.ModelTag = "BoulderGroundStation" groundStation.planetRadius = astroFunctions.E_radius*1e3 groundStation.specifyLocation(np.radians(40.009971), np.radians(-105.243895), 1624) - groundStation.planetInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[0]) + groundStation.planetInMsg.subscribeTo(spiceObject.planetStateOutMsgs[0]) groundStation.minimumElevation = np.radians(10.) groundStation.maximumRange = 1e9 groundStation.addSpacecraftToModel(scObject.scStateOutMsg) @@ -204,7 +203,7 @@ def run(show_plots): # Also log attitude/orbit parameters dataLog = scObject.scStateOutMsg.recorder() - plLog = gravFactory.spiceObject.planetStateOutMsgs[0].recorder() + plLog = spiceObject.planetStateOutMsgs[0].recorder() gsLog = groundStation.currentGroundStateOutMsg.recorder() gsAccessLog = groundStation.accessOutMsgs[-1].recorder() scenarioSim.AddModelToTask(taskName, dataLog) diff --git a/examples/scenarioGroundLocationImaging.py b/examples/scenarioGroundLocationImaging.py index 5baa2453e7..cd59306966 100644 --- a/examples/scenarioGroundLocationImaging.py +++ b/examples/scenarioGroundLocationImaging.py @@ -232,9 +232,7 @@ def run(show_plots): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector( - list(gravFactory.gravBodies.values()) - ) + gravFactory.addBodiesTo(scObject) # # initialize Spacecraft States with initialization variables diff --git a/examples/scenarioGroundMapping.py b/examples/scenarioGroundMapping.py index 76bc8c1f39..512db11bff 100644 --- a/examples/scenarioGroundMapping.py +++ b/examples/scenarioGroundMapping.py @@ -234,16 +234,12 @@ def run(show_plots, useCentral): earth.isCentralBody = useCentral # ensure this is the central gravitational body mu = earth.mu - timeInitString = "2020 MAY 21 18:28:03 (UTC)" - gravFactory.createSpiceInterface( - bskPath + "/supportData/EphemerisData/", timeInitString - ) - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject, ModelPriority=100) + timeInitString = '2020 MAY 21 18:28:03 (UTC)' + spiceObject = gravFactory.createSpiceInterface(time=timeInitString) + scSim.AddModelToTask(simTaskName, spiceObject, -1) # Attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector( - list(gravFactory.gravBodies.values()) - ) + gravFactory.addBodiesTo(scObject) # setup the orbit using classical orbit elements oe = orbitalMotion.ClassicElements() @@ -298,7 +294,7 @@ def run(show_plots, useCentral): groundMap.nHat_B = [0, 0, 1] groundMap.halfFieldOfView = np.radians(22.5) groundMap.scStateInMsg.subscribeTo(scObject.scStateOutMsg) - groundMap.planetInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[0]) + groundMap.planetInMsg.subscribeTo(spiceObject.planetStateOutMsgs[0]) scSim.AddModelToTask(simTaskName, groundMap, 1) # Create the mapping instrument @@ -320,8 +316,8 @@ def run(show_plots, useCentral): # Create the ephemeris converter module ephemConverter = ephemerisConverter.EphemerisConverter() ephemConverter.ModelTag = "ephemConverter" - ephemConverter.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[0]) - scSim.AddModelToTask(simTaskName, ephemConverter, ModelPriority=98) + ephemConverter.addSpiceInputMsg(spiceObject.planetStateOutMsgs[0]) + scSim.AddModelToTask(simTaskName, ephemConverter) # Setup nadir pointing guidance module locPoint = locationPointing.locationPointing() @@ -361,7 +357,7 @@ def run(show_plots, useCentral): snAttLog = sNavObject.attOutMsg.recorder() snTransLog = sNavObject.transOutMsg.recorder() scLog = scObject.scStateOutMsg.recorder() - planetLog = gravFactory.spiceObject.planetStateOutMsgs[0].recorder() + planetLog = spiceObject.planetStateOutMsgs[0].recorder() storageLog = storageUnit.storageUnitDataOutMsg.recorder() # Setup the logging for the mapping locations diff --git a/examples/scenarioHelioTransSpice.py b/examples/scenarioHelioTransSpice.py index 1ffb58dc05..6f7d03cb9c 100644 --- a/examples/scenarioHelioTransSpice.py +++ b/examples/scenarioHelioTransSpice.py @@ -38,22 +38,22 @@ Next, the ``loadSpiceKernel()`` method of class SpiceInterface should be called to load the custom Spice files. This method accepts a file name and the path to the desired file to load:: - gravFactory.spiceObject.loadSpiceKernel(file, os.path.join(path, "dataForExamples", "Spice/")) + spiceObject.loadSpiceKernel(file, os.path.join(path, "dataForExamples", "Spice/")) Note that setting up the orbital elements and initial conditions using the ``orbitalMotion`` module is no longer needed. After the Spice files are loaded, the final step is to connect the configured Spice translational output message to the spacecraft object's ``transRefInMsg`` input message:: - scObject.transRefInMsg.subscribeTo(gravFactory.spiceObject.transRefStateOutMsgs[0]) + scObject.transRefInMsg.subscribeTo(spiceObject.transRefStateOutMsgs[0]) Finally, add the Spice object to the simulation task list:: - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject) + scSim.AddModelToTask(simTaskName, spiceObject) Ensure to unload the Spice kernels at the end of each simulation:: - gravFactory.spiceObject.unloadSpiceKernel(file, os.path.join(path, "dataForExamples", "Spice/")) + spiceObject.unloadSpiceKernel(file, os.path.join(path, "dataForExamples", "Spice/")) Simulation Visualization In Vizard ---------------------------------- @@ -119,31 +119,29 @@ def run(): # Create gravitational bodies gravFactory = simIncludeGravBody.gravBodyFactory() - gravFactory.createBodies(["earth", "sun", "venus", "mars barycenter"]) - scObject.gravField.setGravBodies(gravityEffector.GravBodyVector(list(gravFactory.gravBodies.values()))) + gravFactory.createBodies("earth", "sun", "venus", "mars barycenter") + gravFactory.addBodiesTo(scObject) # Create and configure the default SPICE support module. timeInitString = "2028 February 24 5:30:30.0" # Store the date and time of the start of the simulation. - gravFactory.createSpiceInterface(bskPath + '/supportData/EphemerisData/', - timeInitString, - epochInMsg=True) + spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) # Create a string list of all custom Spice files to upload customSpiceFiles = ["spacecraft_21T01.bsp"] # Load the custom Spice files using the SpiceInterface class loadSpiceKernel() method for file in customSpiceFiles: - gravFactory.spiceObject.loadSpiceKernel(file, os.path.join(path, "dataForExamples", "Spice/")) + spiceObject.loadSpiceKernel(file, os.path.join(path, "dataForExamples", "Spice/")) # Add spacecraft name scNames = ["-60000"] - gravFactory.spiceObject.addSpacecraftNames(messaging.StringVector(scNames)) + spiceObject.addSpacecraftNames(messaging.StringVector(scNames)) # Connect the configured Spice translational output message to spacecraft object's transRefInMsg input message - scObject.transRefInMsg.subscribeTo(gravFactory.spiceObject.transRefStateOutMsgs[0]) + scObject.transRefInMsg.subscribeTo(spiceObject.transRefStateOutMsgs[0]) # Add the Spice and spacecraft objects to the simulation task list. - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject) + scSim.AddModelToTask(simTaskName, spiceObject) scSim.AddModelToTask(simTaskName, scObject) # define the spacecraft inertia and other parameters @@ -195,7 +193,7 @@ def run(): # Unload custom Spice kernels at the end of each simulation gravFactory.unloadSpiceKernels() for file in customSpiceFiles: - gravFactory.spiceObject.unloadSpiceKernel(file, os.path.join(path, "Data", "Spice/")) + spiceObject.unloadSpiceKernel(file, os.path.join(path, "Data", "Spice/")) return diff --git a/examples/scenarioHingedRigidBody.py b/examples/scenarioHingedRigidBody.py index c2f3663283..cb8ceb7ee9 100755 --- a/examples/scenarioHingedRigidBody.py +++ b/examples/scenarioHingedRigidBody.py @@ -209,7 +209,7 @@ def run(show_plots): mu = earth.mu # Attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Adding the HingedRigidBody State Effector scSim.panel1 = hingedRigidBodyStateEffector.HingedRigidBodyStateEffector() diff --git a/examples/scenarioHohmann.py b/examples/scenarioHohmann.py index 7a4b53e891..6b325fe003 100644 --- a/examples/scenarioHohmann.py +++ b/examples/scenarioHohmann.py @@ -214,7 +214,7 @@ def run(show_plots, rFirst, rSecond): timeInitString, epochInMsg=True) gravFactory.spiceObject.zeroBase = 'Earth' - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Add ephemeris for Hill frame ephemObject = ephemerisConverter.EphemerisConverter() diff --git a/examples/scenarioInertialSpiral.py b/examples/scenarioInertialSpiral.py index da0ae08b36..c26dc3d566 100644 --- a/examples/scenarioInertialSpiral.py +++ b/examples/scenarioInertialSpiral.py @@ -157,7 +157,7 @@ def run(show_plots): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # set up extForceTorque module # the control torque is read in through the messaging system diff --git a/examples/scenarioIntegrators.py b/examples/scenarioIntegrators.py index df9620d082..9380a17f85 100755 --- a/examples/scenarioIntegrators.py +++ b/examples/scenarioIntegrators.py @@ -256,9 +256,7 @@ def run(show_plots, integratorCase): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector( - list(gravFactory.gravBodies.values()) - ) + gravFactory.addBodiesTo(scObject) # # setup orbit and simulation time diff --git a/examples/scenarioIntegratorsComparison.py b/examples/scenarioIntegratorsComparison.py index ab827e6273..747d7102fd 100644 --- a/examples/scenarioIntegratorsComparison.py +++ b/examples/scenarioIntegratorsComparison.py @@ -303,9 +303,7 @@ def get_solution(integrator, time_step): earth.isCentralBody = True # ensure this is the central gravitational body # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector( - list(gravFactory.gravBodies.values()) - ) + gravFactory.addBodiesTo(scObject) rN, vN, _ = get_initial_conditions() diff --git a/examples/scenarioJupiterArrival.py b/examples/scenarioJupiterArrival.py index 0923455313..fd67d2ac34 100644 --- a/examples/scenarioJupiterArrival.py +++ b/examples/scenarioJupiterArrival.py @@ -123,7 +123,7 @@ def run(show_plots): gravFactory = simIncludeGravBody.gravBodyFactory() jupiter = gravFactory.createJupiter() jupiter.isCentralBody = True - scObject.gravField.setGravBodies(gravityEffector.GravBodyVector(list(gravFactory.gravBodies.values()))) + gravFactory.addBodiesTo(scObject) scSim.AddModelToTask(simTaskName, scObject) # diff --git a/examples/scenarioLagrangePointOrbit.py b/examples/scenarioLagrangePointOrbit.py index 76efa17c67..569b3bae02 100644 --- a/examples/scenarioLagrangePointOrbit.py +++ b/examples/scenarioLagrangePointOrbit.py @@ -182,29 +182,27 @@ def run(lagrangePoint, nOrbits, timestep, showPlots=True): # Setup gravity factory and gravity bodies # Include bodies as a list of SPICE names gravFactory = simIncludeGravBody.gravBodyFactory() - gravBodies = gravFactory.createBodies(['moon', 'earth']) + gravBodies = gravFactory.createBodies('moon', 'earth') gravBodies['earth'].isCentralBody = True # Add gravity bodies to the spacecraft dynamics - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Create default SPICE module, specify start date/time. timeInitString = "2022 August 31 15:00:00.0" spiceTimeStringFormat = '%Y %B %d %H:%M:%S.%f' timeInit = datetime.strptime(timeInitString, spiceTimeStringFormat) - gravFactory.createSpiceInterface(bskPath + '/supportData/EphemerisData/', - timeInitString, - epochInMsg=True) - gravFactory.spiceObject.zeroBase = 'Earth' + spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) + spiceObject.zeroBase = 'Earth' # Add SPICE object to the simulation task list - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject, 1) + scSim.AddModelToTask(simTaskName, spiceObject, 1) # Import SPICE ephemeris data into the python environment - pyswice.furnsh_c(gravFactory.spiceObject.SPICEDataPath + 'de430.bsp') # solar system bodies - pyswice.furnsh_c(gravFactory.spiceObject.SPICEDataPath + 'naif0012.tls') # leap second file - pyswice.furnsh_c(gravFactory.spiceObject.SPICEDataPath + 'de-403-masses.tpc') # solar system masses - pyswice.furnsh_c(gravFactory.spiceObject.SPICEDataPath + 'pck00010.tpc') # generic Planetary Constants Kernel + pyswice.furnsh_c(spiceObject.SPICEDataPath + 'de430.bsp') # solar system bodies + pyswice.furnsh_c(spiceObject.SPICEDataPath + 'naif0012.tls') # leap second file + pyswice.furnsh_c(spiceObject.SPICEDataPath + 'de-403-masses.tpc') # solar system masses + pyswice.furnsh_c(spiceObject.SPICEDataPath + 'pck00010.tpc') # generic Planetary Constants Kernel # Set spacecraft ICs # Use Earth data @@ -374,10 +372,10 @@ def run(lagrangePoint, nOrbits, timestep, showPlots=True): # Unload spice libraries gravFactory.unloadSpiceKernels() - pyswice.unload_c(gravFactory.spiceObject.SPICEDataPath + 'de430.bsp') # solar system bodies - pyswice.unload_c(gravFactory.spiceObject.SPICEDataPath + 'naif0012.tls') # leap second file - pyswice.unload_c(gravFactory.spiceObject.SPICEDataPath + 'de-403-masses.tpc') # solar system masses - pyswice.unload_c(gravFactory.spiceObject.SPICEDataPath + 'pck00010.tpc') # generic Planetary Constants Kernel + pyswice.unload_c(spiceObject.SPICEDataPath + 'de430.bsp') # solar system bodies + pyswice.unload_c(spiceObject.SPICEDataPath + 'naif0012.tls') # leap second file + pyswice.unload_c(spiceObject.SPICEDataPath + 'de-403-masses.tpc') # solar system masses + pyswice.unload_c(spiceObject.SPICEDataPath + 'pck00010.tpc') # generic Planetary Constants Kernel return figureList diff --git a/examples/scenarioMagneticFieldCenteredDipole.py b/examples/scenarioMagneticFieldCenteredDipole.py index 68fa992071..5a50d8ce04 100644 --- a/examples/scenarioMagneticFieldCenteredDipole.py +++ b/examples/scenarioMagneticFieldCenteredDipole.py @@ -221,7 +221,7 @@ def run(show_plots, orbitCase, planetCase): req = planet.radEquator # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # create the magnetic field diff --git a/examples/scenarioMagneticFieldWMM.py b/examples/scenarioMagneticFieldWMM.py index eb5a7ccfa3..09a8309180 100644 --- a/examples/scenarioMagneticFieldWMM.py +++ b/examples/scenarioMagneticFieldWMM.py @@ -193,7 +193,7 @@ def run(show_plots, orbitCase): req = planet.radEquator # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # create the magnetic field magModule = magneticFieldWMM.MagneticFieldWMM() diff --git a/examples/scenarioMomentumDumping.py b/examples/scenarioMomentumDumping.py index a474e95882..d272aef222 100644 --- a/examples/scenarioMomentumDumping.py +++ b/examples/scenarioMomentumDumping.py @@ -136,30 +136,28 @@ def run(show_plots): gravFactory = simIncludeGravBody.gravBodyFactory() # Next a series of gravitational bodies are included - gravBodies = gravFactory.createBodies(['earth', 'sun']) + gravBodies = gravFactory.createBodies('earth', 'sun') planet = gravBodies['earth'] planet.isCentralBody = True mu = planet.mu # The configured gravitational bodies are added to the spacecraft dynamics with the usual command: - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Next, the default SPICE support module is created and configured. timeInitString = "2022 JUNE 27 00:00:00.0" - # The following is a support macro that creates a `gravFactory.spiceObject` instance - gravFactory.createSpiceInterface(bskPath +'/supportData/EphemerisData/', - timeInitString, - epochInMsg=True) + # The following is a support macro that creates a `spiceObject` instance + spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) # Earth is gravity center - gravFactory.spiceObject.zeroBase = 'Earth' + spiceObject.zeroBase = 'Earth' # The SPICE object is added to the simulation task list. - scSim.AddModelToTask(fswTask, gravFactory.spiceObject, 2) + scSim.AddModelToTask(fswTask, spiceObject, 2) # The gravitational body is connected to the spacecraft object - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # setup the orbit using classical orbit elements oe = orbitalMotion.ClassicElements() diff --git a/examples/scenarioMonteCarloAttRW.py b/examples/scenarioMonteCarloAttRW.py index a93f494379..0064937055 100644 --- a/examples/scenarioMonteCarloAttRW.py +++ b/examples/scenarioMonteCarloAttRW.py @@ -452,7 +452,7 @@ def createScenarioAttitudeFeedbackRW(): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # add RW devices # diff --git a/examples/scenarioMtbMomentumManagement.py b/examples/scenarioMtbMomentumManagement.py index 35918e0308..dccc8f4503 100755 --- a/examples/scenarioMtbMomentumManagement.py +++ b/examples/scenarioMtbMomentumManagement.py @@ -283,7 +283,7 @@ def run(show_plots): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # add RW devices diff --git a/examples/scenarioMtbMomentumManagementSimple.py b/examples/scenarioMtbMomentumManagementSimple.py index e9d280d2c8..4543c6f780 100755 --- a/examples/scenarioMtbMomentumManagementSimple.py +++ b/examples/scenarioMtbMomentumManagementSimple.py @@ -290,7 +290,7 @@ def run(show_plots): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # add RW devices diff --git a/examples/scenarioOrbitManeuver.py b/examples/scenarioOrbitManeuver.py index 32c71c7e3b..0af2f1cb5d 100755 --- a/examples/scenarioOrbitManeuver.py +++ b/examples/scenarioOrbitManeuver.py @@ -164,7 +164,7 @@ def run(show_plots, maneuverCase): earth.isCentralBody = True # ensure this is the central gravitational body # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # setup orbit and simulation time diff --git a/examples/scenarioOrbitMultiBody.py b/examples/scenarioOrbitMultiBody.py index 39dabf93eb..ee50ea851f 100755 --- a/examples/scenarioOrbitMultiBody.py +++ b/examples/scenarioOrbitMultiBody.py @@ -181,14 +181,15 @@ def run(show_plots, scCase): # Next a series of gravitational bodies are included. Note that it is convenient to include them as a # list of SPICE names. The Earth is included in this scenario with the # spherical harmonics turned on. Note that this is true for both spacecraft simulations. - gravBodies = gravFactory.createBodies(['earth', 'mars barycenter', 'sun', 'moon', "jupiter barycenter"]) + gravBodies = gravFactory.createBodies('earth', 'mars barycenter', 'sun', 'moon', "jupiter barycenter") gravBodies['earth'].isCentralBody = True # Other possible ways to access specific gravity bodies include the below # earth = gravBodies['earth'] # earth = gravFactory.createEarth() gravBodies['earth'].useSphericalHarmonicsGravityModel(bskPath + '/supportData/LocalGravData/GGM03S.txt', 100) + # The configured gravitational bodies are added to the spacecraft dynamics with the usual command: - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Next, the default SPICE support module is created and configured. The first step is to store # the date and time of the start of the simulation. @@ -196,13 +197,11 @@ def run(show_plots, scCase): spiceTimeStringFormat = '%Y %B %d %H:%M:%S.%f' timeInit = datetime.strptime(timeInitString, spiceTimeStringFormat) - # The following is a support macro that creates a `gravFactory.spiceObject` instance, and fills in typical + # The following is a support macro that creates a `spiceObject` instance, and fills in typical # default parameters. By setting the epochInMsg argument, this macro provides an epoch date/time # message as well. The spiceObject is set to subscribe to this epoch message. Using the epoch message # makes it trivial to synchronize the epoch information across multiple modules. - gravFactory.createSpiceInterface(bskPath +'/supportData/EphemerisData/', - timeInitString, - epochInMsg=True) + spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) # By default the SPICE object will use the solar system barycenter as the inertial origin # If the spacecraft() output is desired relative to another celestial object, the zeroBase string @@ -213,10 +212,10 @@ def run(show_plots, scCase): # or SSB for short. The spacecraft() state output message is relative to this SBB frame by default. To change # this behavior, the zero based point must be redefined from SBB to another body. # In this simulation we use the Earth. - gravFactory.spiceObject.zeroBase = 'Earth' + spiceObject.zeroBase = 'Earth' # Finally, the SPICE object is added to the simulation task list. - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject) + scSim.AddModelToTask(simTaskName, spiceObject) # Next we would like to import spacecraft specific SPICE ephemeris data into the python environment. This is done # such that the BSK computed trajectories can be compared in python with the equivalent SPICE directories. @@ -233,11 +232,11 @@ def run(show_plots, scCase): else: # default case scEphemerisFileName = 'hst_edited.bsp' scSpiceName = 'HUBBLE SPACE TELESCOPE' - pyswice.furnsh_c(gravFactory.spiceObject.SPICEDataPath + scEphemerisFileName) # Hubble Space Telescope data - pyswice.furnsh_c(gravFactory.spiceObject.SPICEDataPath + 'de430.bsp') # solar system bodies - pyswice.furnsh_c(gravFactory.spiceObject.SPICEDataPath + 'naif0012.tls') # leap second file - pyswice.furnsh_c(gravFactory.spiceObject.SPICEDataPath + 'de-403-masses.tpc') # solar system masses - pyswice.furnsh_c(gravFactory.spiceObject.SPICEDataPath + 'pck00010.tpc') # generic Planetary Constants Kernel + pyswice.furnsh_c(spiceObject.SPICEDataPath + scEphemerisFileName) # Hubble Space Telescope data + pyswice.furnsh_c(spiceObject.SPICEDataPath + 'de430.bsp') # solar system bodies + pyswice.furnsh_c(spiceObject.SPICEDataPath + 'naif0012.tls') # leap second file + pyswice.furnsh_c(spiceObject.SPICEDataPath + 'de-403-masses.tpc') # solar system masses + pyswice.furnsh_c(spiceObject.SPICEDataPath + 'pck00010.tpc') # generic Planetary Constants Kernel # # Setup spacecraft initial states @@ -393,7 +392,7 @@ def run(show_plots, scCase): else: scState = 1000.0 * spkRead(scSpiceName, - gravFactory.spiceObject.getCurrentTimeString(), + spiceObject.getCurrentTimeString(), 'J2000', 'EARTH') rTrue = scState[0:3] @@ -434,10 +433,10 @@ def run(show_plots, scCase): # gravFactory.unloadSpiceKernels() pyswice.unload_c(scEphemerisFileName) - pyswice.unload_c(gravFactory.spiceObject.SPICEDataPath + 'de430.bsp') # solar system bodies - pyswice.unload_c(gravFactory.spiceObject.SPICEDataPath + 'naif0012.tls') # leap second file - pyswice.unload_c(gravFactory.spiceObject.SPICEDataPath + 'de-403-masses.tpc') # solar system masses - pyswice.unload_c(gravFactory.spiceObject.SPICEDataPath + 'pck00010.tpc') # generic Planetary Constants Kernel + pyswice.unload_c(spiceObject.SPICEDataPath + 'de430.bsp') # solar system bodies + pyswice.unload_c(spiceObject.SPICEDataPath + 'naif0012.tls') # leap second file + pyswice.unload_c(spiceObject.SPICEDataPath + 'de-403-masses.tpc') # solar system masses + pyswice.unload_c(spiceObject.SPICEDataPath + 'pck00010.tpc') # generic Planetary Constants Kernel # each test method requires a single assert method to be called # this check below just makes sure no sub-test failures were found diff --git a/examples/scenarioPatchedConics.py b/examples/scenarioPatchedConics.py index e04472e2af..45131671e6 100644 --- a/examples/scenarioPatchedConics.py +++ b/examples/scenarioPatchedConics.py @@ -144,7 +144,7 @@ def run(show_plots): # In order to specify which body the spacecraft position and velocities are integrated relative to, the `isCentralBody` # flag is used. earth.isCentralBody = True - scObject.gravField.setGravBodies(gravityEffector.GravBodyVector(list(gravFactory.gravBodies.values()))) + gravFactory.addBodiesTo(scObject) scSim.AddModelToTask(simTaskName, scObject) # diff --git a/examples/scenarioPowerDemo.py b/examples/scenarioPowerDemo.py index 0a49986f19..5214877ad3 100644 --- a/examples/scenarioPowerDemo.py +++ b/examples/scenarioPowerDemo.py @@ -132,17 +132,16 @@ def run(show_plots): mu = planet.mu sun = gravFactory.createSun() # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # setup Spice interface for some solar system bodies timeInitString = '2021 MAY 04 07:47:48.965 (UTC)' - gravFactory.createSpiceInterface(bskPath +'/supportData/EphemerisData/', - timeInitString) - scenarioSim.AddModelToTask(taskName, gravFactory.spiceObject, -1) + spiceObject = gravFactory.createSpiceInterface(time=timeInitString) + scenarioSim.AddModelToTask(taskName, spiceObject, -1) # store planet and sun msgs - plMsg = gravFactory.spiceObject.planetStateOutMsgs[0] - sunMsg = gravFactory.spiceObject.planetStateOutMsgs[1] + plMsg = spiceObject.planetStateOutMsgs[0] + sunMsg = spiceObject.planetStateOutMsgs[1] # setup orbit using orbitalMotion library oe = orbitalMotion.ClassicElements() diff --git a/examples/scenarioRendezVous.py b/examples/scenarioRendezVous.py index 89f406a0b1..7f69f4a87e 100755 --- a/examples/scenarioRendezVous.py +++ b/examples/scenarioRendezVous.py @@ -236,23 +236,21 @@ def run(show_plots): # setup Earth Gravity Body # earth = gravFactory.createEarth() # earth.isCentralBody = True # ensure this is the central gravitational body - gravBodies = gravFactory.createBodies(['sun', 'earth']) + gravBodies = gravFactory.createBodies('sun', 'earth') gravBodies['earth'].isCentralBody = True mu = gravBodies['earth'].mu sunIdx = 0 earthIdx = 1 # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) - scObject2.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) + gravFactory.addBodiesTo(scObject2) # setup SPICE interface for celestial objects timeInitString = "2022 MAY 1 00:28:30.0" - gravFactory.createSpiceInterface(bskPath +'/supportData/EphemerisData/', - timeInitString, - epochInMsg=True) - gravFactory.spiceObject.zeroBase = 'Earth' - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject) + spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) + spiceObject.zeroBase = 'Earth' + scSim.AddModelToTask(simTaskName, spiceObject) # # add RW devices @@ -301,8 +299,8 @@ def run(show_plots): # 'SpicePlanetStateMsgPayload' to 'EphemerisMsgPayload' ephemObject = ephemerisConverter.EphemerisConverter() ephemObject.ModelTag = 'EphemData' - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[sunIdx]) - ephemObject.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[earthIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[sunIdx]) + ephemObject.addSpiceInputMsg(spiceObject.planetStateOutMsgs[earthIdx]) scSim.AddModelToTask(simTaskName, ephemObject) # diff --git a/examples/scenarioRotatingPanel.py b/examples/scenarioRotatingPanel.py index 3da43c5010..7a31764773 100644 --- a/examples/scenarioRotatingPanel.py +++ b/examples/scenarioRotatingPanel.py @@ -145,7 +145,7 @@ def run(show_plots): planet = gravFactory.createEarth() planet.isCentralBody = True mu = planet.mu - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # create sun position message sunMessage = messaging.SpicePlanetStateMsgPayload() diff --git a/examples/scenarioSensorThermal.py b/examples/scenarioSensorThermal.py index 0f0bb6d13a..fdbcf7031d 100644 --- a/examples/scenarioSensorThermal.py +++ b/examples/scenarioSensorThermal.py @@ -151,15 +151,13 @@ def run(show_plots): mu = earth.mu # Attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector( - list(gravFactory.gravBodies.values()) - ) + gravFactory.addBodiesTo(scObject) # Create the spice interface - gravFactory.createSpiceInterface( - bskPath + "/supportData/EphemerisData/", "2021 MAY 04 07:47:48.965 (UTC)" + spiceObject = gravFactory.createSpiceInterface( + time="2021 MAY 04 07:47:48.965 (UTC)" ) - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject, ModelPriority=100) + scSim.AddModelToTask(simTaskName, spiceObject) # Set up the orbit using classical orbit elements oe = orbitalMotion.ClassicElements() @@ -192,9 +190,9 @@ def run(show_plots): # Create the ephemeris converter ephemConverter = ephemerisConverter.EphemerisConverter() ephemConverter.ModelTag = "ephemConverter" - ephemConverter.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[0]) - ephemConverter.addSpiceInputMsg(gravFactory.spiceObject.planetStateOutMsgs[1]) - scSim.AddModelToTask(simTaskName, ephemConverter, ModelPriority=100) + ephemConverter.addSpiceInputMsg(spiceObject.planetStateOutMsgs[0]) + ephemConverter.addSpiceInputMsg(spiceObject.planetStateOutMsgs[1]) + scSim.AddModelToTask(simTaskName, ephemConverter) # Set up sun pointing guidance module locPoint = locationPointing.locationPointing() @@ -228,7 +226,7 @@ def run(show_plots): thermalSensor.sensorMass = 2.0 # kg thermalSensor.sensorSpecificHeat = 890 thermalSensor.sensorPowerDraw = 30.0 # W - thermalSensor.sunInMsg.subscribeTo(gravFactory.spiceObject.planetStateOutMsgs[0]) + thermalSensor.sunInMsg.subscribeTo(spiceObject.planetStateOutMsgs[0]) thermalSensor.stateInMsg.subscribeTo(scObject.scStateOutMsg) scSim.AddModelToTask(simTaskName, thermalSensor) diff --git a/examples/scenarioSmallBodyFeedbackControl.py b/examples/scenarioSmallBodyFeedbackControl.py index b14c32ccb8..dc23485186 100644 --- a/examples/scenarioSmallBodyFeedbackControl.py +++ b/examples/scenarioSmallBodyFeedbackControl.py @@ -289,7 +289,7 @@ def run(show_plots): # create SC object scObject = spacecraft.Spacecraft() scObject.ModelTag = "bskSat" - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Create the position and velocity of states of the s/c wrt the small body hill frame origin r_BO_N = np.array([-2000., 1500., 1000.]) # Position of the spacecraft relative to the body diff --git a/examples/scenarioSmallBodyLandmarks.py b/examples/scenarioSmallBodyLandmarks.py index db7300b213..7dd5a8306f 100644 --- a/examples/scenarioSmallBodyLandmarks.py +++ b/examples/scenarioSmallBodyLandmarks.py @@ -345,7 +345,7 @@ def run(show_plots, useBatch): scObject.hub.omega_BN_BInit = [[0.001], [-0.01], [0.03]] # Attach gravity to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Set extForceTorque module # The control torque is read in through the messaging system diff --git a/examples/scenarioSmallBodyNav.py b/examples/scenarioSmallBodyNav.py index f6ddcfa7fb..49402fc6b1 100644 --- a/examples/scenarioSmallBodyNav.py +++ b/examples/scenarioSmallBodyNav.py @@ -497,7 +497,7 @@ def run(show_plots): # create SC object scObject = spacecraft.Spacecraft() scObject.ModelTag = "bskSat" - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # Create the position and velocity of states of the s/c wrt the small body hill frame r_BO_N = np.array([2000., 1500., 1000.]) # Position of the spacecraft relative to the body diff --git a/examples/scenarioSmallBodyNavUKF.py b/examples/scenarioSmallBodyNavUKF.py index 3f07faf58a..cc58739337 100644 --- a/examples/scenarioSmallBodyNavUKF.py +++ b/examples/scenarioSmallBodyNavUKF.py @@ -342,8 +342,9 @@ def run(show_plots): mu = 17.2882449693*1e9 # m^3/s^2 asteroid = gravFactory.createCustomGravObject("vesta", mu, radEquator=265*1000) asteroid.isCentralBody = True + nSpherHarm = 14 - asteroid.useSphericalHarmonicsGravityModel(bskPath + '/supportData/LocalGravData/VESTA20H.txt', nSpherHarm) + asteroid.useSphericalHarmonicsGravityModel(bskPath + "/supportData/LocalGravData/VESTA20H.txt", nSpherHarm) asteroid.planetBodyInMsg.subscribeTo(gravBodyEphem.planetOutMsgs[0]) # create an ephemeris converter @@ -354,7 +355,7 @@ def run(show_plots): # create SC object scObject = spacecraft.Spacecraft() scObject.ModelTag = "bskSat" - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # setup orbit initial conditions of the sc oe = orbitalMotion.ClassicElements() diff --git a/examples/scenarioSpacecraftLocation.py b/examples/scenarioSpacecraftLocation.py index 42302bf1b8..242cd4c0e2 100755 --- a/examples/scenarioSpacecraftLocation.py +++ b/examples/scenarioSpacecraftLocation.py @@ -128,8 +128,8 @@ def run(show_plots): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) - scObject2.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) + gravFactory.addBodiesTo(scObject2) # add external control torque to scObject extFTObject = extForceTorque.ExtForceTorque() diff --git a/examples/scenarioSpiceSpacecraft.py b/examples/scenarioSpiceSpacecraft.py index 70a25b9c63..eec0248e8d 100755 --- a/examples/scenarioSpiceSpacecraft.py +++ b/examples/scenarioSpiceSpacecraft.py @@ -163,20 +163,18 @@ def run(show_plots): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # setup spice library for Earth ephemeris and Hubble states timeInitString = "2015 February 10, 00:00:00.0 TDB" - gravFactory.createSpiceInterface(bskPath + '/supportData/EphemerisData/', - timeInitString, - epochInMsg=True) - gravFactory.spiceObject.zeroBase = 'Earth' + spiceObject = gravFactory.createSpiceInterface(time=timeInitString, epochInMsg=True) + spiceObject.zeroBase = 'Earth' scNames = ["HUBBLE SPACE TELESCOPE"] - gravFactory.spiceObject.addSpacecraftNames(messaging.StringVector(scNames)) - gravFactory.spiceObject.loadSpiceKernel("hst_edited.bsp", bskPath + '/supportData/EphemerisData/') + spiceObject.addSpacecraftNames(messaging.StringVector(scNames)) + spiceObject.loadSpiceKernel("hst_edited.bsp", bskPath + '/supportData/EphemerisData/') # need spice to run before spacecraft module as it provides the spacecraft translational states - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject) + scSim.AddModelToTask(simTaskName, spiceObject) scSim.AddModelToTask(simTaskName, scObject) # setup extForceTorque module @@ -235,7 +233,7 @@ def run(show_plots): mrpControl.guidInMsg.subscribeTo(attError.attGuidOutMsg) mrpControl.vehConfigInMsg.subscribeTo(configDataMsg) extFTObject.cmdTorqueInMsg.subscribeTo(mrpControl.cmdTorqueOutMsg) - scObject.transRefInMsg.subscribeTo(gravFactory.spiceObject.transRefStateOutMsgs[0]) + scObject.transRefInMsg.subscribeTo(spiceObject.transRefStateOutMsgs[0]) # # Setup data logging before the simulation is initialized @@ -273,7 +271,7 @@ def run(show_plots): # unload custom Spice kernel gravFactory.unloadSpiceKernels() - gravFactory.spiceObject.unloadSpiceKernel("hst_edited.bsp", bskPath + '/supportData/EphemerisData/') + spiceObject.unloadSpiceKernel("hst_edited.bsp", bskPath + '/supportData/EphemerisData/') # # plot the results diff --git a/examples/scenarioTAM.py b/examples/scenarioTAM.py index e19267a246..cfb8443952 100644 --- a/examples/scenarioTAM.py +++ b/examples/scenarioTAM.py @@ -182,7 +182,7 @@ def run(show_plots, orbitCase, planetCase, useBias, useBounds): req = planet.radEquator # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) if planetCase == 'Jupiter': magModule = magneticFieldCenteredDipole.MagneticFieldCenteredDipole() # default is Earth centered dipole module diff --git a/examples/scenarioTAMcomparison.py b/examples/scenarioTAMcomparison.py index b6df3a12c8..dcd71d6b78 100644 --- a/examples/scenarioTAMcomparison.py +++ b/examples/scenarioTAMcomparison.py @@ -184,7 +184,7 @@ def run(show_plots, orbitCase, useBias1, useBias2, useBounds1, useBounds2): req = planet.radEquator # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # create the centered dipole magnetic field diff --git a/examples/scenarioTwoChargedSC.py b/examples/scenarioTwoChargedSC.py index f925aa57dc..749fc1a424 100644 --- a/examples/scenarioTwoChargedSC.py +++ b/examples/scenarioTwoChargedSC.py @@ -134,8 +134,8 @@ def run(show_plots): mu = earth.mu # attach gravity model to spaceCraftPlus - scObjectLeader.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) - scObjectFollower.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObjectLeader) + gravFactory.addBodiesTo(scObjectFollower) # setup MSM module MSMmodule = msmForceTorque.MsmForceTorque() diff --git a/examples/scenarioVariableTimeStepIntegrators.py b/examples/scenarioVariableTimeStepIntegrators.py index 5b85955ec9..fc1df60114 100644 --- a/examples/scenarioVariableTimeStepIntegrators.py +++ b/examples/scenarioVariableTimeStepIntegrators.py @@ -164,7 +164,7 @@ def run(show_plots, integratorCase, relTol, absTol): mu = earth.mu # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # # setup orbit and simulation time diff --git a/examples/scenarioVizPoint.py b/examples/scenarioVizPoint.py index 2069c85b55..093c56958a 100755 --- a/examples/scenarioVizPoint.py +++ b/examples/scenarioVizPoint.py @@ -176,14 +176,12 @@ def run(show_plots, missionType, saveVizardFile): if missionType == 'dscovr': # setup Grav Bodies and Spice messages gravFactory = simIncludeGravBody.gravBodyFactory() - bodies = gravFactory.createBodies(['earth', 'sun']) + bodies = gravFactory.createBodies('earth', 'sun') bodies['earth'].isCentralBody = True # ensure this is the central gravitational body - gravFactory.createSpiceInterface(bskPath + '/supportData/EphemerisData/', - '2018 OCT 23 04:35:25.000 (UTC)', - epochInMsg=True) + spiceObject = gravFactory.createSpiceInterface(time='2018 OCT 23 04:35:25.000 (UTC)', epochInMsg=True) - gravFactory.spiceObject.zeroBase = 'earth' - scSim.AddModelToTask(simTaskName, gravFactory.spiceObject) + spiceObject.zeroBase = 'earth' + scSim.AddModelToTask(simTaskName, spiceObject) # Setup Camera. cameraConfig = messaging.CameraConfigMsgPayload() cameraConfig.cameraID = 1 @@ -222,7 +220,7 @@ def run(show_plots, missionType, saveVizardFile): scObject.hub.r_BcB_B = [[0.0], [0.0], [0.0]] # m - position vector of body-fixed point B relative to CM scObject.hub.IHubPntBc_B = unitTestSupport.np2EigenMatrix3d(I) # attach gravity model to spacecraft - scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values())) + gravFactory.addBodiesTo(scObject) # add spacecraft object to the simulation process scSim.AddModelToTask(simTaskName, scObject) From f364b84a2ac95066d60236e4cbeb6a911bbaa42c Mon Sep 17 00:00:00 2001 From: Juan Garcia Bonilla Date: Sat, 25 Nov 2023 12:43:50 -0800 Subject: [PATCH 5/5] Update scenarios to use new syntax --- docs/source/Support/bskReleaseNotes.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/source/Support/bskReleaseNotes.rst b/docs/source/Support/bskReleaseNotes.rst index d480d060c8..56256e68da 100644 --- a/docs/source/Support/bskReleaseNotes.rst +++ b/docs/source/Support/bskReleaseNotes.rst @@ -83,6 +83,10 @@ Version |release| and ``usePointMassGravityModel`` have been added. - Fixed examples and tests to run even when Basilisk is built with ``--vizInterface False``. - Added a new method ``setDataBuffer()`` to :ref:`simpleStorageUnit` and :ref:`partitionedStorageUnit` to add or remove data from specified partitions. +- Refactored ``simIncludeGravBody``. The most notable change for users is that the commonly used line + ``scObject.gravField.gravBodies = spacecraft.GravBodyVector(list(gravFactory.gravBodies.values()))`` + can be replaced by ``gravFactory.addBodiesTo(scObject)`` (where ``scObject`` is a ``spacecraft.Spacecraft`` + or ``spacecraftSystem.SpacecraftSystem``, and ``gravFactory`` is a ``simIncludeGravBody.gravBodyFactory``) Version 2.2.0 (June 28, 2023) -----------------------------