Skip to main content
Ctrl+K
kdFlex 1.1.2 documentation - Home
  • Chatbot

Contents:

  • Chatbot
  • Installation
  • Examples
    • Importing a robot arm multibody model from a URDF file
    • 2-link Pendulum
    • Load Mars 2020 rover model from a URDF file
    • n-link Pendulum
    • Spice Frames
    • Import/Export Multibodies
    • Graphics demo
    • Data Logging
    • Slider crank example
    • Double-Wishbone
    • 2-link Pendulum Collision Example
    • Procedural n-link pendulum collision example
    • Flexible Slider-Crank
    • Flexible Double-Wishbone
    • \(n\)-link Pendulum Benchmark Comparison
    • Fully Augmented \(n\)-link Pendulum Benchmark Comparison
    • ATRVjr Driving
    • Cart Pole Reinforcement Learning
    • ATRVjr Reinforcement Learning
    • ATRVjr ROS Integration
  • Key concepts
  • Usage Guide
  • Recipes
  • Program skeletons
  • API
    • kdFlex Python API
      • Karana
        • Karana.Collision
        • Karana.Core
        • Karana.Dynamics
        • Karana.Frame
        • Karana.Integrators
        • Karana.KUtils
        • Karana.Math
        • Karana.Models
        • Karana.Scene
        • Karana.WebUI
        • Karana.version
    • kdFlex C++ API
      • Namespace coal
      • Namespace Eigen
      • Namespace Karana
      • Namespace Karana::Collision
      • Namespace Karana::Core
      • Namespace Karana::Dynamics
      • Namespace Karana::Frame
      • Namespace Karana::Integrators
      • Namespace Karana::KUtils
      • Namespace Karana::Math
      • Namespace Karana::Models
      • Namespace Karana::Scene
      • Namespace Karana::WebUI
      • Namespace KaranaTest
      • Namespace KaranaTest::Dynamics
      • Namespace kf
      • Namespace kf::Frame
      • Namespace LockingBase
      • Namespace pybind11
      • Namespace pybind11::detail
      • Namespace pybind11::typing
      • Namespace spdlog
      • Namespace spdlog::sinks
      • Namespace std
      • Template Struct has_pybind11_caster
      • Struct FrameContact
      • Struct Base::DumpOptions
      • Struct BaseWithVars::DumpOptions
      • Struct BasicDAGImpl::Node
      • Struct BasicTreeImpl::Node
      • Struct DebugManager
      • Struct EdgeHash
      • Struct LockingBase::DumpOptions
      • Struct NestedVars
      • Struct CompoundBody::ATBIDataCaches
      • Struct CompoundBody::DumpOptions
      • Struct CompoundBody::InvDynVectors
      • Struct CompoundSubhinge::ATBIFilterVectors
      • Struct CompoundSubhinge::ATBIMatrices
      • Struct CoordBase::ATBIFilterVectors
      • Struct CoordBase::ATBIMatrices
      • Struct CoordData::CoordOffset
      • Struct DynamicFunctor
      • Struct DynamicFunctorNoJac
      • Template Struct Functor
      • Struct HingeBase::HingeParams
      • Struct HingeNode::DumpOptions
      • Struct HingeOnodeATBIDataCaches
      • Struct HingeOnodeATBIFilterVectors
      • Struct HingeOnodeATBIMatrices
      • Struct HingeOnodeATBISmootherVectors
      • Struct HingeOnodeInvDynVectors
      • Struct HingeOnodeUpsilonMatrices
      • Struct HingePnode::ATBIDataCaches
      • Struct HingePnode::ATBIFilterVectors
      • Struct HingePnode::ATBIMatrices
      • Struct HingePnode::ATBISmootherVectors
      • Struct HingePnode::InvDynVectors
      • Struct HingePnode::UpsilonMatrices
      • Struct LoopConstraintBase::QMats
      • Struct ModalAnalysis
      • Struct ModalNodeDeformationProvider::DeformationParams
      • Struct ModelManager::MMFunctions
      • Struct NodeDeformationProvider::DeformationParams
      • Struct Physical1DofSubhinge::PhysicalSubhingeParams
      • Struct PhysicalBody::DumpOptions
      • Struct PhysicalBody::GatherSweepFlags
      • Struct PhysicalBody::InvDynVectors
      • Struct PhysicalBodyParams
      • Struct PhysicalModalBody::ATBIFilterVectors
      • Struct PhysicalModalBody::ATBIMatrices
      • Struct PhysicalModalBody::ATBISmootherVectors
      • Struct PhysicalModalBody::ModalUpsilonMatrices
      • Struct PhysicalModalBody::SZNodeMatrices
      • Struct PhysicalModalBodyParams
      • Struct PhysicalSubhinge::PhysicalSubhingeParams
      • Struct PhysicalSubhinge_T::ATBIFilterVectors
      • Struct PhysicalSubhinge_T::ATBIMatrices
      • Struct ScrewSubhinge::PhysicalSubhingeParams
      • Struct SphericalSubhinge::PhysicalSubhingeParams
      • Struct StatePropagator::Counters
      • Struct StickPartsConfig
      • Struct SubTree::DumpTreeOptions
      • Struct Frame::DumpFrameTreeOptions
      • Struct FrameContainer::DumpOptions
      • Struct FrameToFrame::DumpOptions
      • Struct OrientedChainedFrameToFrame::DumpOptions
      • Struct ArkExplicitIntegrator::IntegratorOptions
      • Struct CVodeIntegrator::IntegratorOptions
      • Struct IdaIntegrator::IntegratorOptions
      • Struct Integrator::IntegratorOptions
      • Struct SundialsIntegrator::IntegratorOptions
      • Template Struct extract_matrix_dimensions
      • Template Struct extract_matrix_dimensions< Eigen::Matrix< double, _rows, 1 > >
      • Template Struct extract_matrix_dimensions< Eigen::Matrix< double, _rows, _cols, Eigen::RowMajor > >
      • Template Struct extract_rows
      • Template Struct extract_rows< Eigen::Matrix< double, rows, 1 > >
      • Template Struct is_eigen_int_type
      • Template Struct is_eigen_int_type< Eigen::Matrix< int, Rows, 1 > >
      • Template Struct is_eigen_type
      • Template Struct is_eigen_type< Eigen::Matrix< double, Rows, 1 > >
      • Template Struct is_eigen_type< Eigen::Matrix< double, Rows, Cols, Eigen::RowMajor > >
      • Template Struct is_eigen_vector
      • Template Struct is_eigen_vector< Eigen::Matrix< double, Rows, 1 > >
      • Struct SinglePlotData
      • Struct Acceleration3
      • Struct Angle
      • Struct Angle3
      • Struct AngularAcceleration3
      • Struct AngularMomentum3
      • Struct AngularVelocity3
      • Struct FloatQuantityHelper
      • Struct Force3
      • Struct GravitationalParameter
      • Struct Inertia
      • Struct Length
      • Struct Length3
      • Struct Mass
      • Struct Mat33QuantityHelper
      • Struct Momentum3
      • Template Struct NumDiffBaseFunctor
      • Struct NumDiffFunctor
      • Struct StateSpace::SS
      • Struct Torque3
      • Struct Vec3QuantityHelper
      • Struct Velocity3
      • Struct GravityOutput
      • Struct MultibodyObjs
      • Struct ClientSceneData
      • Struct CollisionInfo
      • Struct Contact
      • Struct DistanceInfo
      • Struct ImportResult
      • Struct OrthographicProjection
      • Struct PerspectiveProjection
      • Struct PhongMaterialInfo
      • Struct PhysicalMaterialInfo
      • Struct RGBABuffer
      • Struct ScenePartSpec
      • Struct TextParameters
      • Struct LocalClientOptions
      • Struct Selection::Item
      • Struct SliderOptions
      • Struct TreeView::Edge
      • Struct TreeView::Node
      • Template Struct handle_type_name< typing::Sequence< T > >
      • Template Struct PyStateTypeWrapper
      • Template Struct PyTypeWrapper
      • Template Class duration_caster
      • Class ContactForceBase
      • Class ContactForceManager
      • Class FrameCollider
      • Class HuntCrossley
      • Class HuntCrossley::HuntCrossleyParams
      • Class HuntCrossley::HuntCrossleyScratch
      • Class Base
      • Class BaseContainer
      • Class BaseVars
      • Class BaseWithVars
      • Template Class BasicDAGImpl
      • Template Class BasicTreeImpl
      • Template Class CallbackRegistry
      • Template Class DAG
      • Template Class DataCache
      • Class DelFns
      • Class IdGenerator
      • Class IdHashStruct
      • Class JsonLogger
      • Class LockingBase
      • Class LockingBaseVars
      • Class MsgLogger
      • Class my_formatter_flag
      • Template Class RegistryList
      • Class SideEffect
      • Class StderrLog
      • Class StdoutLog
      • Template Class Tree
      • Template Class UsageTrackingMap
      • Class Var
      • Template Class Var_T
      • Class Algorithms
      • Class BilateralConstraintBase
      • Class BilateralConstraintBaseVars
      • Class BodyBase
      • Class CECompoundBody
      • Class CECompoundBodyVars
      • Class CECompoundSubhinge
      • Class CELoopKinematicsBase
      • Class CELoopKinematicsBaseVars
      • Class CELoopKinematicsNumeric
      • Class CELoopKinematicsNumericVars
      • Class CELoopKinematicsPlanar4Bar
      • Class CompoundBody
      • Class CompoundBodyVars
      • Class CompoundHinge
      • Class CompoundSubhinge
      • Class CompoundSubhingeVars
      • Class ConstraintKinematicsSolver
      • Class ConstraintKinematicsSolverVars
      • Class ConstraintNode
      • Class CoordBase
      • Template Class CoordBase_T
      • Class CoordData
      • Class CoordDataVars
      • Class CoordinateConstraint
      • Class CoordinateConstraintVars
      • Class FramePairHinge
      • Class FramePairHingeVars
      • Class FrameToFrameJacobianGenerator
      • Class HingeBase
      • Class HingeNode
      • Class HingeOnode
      • Class HingePnode
      • Class Linear3Subhinge
      • Class LinearSubhinge
      • Class LockedSubhinge
      • Class LoopConstraintBase
      • Class LoopConstraintBaseVars
      • Class LoopConstraintConVel
      • Class LoopConstraintConVelVars
      • Class LoopConstraintCutJoint
      • Class LoopConstraintCutJointVars
      • Class ModalNodeDeformationProvider
      • Class ModelManager
      • Class ModelManager::MMOptions
      • Class ModelManagerVars
      • Class Multibody
      • Class MultiJacobianGenerator
      • Class Node
      • Class NodeDeformationProvider
      • Class NodeVars
      • Class NonlinearSolver
      • Class Physical1DofSubhinge
      • Class PhysicalBody
      • Class PhysicalBodyVars
      • Class PhysicalHinge
      • Class PhysicalModalBody
      • Class PhysicalModalBodyVars
      • Class PhysicalSubhinge
      • Template Class PhysicalSubhinge_T
      • Class PhysicalSubhingeVars
      • Class PinSubhinge
      • Class Scheduler
      • Class ScrewSubhinge
      • Class SphericalQuatSubhinge
      • Class SphericalSubhinge
      • Class StatePropagator
      • Class StatePropagator::SpOptions
      • Class StatePropagatorVars
      • Class SubGraph
      • Class SubGraphVars
      • Class SubhingeBase
      • Class SubTree
      • Class SubTreeVars
      • Class TimedEvent
      • Class TimeKeeper
      • Class TimeKeeperVars
      • Class ChainedFrameToFrame
      • Class ChainedFrameToFrameVars
      • Class EdgeFrameToFrame
      • Class Frame
      • Class FrameContainer
      • Class FrameToFrame
      • Class FrameToFrameVars
      • Class FrameVars
      • Class OrientedChainedFrameToFrame
      • Class OrientedChainedFrameToFrameVars
      • Class PrescribedFrameToFrame
      • Class SpiceFrame
      • Class SpiceFrameToFrame
      • Class ArkExplicitIntegrator
      • Class CVodeIntegrator
      • Class CVodeIntegratorVars
      • Class EulerIntegrator
      • Class IdaIntegrator
      • Class Integrator
      • Class NoopIntegrator
      • Class RK4Integrator
      • Class SundialsIntegrator
      • Class SundialsIntegratorVars
      • Class ContactForceVisualizer
      • Class FrameToFrameVectorVisualizer
      • Class FSM
      • Class FSMState
      • Class FSMTransition
      • Class FSMVars
      • Class H5Writer
      • Class PacketTableConfig
      • Class PlotData
      • Class ScaledVectorVisualizer
      • Class VectorVisualizer
      • Class WsClient
      • Class AABB
      • Class AkimaSplineInterpolator
      • Class BaseInterpolator
      • Class ConstantInterpolator
      • Class CubicHermiteInterpolator
      • Class HomTran
      • Class Jacobian
      • Class LinearInterpolator
      • Class NearestNeighborInterpolator
      • Class Ray
      • Class RotationMatrix
      • Class RotationVector
      • Class SimTran
      • Class SpatialAcceleration
      • Class SpatialForce
      • Class SpatialInertia
      • Class SpatialMomentum
      • Class SpatialVector
      • Class SpatialVelocity
      • Class StateSpace
      • Class UnitQuaternion
      • Class BaseKModel
      • Class ComputedTorque
      • Template Class ConstantProfileGenerator
      • Template Class CubicSplineProfileGenerator
      • Class DataLogger
      • Class DataLoggerParams
      • Class DataPlotter
      • Class DataPlotterParams
      • Class GilRelease
      • Class GraphicalSceneMovie
      • Class GraphicalSceneMovieParams
      • Class Gravity
      • Class GravityInterface
      • Class GravityVars
      • Template Class KModel
      • Class KModelContinuousStates
      • Class KModelDiscreteStates
      • Class KModelParams
      • Class KModelScratch
      • Template Class KModelVars
      • Template Class LinearProfileGenerator
      • Class NoContinuousStates
      • Class NoDiscreteStates
      • Class NoParams
      • Class NoScratch
      • Class PenaltyContact
      • Class PID
      • Class PIDParams
      • Class PIDParamsVars
      • Class PinJointLimits
      • Class PinJointLimitsParams
      • Class PointMassGravity
      • Template Class ProfileGenerator
      • Template Class ProfileGeneratorVars
      • Class ProjectConstraintError
      • Class ProjectConstraintErrorParams
      • Class SpringDamper
      • Class SpringDamperParams
      • Class SpringDamperParamsVars
      • Class SpringDamperScratch
      • Class SpringDamperScratchVars
      • Class SubhingeForceLimits
      • Class SubhingeForceLimitsParams
      • Class SubhingeSpringDamper
      • Class SubhingeSpringDamperParams
      • Class SyncRealTime
      • Class TimeDisplay
      • Class TimeDisplayParams
      • Class TimeDisplayParamsVars
      • Class UniformGravity
      • Class UpdateProxyScene
      • Class AbstractImporter
      • Class AbstractStaticGeometry
      • Class AssimpImporter
      • Class BoxGeometry
      • Class CapsuleGeometry
      • Class ClientRegistry
      • Class CoalGeometryCache
      • Class CoalScene
      • Class CoalSceneNode
      • Class CoalScenePart
      • Class CollisionScene
      • Class CollisionSceneNode
      • Class CollisionScenePart
      • Class Color
      • Class ConeGeometry
      • Class CylinderGeometry
      • Class ExtMime
      • Class GraphicalScene
      • Class GraphicalSceneCamera
      • Class GraphicalSceneNode
      • Class GraphicalScenePart
      • Class GrayscaleTexture
      • Class HeightFieldGeometry
      • Class ImplDatabase
      • Class PhongMaterial
      • Class PhysicalMaterial
      • Class ProxyScene
      • Class ProxySceneNode
      • Class ProxyScenePart
      • Class ProxyScenePartVars
      • Class ProxySceneVars
      • Class RoundFrustumGeometry
      • Class Scene
      • Class SceneNode
      • Class SceneNodeVars
      • Class ScenePart
      • Class ScenePartSpecVars
      • Class ScenePartVars
      • Class SceneVars
      • Class SphereGeometry
      • Class StaticMeshGeometry
      • Class Texture
      • Class TransformUpdateScope
      • Class WebResourceManager
      • Class WebScene
      • Class WebSceneBetweenLine
      • Class WebSceneCamera
      • Class WebSceneNode
      • Class WebSceneOverlayText
      • Class WebScenePart
      • Class Button
      • Class Channel
      • Class ClientApp
      • Class Connection
      • Class ContentSource
      • Class Dock
      • Class Dropdown
      • Class HttpWsServer
      • Class IFrame
      • Class InputGroup
      • Class Layout
      • Class Markdown
      • Class QuantityInput
      • Class Router
      • Class Selection
      • Class Server
      • Class Slider
      • Class State
      • Class Toggle
      • Class TreeView
      • Class Widget
      • Template Class Sequence
      • Template Class type_caster< std::chrono::duration< Rep, Period > >
      • Template Class type_caster< std::chrono::time_point< Clock, Duration > >
      • Enum VarType
      • Enum BilateralConstraintType
      • Enum CKFrozenCoordType
      • Enum HingeType
      • Enum MMSolverType
      • Enum NeedsStateReset
      • Enum SolverType
      • Enum SpStatusEnum
      • Enum SubhingeType
      • Enum IntegratorType
      • Enum FrameToFrameRateType
      • Enum DumpFormatType
      • Enum OutputUpdateType
      • Enum Alignment
      • Function ADD_TO_DS_METHOD_CASTER
      • Function addToDSMethod< GilRelease >
      • Function addToDSMethod< Gravity >
      • Function addToDSMethod< GravityInterface >
      • Function addToDSMethod< PointMassGravity >
      • Function addToDSMethod< SpringDamper >
      • Function addToDSMethod< SubhingeSpringDamper >
      • Function addToDSMethod< SyncRealTime >
      • Function addToDSMethod< UniformGravity >
      • Function addToDSMethod< UpdateProxyScene >
      • Function cast
      • Function def(“getGravity”, &GravityInterface::getGravity, DOC(Karana, Models, GravityInterface, getGravity))
      • Function def(py::init<>&::create, py::arg(“name”), DOC(Karana, Models, UniformGravity, create))
      • Function def(py::init<>&::create, py::arg(“name”), py::arg(“st”), py::arg(“central_body”), DOC(Karana, Models, PointMassGravity, create))
      • Function def(“getQ”, &ProfileGenerator<double>::getQ, py::arg(“t”), DOC(Karana, Models, ProfileGenerator, getQ))
      • Function def(“getQ”, &ProfileGenerator<km::ArrayVec>::getQ, py::arg(“t”), DOC(Karana, Models, ProfileGenerator, getQ))
      • Function def(“getQ”, &ProfileGenerator<km::UnitQuaternion>::getQ, py::arg(“t”), DOC(Karana, Models, ProfileGenerator, getQ))
      • Function def(py::init<>&<>::create, py::arg(“name”), py::arg(“t_i”), py::arg(“q_i”), py::arg(“t_f”), py::arg(“q_f”), DOC(Karana, Models, LinearProfileGenerator, create))
      • Function def(py::init<>&<::>::create, py::arg(“name”), py::arg(“t_i”), py::arg(“q_i”), py::arg(“t_f”), py::arg(“q_f”), DOC(Karana, Models, LinearProfileGenerator, create))
      • Function def(py::init<>&<>::create, py::arg(“name”), py::arg(“q”), DOC(Karana, Models, ConstantProfileGenerator, create))
      • Function def(py::init<>&<::>::create, py::arg(“name”), py::arg(“q”), DOC(Karana, Models, ConstantProfileGenerator, create))
      • Function def(py::init<>&<>::create, py::arg(“name”), py::arg(“t_i”), py::arg(“q_i”), py::arg(“u_i”), py::arg(“t_f”), py::arg(“q_f”), py::arg(“u_f”), DOC(Karana, Models, CubicSplineProfileGenerator, create))
      • Function def(py::init<>&<::>::create, py::arg(“name”), py::arg(“t_i”), py::arg(“q_i”), py::arg(“u_i”), py::arg(“t_f”), py::arg(“q_f”), py::arg(“u_f”), DOC(Karana, Models, CubicSplineProfileGenerator, create))
      • Function def(py::init<>&::create, py::arg(“name”), py::arg(“mm”), py::arg(“nd1”), py::arg(“nd2”), DOC(Karana, Models, SpringDamper, create))
      • Function def(py::init<>&::create, py::arg(“name”), py::arg(“mm”), py::arg(“sh”), DOC(Karana, Models, SubhingeSpringDamper, create))
      • Function def(py::init<>&::create, py::arg(“name”), py::arg(“mm”), py::arg(“scene”), DOC(Karana, Models, UpdateProxyScene, create))
      • Function def(py::init<>&::create, py::arg(“name”), py::arg(“mm”), py::arg(“rt_speed”), DOC(Karana, Models, SyncRealTime, create))
      • Function def(py::init<>&::create, py::arg(“name”), py::arg(“mm”), DOC(Karana, Models, GilRelease, create))
      • Function def_readwrite
      • Function DOC(Karana, Models, GravityInterface, setGravity)
      • Function DOC(Karana, Models, GravityInterface, isReady)
      • Function DOC(Karana, Models, UniformGravity, create)
      • Function DOC(Karana, Models, PointMassGravity, create)
      • Function DOC(Karana, Models, PointMassGravity, mu)
      • Function DOC(Karana, Models, PointMassGravity, getObjIds)
      • Function DOC(Karana, Models, ProfileGeneratorVars, getQ)
      • Function DOC(Karana, Models, ProfileGeneratorVars, getU)
      • Function DOC(Karana, Models, ProfileGeneratorVars, getUdot)
      • Function DOC(Karana, Models, ProfileGenerator, getU)
      • Function DOC(Karana, Models, ProfileGenerator, getUdot)
      • Function DOC(Karana, Models, ProfileGenerator, getVars)
      • Function DOC(Karana, Models, LinearProfileGenerator, create)
      • Function DOC(Karana, Models, LinearProfileGenerator, t_i)
      • Function DOC(Karana, Models, LinearProfileGenerator, t_f)
      • Function DOC(Karana, Models, LinearProfileGenerator, q_i)
      • Function DOC(Karana, Models, LinearProfileGenerator, q_f)
      • Function DOC(Karana, Models, ConstantProfileGenerator, create)
      • Function DOC(Karana, Models, ConstantProfileGenerator, q)
      • Function DOC(Karana, Models, CubicSplineProfileGenerator, create)
      • Function DOC(Karana, Models, CubicSplineProfileGenerator, setValues)
      • Function DOC(Karana, Models, SpringDamperParamsVars, unsprung_length)
      • Function DOC(Karana, Models, SpringDamperParamsVars, k)
      • Function DOC(Karana, Models, SpringDamperParamsVars, d)
      • Function DOC(Karana, Models, SpringDamperParams, isReady)
      • Function DOC(Karana, Models, SpringDamperParams, unsprung_length)
      • Function DOC(Karana, Models, SpringDamperParams, d)
      • Function DOC(Karana, Models, SpringDamperParams, k)
      • Function DOC(Karana, Models, SpringDamperParams, getVars)
      • Function DOC(Karana, Models, SpringDamperScratchVars, offset)
      • Function DOC(Karana, Models, SpringDamperScratchVars, position_error)
      • Function DOC(Karana, Models, SpringDamperScratchVars, velocity_error)
      • Function DOC(Karana, Models, SpringDamperScratchVars, stiffness_force)
      • Function DOC(Karana, Models, SpringDamperScratchVars, damping_force)
      • Function DOC(Karana, Models, SpringDamperScratchVars, total_force)
      • Function DOC(Karana, Models, SpringDamperScratch, offset)
      • Function DOC(Karana, Models, SpringDamperScratch, position_error)
      • Function DOC(Karana, Models, SpringDamperScratch, velocity_error)
      • Function DOC(Karana, Models, SpringDamperScratch, stiffness_force)
      • Function DOC(Karana, Models, SpringDamperScratch, damping_force)
      • Function DOC(Karana, Models, SpringDamperScratch, total_force)
      • Function DOC(Karana, Models, SpringDamperScratch, getVars)
      • Function DOC(Karana, Models, SpringDamper, create)
      • Function DOC(Karana, Models, SpringDamper, preDeriv)
      • Function DOC(Karana, Models, SpringDamper, sourceNode)
      • Function DOC(Karana, Models, SpringDamper, targetNode)
      • Function DOC(Karana, Models, PinJointLimitsParams, isReady)
      • Function DOC(Karana, Models, PinJointLimitsParams, upper_limit)
      • Function DOC(Karana, Models, PinJointLimitsParams, lower_limit)
      • Function DOC(Karana, Models, PinJointLimitsParams, d)
      • Function DOC(Karana, Models, PinJointLimitsParams, k)
      • Function DOC(Karana, Models, SubhingeSpringDamperParams, isReady)
      • Function DOC(Karana, Models, SubhingeSpringDamperParams, setpoint)
      • Function DOC(Karana, Models, SubhingeSpringDamperParams, d)
      • Function DOC(Karana, Models, SubhingeSpringDamperParams, k)
      • Function DOC(Karana, Models, SubhingeSpringDamper, create)
      • Function DOC(Karana, Models, SubhingeSpringDamper, preDeriv)
      • Function DOC(Karana, Models, SubhingeSpringDamper, getSubhinge)
      • Function DOC(Karana, Models, SubhingeForceLimitsParams, isReady)
      • Function DOC(Karana, Models, SubhingeForceLimitsParams, lower_limits)
      • Function DOC(Karana, Models, SubhingeForceLimitsParams, upper_limits)
      • Function DOC(Karana, Models, PIDParamsVars, kp)
      • Function DOC(Karana, Models, PIDParamsVars, kd)
      • Function DOC(Karana, Models, PIDParamsVars, ki)
      • Function DOC(Karana, Models, PIDParams, isReady)
      • Function DOC(Karana, Models, PIDParams, kp)
      • Function DOC(Karana, Models, PIDParams, kd)
      • Function DOC(Karana, Models, PIDParams, ki)
      • Function DOC(Karana, Models, PIDParams, getVars)
      • Function DOC(Karana, Models, UpdateProxyScene, create)
      • Function DOC(Karana, Models, UpdateProxyScene, postHop)
      • Function DOC(Karana, Models, UpdateProxyScene, getProxyScene)
      • Function DOC(Karana, Models, SyncRealTime, create)
      • Function DOC(Karana, Models, SyncRealTime, preHop)
      • Function DOC(Karana, Models, SyncRealTime, postHop)
      • Function DOC(Karana, Models, SyncRealTime, getRealTimeSpeed)
      • Function DOC(Karana, Models, GilRelease, create)
      • Function DOC(Karana, Models, GilRelease, postHop)
      • Function DOC(Karana, Models, TimeDisplayParamsVars, color)
      • Function DOC(Karana, Models, TimeDisplayParams, isReady)
      • Function DOC(Karana, Models, TimeDisplayParams, color)
      • Function DOC(Karana, Models, TimeDisplayParams, getVars)
      • Function DOC(Karana, Models, GraphicalSceneMovieParams, isReady)
      • Function DOC(Karana, Models, GraphicalSceneMovieParams, dir)
      • Function DOC(Karana, Models, GraphicalSceneMovieParams, filename_prefix)
      • Function DOC(Karana, Models, GraphicalSceneMovieParams, render_first_frame)
      • Function DOC(Karana, Models, ProjectConstraintErrorParams, isReady)
      • Function DOC(Karana, Models, ProjectConstraintErrorParams, tol)
      • Function DOC(Karana, Models, DataLoggerParams, isReady)
      • Function DOC(Karana, Models, DataLoggerParams, log_first_step)
      • Function DOC(Karana, Models, DataPlotterParams, isReady)
      • Function DOC(Karana, Models, DataPlotterParams, log_first_step)
      • Function Karana::Core::_dummy
      • Function Karana::Core::_ensureRegisteredPy
      • Function Karana::Core::_numTraceCheck
      • Function Karana::Core::_numTraceInt(std::string_view)
      • Function Karana::Core::_numTraceInt(msg_f)
      • Template Function Karana::Core::_numTraceInt(spdlog::format_string_t<Args…>, Args&&…)
      • Template Function Karana::Core::addToDSMethod
      • Template Function Karana::Core::addToStateDSMethod
      • Template Function Karana::Core::addVarsToStruct
      • Function Karana::Core::allDestroyed
      • Function Karana::Core::allHealthy
      • Function Karana::Core::allReady
      • Template Function Karana::Core::CallbackRegistryPybind11
      • Template Function Karana::Core::const_pointer_cast
      • Template Function Karana::Core::createSharedPtrDiscard
      • Function Karana::Core::debug(std::string_view)
      • Function Karana::Core::debug(msg_f)
      • Template Function Karana::Core::debug(spdlog::format_string_t<Args…>, Args&&…)
      • Function Karana::Core::debugJson(const nlohmann::ordered_json&, OrderedJsonToString)
      • Function Karana::Core::debugJson(const nlohmann::json&, JsonToString)
      • Function Karana::Core::defaultJsonToString
      • Function Karana::Core::defaultOrderedJsonToString
      • Function Karana::Core::deprecated
      • Template Function Karana::Core::deprecatedWrapper
      • Template Function Karana::Core::discard
      • Template Function Karana::Core::dynamic_pointer_cast
      • Function Karana::Core::error(std::string_view)
      • Function Karana::Core::error(msg_f)
      • Template Function Karana::Core::error(spdlog::format_string_t<Args…>, Args&&…)
      • Function Karana::Core::findShareDir
      • Function Karana::Core::findVariablesInFrame
      • Function Karana::Core::findVariablesInGc
      • Function Karana::Core::getVarType
      • Function Karana::Core::info(std::string_view)
      • Function Karana::Core::info(msg_f)
      • Template Function Karana::Core::info(spdlog::format_string_t<Args…>, Args&&…)
      • Function Karana::Core::sharedPtrClearPyVariable
      • Function Karana::Core::sharedPtrDiscard
      • Function Karana::Core::sharedPtrDiscardVec
      • Template Function Karana::Core::static_pointer_cast
      • Function Karana::Core::trace(std::string_view)
      • Function Karana::Core::trace(msg_f)
      • Template Function Karana::Core::trace(spdlog::format_string_t<Args…>, Args&&…)
      • Function Karana::Core::traceJson(const nlohmann::ordered_json&, OrderedJsonToString)
      • Function Karana::Core::traceJson(const nlohmann::json&, JsonToString)
      • Function Karana::Core::warn(std::string_view)
      • Function Karana::Core::warn(msg_f)
      • Template Function Karana::Core::warn(spdlog::format_string_t<Args…>, Args&&…)
      • Function Karana::Integrators::strToIntegratorType
      • Function Karana::KUtils::visualizeFrameToFrameRates
      • Function Karana::KUtils::visualizeInterBodyForce
      • Function Karana::KUtils::visualizeInterBodyTorque
      • Function Karana::KUtils::visualizeNodeForce
      • Function Karana::KUtils::visualizeNodeTorque
      • Function Karana::Math::buildNaNWithPayload
      • Template Function Karana::Math::dump
      • Template Function Karana::Math::dumpString
      • Template Function Karana::Math::getIndepColIndices
      • Template Function Karana::Math::getIndepRowColIndices
      • Template Function Karana::Math::getRank
      • Template Function Karana::Math::getSingularValues
      • Function Karana::Math::isNaNWithPayload
      • Function Karana::Math::isNotReadyNaN
      • Function Karana::Math::isReady(const Ktime&)
      • Template Function Karana::Math::isReady(const Eigen::MatrixBase<Derived>&)
      • Template Function Karana::Math::isReady(const Eigen::ArrayBase<Derived>&)
      • Function Karana::Math::ktimeToSeconds
      • Function Karana::Math::makeNotReady(Ktime&)
      • Template Function Karana::Math::makeNotReady(Eigen::DenseBase<Derived>&)
      • Function Karana::Math::secondsToKtime
      • Function Karana::Math::solveLcpPgs
      • Function Karana::Math::solveLcpPsor
      • Function Karana::Math::tilde
      • Template Function Karana::Models::KModelPybind11
      • Function Karana::Scene::defaultGeometry
      • Function Karana::Scene::defaultMaterial
      • Function Karana::WebUI::uuidv4
      • Function load
      • Function localtime_thread_safe
      • Function operator<<
      • Function py::class_< DataLoggerParams, kc::ks_ptr< DataLoggerParams > >
      • Function py::class_< DataPlotterParams, kc::ks_ptr< DataPlotterParams > >
      • Function py::class_< GraphicalSceneMovieParams, kc::ks_ptr< GraphicalSceneMovieParams > >
      • Function py::class_< PIDParams, kc::ks_ptr< PIDParams > >
      • Function py::class_< PIDParamsVars, Karana::Core::BaseVars, kc::ks_ptr< PIDParamsVars > >
      • Function py::class_< PinJointLimitsParams, kc::ks_ptr< PinJointLimitsParams > >
      • Function py::class_< ProjectConstraintErrorParams, kc::ks_ptr< ProjectConstraintErrorParams > >
      • Function py::class_< SpringDamperParams, kc::ks_ptr< SpringDamperParams > >
      • Function py::class_< SpringDamperParamsVars, Karana::Core::BaseVars, kc::ks_ptr< SpringDamperParamsVars > >
      • Function py::class_< SpringDamperScratch, kc::ks_ptr< SpringDamperScratch > >
      • Function py::class_< SpringDamperScratchVars, Karana::Core::BaseVars, kc::ks_ptr< SpringDamperScratchVars > >
      • Function py::class_< SubhingeForceLimitsParams, kc::ks_ptr< SubhingeForceLimitsParams > >
      • Function py::class_< SubhingeSpringDamperParams, kc::ks_ptr< SubhingeSpringDamperParams > >
      • Function py::class_< TimeDisplayParams, kc::ks_ptr< TimeDisplayParams > >
      • Function py::class_< TimeDisplayParamsVars, Karana::Core::BaseVars, kc::ks_ptr< TimeDisplayParamsVars > >
      • Function PyArrayVecProfileGenerator
      • Function pybind11::detail::FLOAT_QUANTITY(Karana::Math::Length, Karana.Math.Ktyping., length)
      • Function pybind11::detail::FLOAT_QUANTITY(Karana::Math::Angle, Karana.Math.Ktyping., angle)
      • Function pybind11::detail::FLOAT_QUANTITY(Karana::Math::Mass, Karana.Math.Ktyping., mass)
      • Function pybind11::detail::FLOAT_QUANTITY(Karana::Math::GravitationalParameter, Karana.Math.Ktyping., gravitational_parameter)
      • Function pybind11::detail::MAT33_QUANTITY
      • Function pybind11::detail::VEC3_QUANTITY(Karana::Math::Length3, Karana.Math.Ktyping., length)
      • Function pybind11::detail::VEC3_QUANTITY(Karana::Math::Angle3, Karana.Math.Ktyping., angle)
      • Function pybind11::detail::VEC3_QUANTITY(Karana::Math::Velocity3, Karana.Math.Ktyping., velocity)
      • Function pybind11::detail::VEC3_QUANTITY(Karana::Math::Acceleration3, Karana.Math.Ktyping., acceleration)
      • Function pybind11::detail::VEC3_QUANTITY(Karana::Math::AngularVelocity3, Karana.Math.Ktyping., angular_velocity)
      • Function pybind11::detail::VEC3_QUANTITY(Karana::Math::AngularAcceleration3, Karana.Math.Ktyping., angular_acceleration)
      • Function pybind11::detail::VEC3_QUANTITY(Karana::Math::Force3, Karana.Math.Ktyping., force)
      • Function pybind11::detail::VEC3_QUANTITY(Karana::Math::Torque3, Karana.Math.Ktyping., torque)
      • Function pybind11::detail::VEC3_QUANTITY(Karana::Math::Momentum3, Karana.Math.Ktyping., momentum)
      • Function pybind11::detail::VEC3_QUANTITY(Karana::Math::AngularMomentum3, Karana.Math.Ktyping., angular_momentum)
      • Function PYBIND11_DECLARE_HOLDER_TYPE
      • Function PYBIND11_TYPE_CASTER
      • Function PyFloatConstantProfileGenerator
      • Function PyFloatCubicSplineProfileGenerator
      • Function PyFloatLinearProfileGenerator
      • Function PyFloatProfileGenerator
      • Function PyGilRelease
      • Function PyGravityInterface
      • Function PyGravityVars
      • Function PyPointMassGravity
      • Function PySpringDamper
      • Function PySubhingeSpringDamper
      • Function PySyncRealTime
      • Function PyUniformGravity
      • Function PyUnitQuaternionConstantProfileGenerator
      • Function PyUnitQuaternionProfileGenerator
      • Function PyUpdateProxyScene
      • Function PyVecConstantProfileGenerator
      • Function PyVecCubicSplineProfileGenerator
      • Function PyVecLinearProfileGenerator
      • Template Variable ConstantProfileGenerator< double >::create
      • Template Variable ConstantProfileGenerator< double >::q
      • Template Variable ConstantProfileGenerator< km::ArrayVec >::create
      • Template Variable ConstantProfileGenerator< km::ArrayVec >::q
      • Template Variable ConstantProfileGenerator< km::UnitQuaternion >::create
      • Template Variable ConstantProfileGenerator< km::UnitQuaternion >::q
      • Template Variable CubicSplineProfileGenerator< double >::create
      • Template Variable CubicSplineProfileGenerator< double >::setValues
      • Template Variable CubicSplineProfileGenerator< km::ArrayVec >::create
      • Template Variable CubicSplineProfileGenerator< km::ArrayVec >::setValues
      • Variable has_pybind11_caster_v
      • Variable Karana::KUtils::extract_cols_v
      • Variable Karana::KUtils::extract_rows_v
      • Variable Karana::KUtils::extract_vector_rows_v
      • Variable Karana::KUtils::is_eigen_int_type_v
      • Variable Karana::KUtils::is_eigen_type_v
      • Variable Karana::KUtils::is_eigen_vector_v
      • Variable Karana::Math::notReadyNaN
      • Variable Karana::Math::notReadyPayload
      • Variable Karana::Scene::LAYER_ALL
      • Variable Karana::Scene::LAYER_COLLISION
      • Variable Karana::Scene::LAYER_CUSTOM0
      • Variable Karana::Scene::LAYER_CUSTOM1
      • Variable Karana::Scene::LAYER_CUSTOM10
      • Variable Karana::Scene::LAYER_CUSTOM11
      • Variable Karana::Scene::LAYER_CUSTOM12
      • Variable Karana::Scene::LAYER_CUSTOM13
      • Variable Karana::Scene::LAYER_CUSTOM14
      • Variable Karana::Scene::LAYER_CUSTOM15
      • Variable Karana::Scene::LAYER_CUSTOM16
      • Variable Karana::Scene::LAYER_CUSTOM17
      • Variable Karana::Scene::LAYER_CUSTOM18
      • Variable Karana::Scene::LAYER_CUSTOM19
      • Variable Karana::Scene::LAYER_CUSTOM2
      • Variable Karana::Scene::LAYER_CUSTOM20
      • Variable Karana::Scene::LAYER_CUSTOM21
      • Variable Karana::Scene::LAYER_CUSTOM22
      • Variable Karana::Scene::LAYER_CUSTOM23
      • Variable Karana::Scene::LAYER_CUSTOM3
      • Variable Karana::Scene::LAYER_CUSTOM4
      • Variable Karana::Scene::LAYER_CUSTOM5
      • Variable Karana::Scene::LAYER_CUSTOM6
      • Variable Karana::Scene::LAYER_CUSTOM7
      • Variable Karana::Scene::LAYER_CUSTOM8
      • Variable Karana::Scene::LAYER_CUSTOM9
      • Variable Karana::Scene::LAYER_FLUIDS
      • Variable Karana::Scene::LAYER_GRAPHICS
      • Variable Karana::Scene::LAYER_NONE
      • Variable Karana::Scene::LAYER_ORNAMENTAL
      • Variable Karana::Scene::LAYER_PHYSICAL
      • Variable Karana::Scene::LAYER_PHYSICAL_GRAPHICS
      • Variable Karana::Scene::LAYER_RESERVED0
      • Variable Karana::Scene::LAYER_RESERVED1
      • Variable Karana::Scene::LAYER_RESERVED2
      • Variable Karana::Scene::LAYER_RESERVED3
      • Variable Karana::Scene::LAYER_RESERVED4
      • Variable Karana::Scene::LAYER_RESERVED5
      • Variable Karana::Scene::LAYER_RESERVED6
      • Variable Karana::Scene::LAYER_RESERVED7
      • Variable Karana::Scene::LAYER_STICK_FIGURE
      • Template Variable LinearProfileGenerator< double >::create
      • Template Variable LinearProfileGenerator< double >::q_f
      • Template Variable LinearProfileGenerator< double >::q_i
      • Template Variable LinearProfileGenerator< double >::t_f
      • Template Variable LinearProfileGenerator< double >::t_i
      • Template Variable LinearProfileGenerator< km::ArrayVec >::create
      • Template Variable LinearProfileGenerator< km::ArrayVec >::q_f
      • Template Variable LinearProfileGenerator< km::ArrayVec >::q_i
      • Template Variable LinearProfileGenerator< km::ArrayVec >::t_f
      • Template Variable LinearProfileGenerator< km::ArrayVec >::t_i
      • Variable m
      • Variable mm
      • Template Variable ProfileGenerator< double >::getU
      • Template Variable ProfileGenerator< double >::getUdot
      • Template Variable ProfileGenerator< km::ArrayVec >::getU
      • Template Variable ProfileGenerator< km::ArrayVec >::getUdot
      • Template Variable ProfileGenerator< km::UnitQuaternion >::getU
      • Template Variable ProfileGenerator< km::UnitQuaternion >::getUdot
      • Variable PyKmodelComputedTorque
      • Variable PyKmodelDataLogger
      • Variable PyKmodelDataPlotter
      • Variable PyKmodelGilRelease
      • Variable PyKmodelGraphicalSceneMovie
      • Variable PyKmodelPID
      • Variable PyKmodelPinJointLimits
      • Variable PyKmodelProjectConstraintError
      • Variable PyKmodelSpringDamper
      • Variable PyKmodelSubhingeForceLimits
      • Variable PyKmodelSubhingeSpringDamper
      • Variable PyKmodelSyncRealTime
      • Variable PyKmodelTimeDisplay
      • Variable PyKmodelUniformGrav
      • Variable PyKmodelUpdateProxyScene
      • Variable self
      • Define ADD_TO_DS_METHOD_CASTER
      • Define ADD_TO_STATE_DS_METHOD_CASTER
      • Define FLOAT_QUANTITY
      • Define KARANA_MODIFIED
      • Define KARANA_VERSION_MAJOR
      • Define KARANA_VERSION_MINOR
      • Define KARANA_VERSION_PATCH
      • Define KARANA_VERSION_STRING
      • Define MAT33_QUANTITY
      • Define MATH_EPSILON
      • Define numTrace
      • Define VEC3_QUANTITY
      • Typedef Karana::Core::Allocator
      • Typedef Karana::Core::id_t
      • Typedef Karana::Core::JsonToString
      • Typedef Karana::Core::ks_ptr
      • Typedef Karana::Core::msg_f
      • Typedef Karana::Core::OrderedJsonToString
      • Typedef Karana::Dynamics::cost_fn
      • Typedef Karana::Dynamics::DynamicFunctorNumJac
      • Typedef Karana::Dynamics::f
      • Typedef Karana::Dynamics::functor_type
      • Typedef Karana::Dynamics::jac_fn
      • Typedef Karana::Dynamics::solver_type
      • Typedef Karana::Integrators::DerivativeFunction
      • Typedef Karana::Integrators::ResidualsFunction
      • Typedef Karana::KUtils::PlotDataFnType
      • Typedef Karana::KUtils::PlotDataType
      • Typedef Karana::KUtils::XDataFnType
      • Typedef Karana::Math::Array
      • Typedef Karana::Math::ArrayVec
      • Typedef Karana::Math::ConstMatSlice
      • Typedef Karana::Math::ConstVec3Slice
      • Typedef Karana::Math::ConstVecSlice
      • Typedef Karana::Math::fn
      • Typedef Karana::Math::Ktime
      • Typedef Karana::Math::lin_fn
      • Typedef Karana::Math::Mat
      • Typedef Karana::Math::Mat33
      • Typedef Karana::Math::Mat44
      • Typedef Karana::Math::Mat66
      • Typedef Karana::Math::Mat6n
      • Typedef Karana::Math::MatSlice
      • Typedef Karana::Math::num_diff_functor_type
      • Typedef Karana::Math::Vec
      • Typedef Karana::Math::Vec3
      • Typedef Karana::Math::Vec3Slice
      • Typedef Karana::Math::Vec4
      • Typedef Karana::Math::Vec6
      • Typedef Karana::Math::VecInt
      • Typedef Karana::Math::VecSlice
      • Typedef Karana::Scene::layer_t
      • Typedef Karana::Scene::TextureCache
      • Typedef Karana::Scene::TextureData
      • Typedef Karana::Scene::VarMaterial
      • Typedef Karana::Scene::VarProjection
      • Typedef Karana::Scene::VarStaticGeometry
      • Typedef Karana::WebUI::HeaderList
      • Typedef Karana::WebUI::StateMap
      • Typedef Karana::WebUI::StyleMap
      • Typedef SUNComm
      • Typedef sunrealtype
      • Typedef type
  • Conventions
  • Glossary
  • .ipynb

