Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/source/Support/bskReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ Version |release|
- Added support for :ref:`hingedRigidBodyStateEffector` to be the parent for Dynamic Effectors.
- Added SWIG Eigen typemaps for passing Eigen products or returning Eigen products to/from director methods.
- Added a new scenario that simulates a debris strike on a flexible solar array :ref:`scenarioImpact`.
- Added ``SysModelMixin``, a utility class in ``py_sys_model.i`` that can be used for subclasses
of ``SysModel`` (:ref:`sys_model`) that have virtual methods to be implemented in Python. The class will automatically
add better error logging for all methods implemented in Python and will add a sanity check that the
C++ class constructor is called (otherwise, hard-to-parse errors will be raised). Refactored
``pyStatefulSysModel.i`` to use this mixin.


Version 2.8.0 (August 30, 2025)
Expand Down
4 changes: 2 additions & 2 deletions docs/source/codeSamples/making-pyModules.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ def run():


class TestPythonModule(sysModel.SysModel):
def __init__(self, *args):
super().__init__(*args)
def __init__(self):
super().__init__()
self.dataInMsg = messaging.CModuleTemplateMsgReader()
self.dataOutMsg = messaging.CModuleTemplateMsg()

Expand Down
180 changes: 153 additions & 27 deletions src/architecture/_GeneralModuleFiles/py_sys_model.i
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
/*
ISC License

Copyright (c) 2025, Autonomous Vehicle Systems Lab, University of Colorado at Boulder

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

%module(directors="1",threads="1",package="Basilisk.architecture") sysModel

Expand All @@ -13,49 +30,158 @@ import sys
import traceback
from Basilisk.architecture.swig_common_model import *
%}

%include "std_string.i"
%include "swig_conly_data.i"
%include "architecture/utilities/bskLogging.h"

/* Director support for the C++ SysModel base */
%feature("director") SysModel;
%feature("pythonappend") SysModel::SysModel %{
self.__super_init_called__ = True%}

/* Expose the raw SWIG proxy as _SysModel */
%rename("_SysModel") SysModel;
%include "sys_model.i"