Procedural n-link pendulum collision example

Contents

  • Create the n-link Pendulum Multibody
  • Setup the kdFlex Scene
  • Setup Geometries
  • Setup KModels
  • Set Initial State
  • Register a Timed Event
  • Run the Simulation
  • Clean Up the Simulation
  • Summary
  • Further Readings

Procedural n-link pendulum collision example#

This notebook is a more advanced version of the n-link pendulum and 2-link pendulum collision tutorials.In this notebook a pendulum is created using the procedural approach to allow for an n number of linked bodies to be built at once. Collision detection is added in this notebook and visualized using material colors.

Requirements:

  • n-link Pendulum

  • 2-link Pendulum Collision

In this example we will:

  • Create the n-link pendulum multibody

  • Create the kdFlex Scene

  • Setup geometries

  • Set up the state propagator and models

  • Set initial state

  • Register a timed event

  • Run the simulation

  • Clean up the simulation

For a more in-depth descriptions of kdflex concepts see usage.

import numpy as np
from typing import cast
from math import pi
import atexit

import Karana.Core as kc
import Karana.Math as km
import Karana.Integrators as ki
import Karana.Frame as kf
import Karana.Dynamics as kd
import Karana.Dynamics.SOADyn_types as kdt
import Karana.Scene as ks
import Karana.KUtils as ku
import Karana.Models as kmdl
import Karana.Collision as kcoll
from Karana.KUtils.Sim import Sim

Create the n-link Pendulum Multibody#

See Multibody or Frames for more information relating to this step.

def populateMbody(n_links: int, sim: Sim) -> None:
    """Populate the Multibody.

    Parameters
    ----------
    n_links : int
        Number of links in the pendulum system.
    sim : Sim
        The Simulation whose Multibody will be populated.
    """
    mb = sim.mb

    # inertia used for both bodies
    spI = km.SpatialInertia(2.0, np.zeros(3), np.diag([3, 2, 1]))

    # inboard to joint transform used for both bodies
    ib2j = km.HomTran()

    # body to joint transform used for both bodies
    b2j = km.HomTran(np.array([0, 0, 1.0]))

    # adding colored material
    mat_info = ks.PhysicalMaterialInfo()
    mat_info.color = ks.Color.BLUE
    blue = ks.PhysicalMaterial(mat_info)
    mat_info.color = ks.Color.LIGHTBLUE
    light_blue = ks.PhysicalMaterial(mat_info)

    # Add a scene part that is for collisions and
    sp_col = ks.ScenePartSpec()
    sp_col.name = "sp_collision"
    sp_col.geometry = ks.SphereGeometry(0.3)
    sp_col.material = blue
    sp_col.transform = km.HomTran([0.0, 0.0, 0.0])
    sp_col.scale = [1, 1, 1]
    # LAYER_PHYSICAL is default ScenePart layer which this part belongs to

    # Add a scene part that is purely visual
    sp_vis = ks.ScenePartSpec()
    sp_vis.name = "sp_graphics"
    sp_vis.geometry = ks.CylinderGeometry(0.025, 1.0)
    sp_vis.material = light_blue
    sp_vis.transform = km.HomTran(q=km.UnitQuaternion(pi / 2, [1.0, 0.0, 0.0]), vec=[0.0, 0.0, 0.5])
    sp_vis.scale = [1, 1, 1]
    sp_vis.layers = ks.LAYER_PHYSICAL_GRAPHICS

    # params for each body in pendulum
    params = kd.PhysicalBodyParams(
        spI=spI,
        axes=[np.array([0.0, 1.0, 0.0])],
        body_to_joint_transform=b2j,
        inb_to_joint_transform=ib2j,
        scene_part_specs=[sp_col, sp_vis],
    )

    kd.PhysicalBody.addSerialChain(
        "body",
        n_links,
        cast(kd.PhysicalBody, mb.virtualRoot()),
        htype=kd.HingeType.BALL,
        params=params,
    )

    # finalize and verify multibody
    mb.ensureHealthy()
    mb.resetData()
    assert kc.allReady()