%pythoncode %{
class SuperInitChecker(type):

def __call__(cls, *a, **kw):
rv = super(SuperInitChecker, cls).__call__(*a, **kw)
if not getattr(rv, "__super_init_called__", False):
error_msg = (
"Need to call parent __init__ in SysModel subclasses:\n"
f"class {cls.__name__}(sysModel.SysModel):\n"
" def __init__(...):\n"
" super().__init__()"
)
raise SyntaxError(error_msg)
return rv

def logError(func):
"""Decorator that prints any exceptions that happen when
the original function is called, and then raises them again."""
def inner(*arg, **kwargs):
"""Decorator that prints any exceptions raised by func, then re raises them."""
def inner(*args, **kwargs):
try:
return func(*arg, **kwargs)
return func(*args, **kwargs)
except Exception:
traceback.print_exc()
raise
# Mark so we do not wrap twice
inner._sysmodelLogged = True
return inner

class SysModel(_SysModel, metaclass=SuperInitChecker):
bskLogger: BSKLogger = None

class SysModelMixin:
"""Pure Python mixin for Basilisk system models.

Provides:
* Automatic logError wrapping for overridden director methods
from any SWIG C++ proxy bases in the MRO.
* Enforcement that subclasses call super().__init__().
"""

def __init__(self, *args, **kwargs):
# Cooperative init; super() will eventually call the SWIG proxy __init__
super().__init__(*args, **kwargs)
# Mark that the mixin init has been called on this instance.
self._sysmodelBaseInitSeen = True

@classmethod
def _wrapOverriddenDirectorMethods(cls):
"""Wrap all overridden director methods with logError.

A method is considered a director method if:
* it exists on at least one SWIG C++ proxy base
* and it is overridden in cls with a different callable
"""
cppBases = []
for base in cls.mro()[1:]:
if base is object:
continue
# Heuristic: SWIG proxy types have __swig_destroy__ or similar
if hasattr(base, "__swig_destroy__"):
cppBases.append(base)

if not cppBases:
return

# Collect candidate method names from all C++ bases
candidateNames = set()
for base in cppBases:
for name in dir(base):
if name.startswith("_"):
continue
if name in ("__init__",):
continue
candidateNames.add(name)

for name in candidateNames:
subAttr = getattr(cls, name, None)
if not callable(subAttr):
continue

# Find the first base that defines this name
baseAttr = None
for base in cppBases:
if hasattr(base, name):
baseAttr = getattr(base, name)
break

if baseAttr is None:
continue

# Only wrap if the subclass actually overrides the method
if subAttr is baseAttr:
continue

# Avoid double wrapping
if getattr(subAttr, "_sysmodelLogged", False):
continue

setattr(cls, name, logError(subAttr))

def __init_subclass__(cls):
# Make it so any exceptions in UpdateState and Reset
# print any exceptions before returning control to
# C++ (at which point exceptions will crash the program)
cls.UpdateState = logError(cls.UpdateState)
cls.Reset = logError(cls.Reset)
"""Hook that runs for every Python subclass of SysModelMixin.

It:
* wraps all overridden director methods from SWIG C++ proxy bases
in the MRO with logError
* enforces super().__init__() on subclasses
"""
super().__init_subclass__()

# Wrap overridden director methods
cls._wrapOverriddenDirectorMethods()

origInit = cls.__init__

# Avoid double wrapping if someone subclasses a subclass.
if getattr(origInit, "_sysmodelWrappedInit", False):
return

def wrappedInit(self, *args, **kwargs):
# Clear flag before running user __init__.
object.__setattr__(self, "_sysmodelBaseInitSeen", False)
origInit(self, *args, **kwargs)
if not getattr(self, "_sysmodelBaseInitSeen", False):
errorMsg = (
"Need to call parent __init__ in SysModel based subclasses:\n"
f"class {cls.__name__}(...):\n"
" def __init__(...):\n"
" super().__init__()"
)
raise SyntaxError(errorMsg)

wrappedInit._sysmodelWrappedInit = True
cls.__init__ = wrappedInit


class SysModel(SysModelMixin, _SysModel):
"""Python friendly base class for Basilisk system models.

Inherits:
* SysModelMixin (pure Python)
* _SysModel (SWIG proxy for C++ SysModel)

Typical usage for new models:
from Basilisk.architecture import sysModel

class MyModel(sysModel.SysModel):
def __init__(self):
super().__init__()
...

def UpdateState(self, CurrentSimNanos):
...

def Reset(self, CurrentSimNanos):
...
"""

bskLogger: BSKLogger = None
%}
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

*/
%module(directors="1",threads="1") StatefulSysModel
%module(directors="1",threads="1",package="Basilisk.simulation") StatefulSysModel

%include "architecture/utilities/bskException.swg"
%default_bsk_exception();

%{
#include "StatefulSysModel.h"
%}

%pythoncode %{
import sys
import traceback
from Basilisk.architecture.swig_common_model import *
%}

Expand All @@ -35,22 +38,14 @@ from Basilisk.architecture.swig_common_model import *
%ignore DynParamRegisterer::DynParamRegisterer;

%feature("director") StatefulSysModel;
%feature("pythonappend") StatefulSysModel::StatefulSysModel %{
self.__super_init_called__ = True%}
%rename("_StatefulSysModel") StatefulSysModel;
%include "StatefulSysModel.h"

%template(registerState) DynParamRegisterer::registerState<StateData, true>;

%pythoncode %{
class StatefulSysModel(_StatefulSysModel, metaclass=Basilisk.architecture.sysModel.SuperInitChecker):
bskLogger: BSKLogger = None

def __init_subclass__(cls):
# Make it so any exceptions in UpdateState and Reset
# print any exceptions before returning control to
# C++ (at which point exceptions will crash the program)
cls.UpdateState = Basilisk.architecture.sysModel.logError(cls.UpdateState)
cls.Reset = Basilisk.architecture.sysModel.logError(cls.Reset)
cls.registerStates = Basilisk.architecture.sysModel.logError(cls.registerStates)
from Basilisk.architecture.sysModel import SysModelMixin

class StatefulSysModel(SysModelMixin, _StatefulSysModel):
"""Python wrapper for the C++ StatefulSysModel."""
%}
Loading