n_links = 5
sim = Sim()
populateMbody(n_links, sim)

# get the first body
bd1 = sim.mb.getBody("body_0")

# get the second body
bd2 = sim.mb.getBody("body_1")

Setup the kdFlex Scene#

Next we setup kdflex’s graphics by calling the setupGraphics helper method on the multibody. This method takes care of setting up the graphics environment.

See Visualization and Scene Layer for more information relating to this section.

_, web_scene = sim.setupGraphics(port=0, axes=0.5)
# position the viewpoint camera of the visualization:
web_scene.defaultCamera().pointCameraAt([-4, 8, -n_links / 2 + 2], [0, 0, -n_links / 2], [0, 0, 1])
web_scene._setShadows([0, 0, -1])

# get the proxy scene
proxy_scene = sim.mb.getScene()

To our scene layer, we register a Karana.Scene.CoalScene instance to perform collision and distance queries using the geometries populated in Karana.Scene.ProxyScene. CoalScene is a wrapper of the open source Coal project.

See Collisions for more information.

col_scene = ks.CoalScene("collision_scene")
proxy_scene.registerClientScene(col_scene, sim.mb.virtualRoot(), layers=ks.LAYER_COLLISION)

Setup Geometries#

For the pendulum, we create 3d geometries with associated material properties and attach them to bodies. This is commonly useful for collision detection and 3d visualization.

We then add geometries for the floor, wall, and top pendulum connector

# alternate geometries
box_geom = ks.BoxGeometry(0.1, 0.1, 0.1)
capsule_geom = ks.CapsuleGeometry(0.1, 0.15)

# create an obstacle wall  to be placed in the path of the pendulum
obstacle_geom = ks.BoxGeometry(0.5, 1.8, n_links + 0.1)

# create a ground for the pendulum to collide with
ground_geom = ks.BoxGeometry(7.5, 7.5, 0.5)

# create a connection part for the top of the pendulum
connection_geom = ks.BoxGeometry(0.25, 0.25, 0.1)

# create various visual materials to color the bodies
mat_info = ks.PhysicalMaterialInfo()
mat_info.color = ks.Color.BLUE
blue = ks.PhysicalMaterial(mat_info)
mat_info.color = ks.Color.RED
red = ks.PhysicalMaterial(mat_info)
mat_info.color = ks.Color.DARKSEAGREEN
seagreen = ks.PhysicalMaterial(mat_info)
mat_info.color = ks.Color.BEIGE
beige = ks.PhysicalMaterial(mat_info)
mat_info.color = ks.Color.BLACK
black = ks.PhysicalMaterial(mat_info)

# manually add some objects that are not attached to the pendulum (implicitly attached to the root frame)
root_scene_node = ks.ProxySceneNode("root_scene_node", scene=proxy_scene)

# add the wall
obstacle_part = ks.ProxyScenePart(
    "obstacle_part", scene=proxy_scene, geometry=obstacle_geom, material=seagreen
)
obstacle_part.setTranslation([2.75, 0, -n_links / 2 - 0.1])

# add the ground
ground = ks.ProxyScenePart(
    "ground", scene=proxy_scene, geometry=ground_geom, material=beige, layers=ks.LAYER_PHYSICAL
)
ground.setTranslation([0, 0, -n_links - 0.25])

# add an upper connection point for the pendulum that is purely visual
connection = ks.ProxyScenePart(
    "ground",
    scene=proxy_scene,
    geometry=connection_geom,
    material=black,
    layers=ks.LAYER_PHYSICAL_GRAPHICS,
)

del (
    mat_info,
    seagreen,
    black,
    beige,
    connection_geom,
    ground_geom,
    capsule_geom,
    box_geom,
    obstacle_geom,
)

Because we are procedurally generating our pendulum, this dictionary is initialized to store each body and its ScenePart. We also add axes for visualization

# creating an empty dictionary which is populated
# by scene parts from the multibody
scene_part_dict = {}
# visualize axes for important frames
root_scene_node.graphics().showAxes(0.5)

# loop through each body to add SceneParts to a dictionary
for link in list(range(0, n_links)):
    body_string = f"body_{link}"
    part_string = f"body_{link}_part"

    # retrieve the sphere ScenePart visual geometries to work with later. We only want the spheres so index for 0
    scene_part_dict[part_string] = sim.mb.getBody(body_string).getSceneParts()[0]

    # add axes to object
    scene_part_dict[part_string].graphics().showAxes(0.5)

Setup KModels#

Now, we setup and register our KModels as well.

See Models for more concepts and information.

# set up state propagator
integ = sim.sp.getIntegrator()

# Create a UniformGravity model, and set it's gravitational acceleration.
ug = kmdl.Gravity("grav_model", sim.sp, kmdl.UniformGravity("uniform_gravity"), sim.mb)
ug.getGravityInterface().setGravity(np.array([0, 0, -9.81]), 0.0, kmdl.OutputUpdateType.PRE_HOP)
del ug

# sync the simulation time with real-time.
kmdl.SyncRealTime("sync_real_time", sim.sp, 1.0)
<Karana.Models.SyncRealTime at 0x7e2b898a8f70>

Because our CoalScene managed distance queries and collision detection, we now attach a Karana.Models.PenaltyContact using the CoalScene and ProxyScene to apply counter forces whenever registered bodies collide.

# Set contact force model parameters
hc = kcoll.HuntCrossley("hunt_crossley_contact")
hc.params.kp = 100000
hc.params.kc = 20000
hc.params.mu = 0.3
hc.params.n = 1.5
hc.params.linear_region_tol = 1e-3

kmdl.PenaltyContact(
    "penalty_contact", sim.sp, sim.mb, [kcoll.FrameCollider(proxy_scene, col_scene)], hc
)
del hc

The following section is responsible for indicating collisions of the pendulum by coloring the scene parts when a collision occur. We utilize Karana.Scene.CoalScene.cachedCollisions() which stores a list of collisions which occurred during the last collision scene sweep function, which is ran by the collision model. it loops through each Karana.Scene.CollisionInfo object and uses the information to lookup the scene parts corresponding the colliding body and then recolors it. The col_mat_reset_list is a way to recolor the last collisions after the collision has stopped occurring.

col_mat_reset_list = []


def post_step_fn(t, x):
    """Change material color based on collision status.

    If bodies are is colliding, make their materials red. Otherwise, make them blue.

    Parameters
    ----------
    t : float
        The current time.
    x : NDArray[np.float64]
       The current state.
    """
    # reset the materials of the last collision scene parts
    global col_mat_reset_list
    if col_mat_reset_list:
        for mat_reset_part in col_mat_reset_list:
            mat_reset_part.setMaterial(blue)
        col_mat_reset_list = []

    # check if there are any cached collisions
    # and if so, loop through them
    # and recolor the scene parts that were involved in the collision
    if col_scene.cachedCollisions():
        for collision in col_scene.cachedCollisions():
            collision_body_1_id = collision.part1
            collision_body_2_id = collision.part2

            col_part_1 = col_scene.lookupPart(collision_body_1_id)
            col_part_2 = col_scene.lookupPart(collision_body_2_id)

            if col_part_1.name() == "collision_scene_sp_collision":
                collision_part = proxy_scene.lookupProxyFromImpl(col_part_1)
                collision_part.setMaterial(red)
                col_mat_reset_list.append(collision_part)

            if col_part_2.name() == "collision_scene_sp_collision":
                collision_part = proxy_scene.lookupProxyFromImpl(col_part_2)
                collision_part.setMaterial(red)
                col_mat_reset_list.append(collision_part)


sim.sp.fns.post_hop_fns["update_and_info"] = post_step_fn

Set Initial State#

Before we begin our simulation, we set the initial state for our multibody and statepropagator.

When accessing or modifying generalized coordinates for a subhinge, it is recommended to directly set the subhinge’s values rather than for the entire multibody in order to avoid ambiguity.

# modify the initial multibody state
bd1 = sim.mb.getBody("body_0")
bd1.parentHinge().subhinge(0).setQ([0.0, pi / 3, 0])  # try adding rotation around x or z axis
bd1.parentHinge().subhinge(0).setU([0.0, -0.5, 0.0])  # for a more chaotic pendulum swing

# set integrator state
sim.sp.hardReset()
t_init = np.timedelta64(0, "ns")
x_init = sim.sp.assembleState()
sim.sp.setTime(t_init)
sim.sp.setState(x_init)
sim.sp.ensureHealthy()

# syncs up the graphics
proxy_scene.update()

Register a Timed Event#

Because the penalty contact model applies forces proportional to the overlap between two objects in collision, it is necessary to shorten the period of the timed event. Otherwise, if a collision is only detected when 2 objects have significant overlap, unrealistic forces may be applied.

h = np.timedelta64(int(1e7), "ns")
t = kd.TimedEvent("hop_size", h, lambda _: None, False)
t.period = h

# register after time has been initialized
sim.sp.registerTimedEvent(t)
del t

Run the Simulation#

Karana.Dynamics.StatePropagator.advanceTo() can be increased to lengthen the simulation

# print the initial state
print(f"t = {float(integ.getTime()) / 1e9}s; x = {integ.getX()}")

sim.sp.advanceTo(5.0)
t = 0.0s; x = [ 0.          1.04719755  0.          0.          0.          0.
  0.          0.          0.          0.          0.          0.
  0.          0.          0.          0.         -0.5         0.
  0.          0.          0.          0.          0.          0.
  0.          0.          0.          0.          0.          0.        ]
<SpStatusEnum.REACHED_END_TIME: 1>

Clean Up the Simulation#

Below, we cleanup our simulation. We first delete local variables, cleanup our visualizer, discard remaining Karana objects, and optionally verify using allDestroyed.

def cleanup():
    """Cleanup the simulation."""
    global sim, col_scene, web_scene, proxy_scene
    global integ, bd1, bd2, ground, obstacle_part
    global root_scene_node, connection, red, blue, col_mat_reset_list, scene_part_dict
    del (
        integ,
        bd1,
        bd2,
        proxy_scene,
        web_scene,
        col_scene,
        ground,
        obstacle_part,
        root_scene_node,
        connection,
        red,
        blue,
        col_mat_reset_list,
        scene_part_dict,
        sim,
    )

    bc = kc.BaseContainer.singleton()
    bc.at_exit_fns.executeAndPopReverse()
    del bc


atexit.register(cleanup)
<function __main__.cleanup()>

Summary#

You now know how to setup a n-link pendulum with obstacles to simulate collisions. By attaching a CoalScene and creating a PenaltyContact model, the simulation is able to model collisions. And using a dictionary to track SceneParts for each body allowed us to visualize collisions by making the material red.

Further Readings#

Drive an ATRVjr rover

previous

2-link Pendulum Collision Example

next

Flexible Slider-Crank

Contents
  • Create the n-link Pendulum Multibody
  • Setup the kdFlex Scene
  • Setup Geometries
  • Setup KModels
  • Set Initial State
  • Register a Timed Event
  • Run the Simulation
  • Clean Up the Simulation
  • Summary
  • Further Readings

By Karana Dynamics Inc.

© Copyright 2025, Karana Dynamics Inc. Generated on 8 May 2026 18:30 UTC.