pymbs documentation - read the docs · as we don’t have a mac available for testing, we can’t...

78
PyMbs Documentation Release 2 Carsten Knoll, Christian Schubert, Jens Frenkel, Sebastian Voigt November 21, 2016

Upload: others

Post on 10-Jun-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs DocumentationRelease 2

Carsten Knoll, Christian Schubert, Jens Frenkel, Sebastian Voigt

November 21, 2016

Page 2: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules
Page 3: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

Contents

1 About 3

2 Getting Started 52.1 What is PyMbs? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.3 A First Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

3 Command Reference 133.1 General . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.2 Kinematic Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.3 Loads (Forces and Torques) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233.4 Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243.5 Visualisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273.6 Equation generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293.7 Code generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303.8 Interaction with PyTrajectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

4 Background 354.1 Deriving Equations of Motion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354.2 Explicit Handling of Kinematic Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

5 PyMbs Architecture and Design 435.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435.2 Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445.3 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465.4 Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465.5 Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

6 Troubleshooting 496.1 Error: PyScripter throws strange errors in Gui.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496.2 Anything Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

7 Examples 517.1 Simple Pendulum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517.2 Mass-Spring-Damper System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537.3 Rope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557.4 Four Bar Linkage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587.5 Inverted Pendulum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

i

Page 4: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

8 Developer Notes 658.1 Development History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658.2 Structure of the Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658.3 Building PyMbs under Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668.4 Running the Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668.5 Working on the Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

9 Indices and tables 69

Bibliography 71

ii

Page 5: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Contents:

Contents 1

Page 6: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

2 Contents

Page 7: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

CHAPTER 1

About

PyMbs is being developed at Dresden University of Technology at the Institute of Processing Machines and MobileMachinery by a questing quartet:

Fig. 1.1: Carsten Knoll & Christian Schubert & Jens Frenkel & Sebastian Voigt

We startetd working on PyMbs in July 2009, as we faced the need of a convenient way to obtain the equations ofmotion of complex mechanical systems to feed a real time simulatiuon environment based on the Modelica modelinglanguage. By the release of PyMbs 0.1 these aim could be achieved. Nevertheless PyMbs is subject to ongoingdevelopment to enhance its features and increase numeric performance. It is published under the LGPL license.

If you face any problems using PyMbs, feel free to contact us. As Christian’s got a heart for PyMbs users, he will beyour primary contact person. Of course you may consult any other developer as well.

Dresden University of Technology

Institute of Processing Machines and Mobile Machinery

Tel.: +49 (351) 463-39278

Fax: +49 (351) 463-37731

D-01062 Dresden, Germany

Chair of Construction Machines and Conveying Technology

• christian.schubert @ <tud>

• jens.frenkel @ <tud>

• sebastian.voigt @ mailbox.<tud>

Chair of Control Theory

• carsten.knoll @ <tud>

Further Contributors:

• Christoph Pohl - christoph.pohl1 @ mailbox.<tud>

3

Page 8: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

<tud> = tu-dresden.de

4 Chapter 1. About

Page 9: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

CHAPTER 2

Getting Started

This section is meant to be a quick start guide and shall provide an overview of the basic features and capabilities ofthe PyMbs module. For a more detailed description please consult the Command Reference.

2.1 What is PyMbs?

PyMbs is a tool to generate the equations of motion of holonomic multibody systems. The equations can be exportedto several target languages like Matlab, Modelica, Python or C++. Thus the output of PyMbs is a mathematical modelof the mechanical system which can be simulated by timestep integration.

The description of the mechanical system is text-based but held as easy and convenient as possible. The user assemblesthe system from a range of predefined objects like bodies, joints, loops and sensors. As this method may provoke typingerrors, especially when modelling more complex systems, it is possible to create a visualisation for the mechanicalsystem from CAD files or geometric primitives to check the consistency of the model. It is also possible to manipulatethe degrees of freedom interactively.

2.2 Installation

It was tested on Python 2.7. In this section the required modules are specified and afterwards a step-by-step instructionis given on how to install PyMbs on Windows machines, which is intended to help users who never got in touch withPython before.

2.2.1 Dependencies

• numpy

• scipy

• VTK

• matplotlib

• Qt4

5

Page 10: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

2.2.2 Windows

This guide assumes that no Python distribution is installed on your system. If Python is already installed, you maygo directly to A First Example. We strongly recommend the installation of a prebundled Python distribution to avoidtroubles regarding dependencies.

• Download Python(x,y) from http://www.pythonxy.com.

• Install Python(x,y). Make sure you selected ‘Full’ as ‘type of install’. This will install Python 2.7 to‘C:\Python27’ and Python(x,y) to ‘C:\Program Files\pythonxy’ per default.

Fig. 2.1: Python(x,y) installer

• Install PyMbs using the installer PyMbs-0.2.1-alpha.win32.exe.

Note that this programme must be run with administrator privileges. Please make sure that PyMbs uses thecorrect Python Version which is in ‘C:\Python27’ per default. This is especially important if there is more thanone Python distribution installed.

• You may use any text editor to write your PyMbs models. However, we recommend the use of PyScripter as itsupports syntax highlighting and code completion. It is freely available at http://code.google.com/p/pyscripter/.

• You can check your installation by starting Python(x,y) from your desktop and pressing the button next toIPython(x,y) which will start IPython. As soon as IPython has started a line saying In [1]: will appear. Now

6 Chapter 2. Getting Started

Page 11: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Fig. 2.2: PyMbs installer

2.2. Installation 7

Page 12: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

type from PyMbs.Input import *. If there is no error message and it jumps directly to In [2]: thenthe installation was successful.

Fig. 2.3: Check your installation

2.2.3 Linux

Currently, there are no PyMbs binaries for Linux. However, you can build PyMbs yourself. All you need is a C++Compiler, CMake and various python packages, specifically numpy, scipy, matplotlib, vtk and PyQt4. Under Debianand Ubuntu, you can install these with:

sudo apt-get install build-essential cmake python-numpy python-scipy python-vtk python-qt4 python-h5py python-matplotlib

Then all you have to do to build and install PyMbs is:

sudo python setup.py install

2.2.4 Mac OS

As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you havePython and its modules running, you only need to copy the PyMbs package to a folder of your choice and add it to thePYTHONPATH.

2.3 A First Example

2.3.1 Mechanical System

In order to demonstrate the usage of PyMbs a simple exemplary system shall be modeled. Consider the system of acrane crab given in figure PyMbs visualisation of the crane crab.

8 Chapter 2. Getting Started

Page 13: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

2.3.2 Model Description

Next the model of the Crane Crab is generated using PyMbs.

• Start PyScripter (or your favourite Python editor) and copy the following code into the editor window. Pleasenote that some systems mess up the apostrophe ‘?! If that is the case it is marked as red and has to be replacedmanually by a proper one.:

# import PyMbsfrom PyMbs.Input import *

# set up inertial frameworld=MbsSystem([0,0,-1])

# add inputs and parametersF=world.addInput('F', limits=[-10, 10], name='DrivingForce')m1=world.addParam('m1', 1.0)m2=world.addParam('m2', 1.0)l2=world.addParam('l2', 1.0)I2=world.addParam('I2', (m2*l2**2)/12)

# add bodiescrab=world.addBody(mass=m1, name='Crab')pend=world.addBody(mass=m2, inertia=diag([0,I2,0]), name='Pendulum')pend.addFrame(name='joint' , p=[0, 0, l2])pend.addFrame(name='middle', p=[0, 0, l2/2], R=rotMat(pi/2,'x'))

# add jointsjT = world.addJoint(world, crab, 'Tx', 1, name='TransCrab')jR = world.addJoint(crab, pend.joint, 'Ry', -1, name='RotPendulum')

# add load element and sensorworld.addLoad.CmpForce([F,0,0], crab, world)world.addSensor.Distance('d', crab, world)

# add visualisationworld.addVisualisation.Box(crab, 1, 0.5, 0.1)world.addVisualisation.Cylinder(pend.middle, 0.01, 1)world.addVisualisation.Sphere(pend, 0.1)

# generate equationsworld.genEquations.Explicit()

# generate simulation codeworld.genCode.Python('CraneCrab', './Output')

# show systemworld.show('CraneCrab')

• Once you have done this, you can run the model by clicking on the button with a green arrow inside. After ashort moment you should see a screen showing the crane crab (figure PyMbs visualisation of the crane crab).You may use the sliders on the left to move the crane crab and the pendulum which can be used for checking thekinematics of your assembly. In case you receive a Syntax Error you might have to replace the inverted commasby ‘proper ones’. Also note that, due to the fact that PyScripter does not properly reinitialise its Python engine,it might help to restart it as soon as you receive errors you cannot explain.

2.3. A First Example 9

Page 14: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Fig. 2.4: PyMbs visualisation of the crane crab

2.3.3 Code Export

Python

The command world.genCode(’py’, ’CraneCrab’) is used to export the equations of motion into Pythonformat. The generated module CraneCrab_der_state.py includes the function CraneCrab_der_state(t, y) which cal-culates the state derivative from a given state. This can be used in combination with any standard numerical integrator,which is able to solve differential equations of the form

�̇� = 𝑓(𝑦, 𝑡)

where y is the state vector and t the time.

Modelica

The Modelica code generator, accessible through world.genCode(’mo’,’CraneCrab’), creates a file calledCraneCrab_der_state.mo. It can be used in combination with any Standard Modelica tool such as OpenModelica(http://www.openmodelica.org) or JModelica (http://www.jmodelica.org). Note, that this special model is definedpartial since no equation for the input F is given. Usually, the driving force F is calculated directly inside Modelicausing the Modelica Standard Library (MSL). In order to combine this model with the MSL, it is recommended to writeanother Modelica model by hand as given in the listing below which inherits from the automatically generated modeland simply extends it by a mechanical connector:

model CraneCrabextends CraneCrab_der_state;

import Modelica.Mechanics.Translational.*;Interfaces.Flange_b flange;

equation

10 Chapter 2. Getting Started

Page 15: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

flange.f = F;flange.s = d[1];

end CraneCrab;

Matlab

The MATLAB code generation is more involved since five different files are generated

CraneCrab_sim.m Basic simulation file. It defines the initial values, start time and stop time and calls the solver.

CraneCrab_der_state.m This file features the calculation of all state derivatives of the form

�̇� = 𝑓 (𝑡, 𝑦)

CraneCrab_inputs.m This function is called from CraneCrab_der_state.m. Here one can implement its own algo-rithms to generate inputs to the system.

CraneCrab_sensors.m PyMbs separates the calculation of sensor values from the state derivatives. The functionwithin CraneCrab_sensors returns a struct containing all sensor values if passed a state vector, i.e.

𝑆 = 𝑔 (𝑡, 𝑦)

CraneCrab_visual.m This file can be used to visualise the system according to the description in the PyMbs modeldescription. It features a function that takes the result from the MATLAB Solvers, i.e. a vector T containing all timevalues and a matrix Y where each row is a state vector. The column corresponds to the time value in T. There is thirdparameter fak which can be used to slow the visualisation down if chosen greater than one.

2.3. A First Example 11

Page 16: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

12 Chapter 2. Getting Started

Page 17: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

CHAPTER 3

Command Reference

3.1 General

3.1.1 PyMbs.Input

PyMbs.Input.MbsSystem provides the user interface for PyMbs.

The task of setting up a multibody system is divided into six parts, to which the corresponding functions are givenbelow.

1. Initialisation

• PyMbs.Input.MbsSystem

• PyMbs.Input.MbsSystem.addParam()

• PyMbs.Input.MbsSystem.addInput()

• PyMbs.Input.MbsSystem.setGravity()

2. Create Bodies and Coordinate Systems, i.e. Frames or Connectors

• PyMbs.Input.MbsSystem.addBody()

• PyMbs.Input.MbsSystem.addFrame()

3. Connect Bodies

• PyMbs.Input.MbsSystem.addJoint()

• PyMbs.Input.MbsSystem.addConstraint()

• PyMbs.Input.MbsSystem.addLoop

4. Add Load Elements, Sensors, Expressions and Controllers

• PyMbs.Input.MbsSystem.addLoad

• PyMbs.Input.MbsSystem.addSensor

• PyMbs.Input.MbsSystem.addExpression()

• PyMbs.Input.MbsSystem.addController()

5. Add Visualisation

• PyMbs.Input.MbsSystem.addVisualisation

6. Calculate Equations of Motion and Generate Code

13

Page 18: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

• PyMbs.Input.MbsSystem.genEquations

• PyMbs.Input.MbsSystem.genCode

• PyMbs.Input.MbsSystem.show()

• PyMbs.Input.MbsSystem.simulate()

In the following the members of the module PyMbs.Input are explained in more detail.

PyMbs.Input.MbsSystem

class PyMbs.Input.MbsSystem(gravity_vect=[0, 0, -1], name=’world’)The “world”, which is a kind of body, manages (mainly collects) all these Elements: Bodies, joints, loads, loops,sensors, constraints and expressions. It gives access to the transformation module which is the user interface tothe functionality of PyMbs.

addBody(mass, cg=<MagicMock name=’mock.CZeros()’ id=‘139725406484304’>, iner-tia=<MagicMock name=’mock.CZeros()’ id=‘139725406484304’>, name=None)

With addBody you can insert a rigid body to your multibody system.

TODO: Mentioning of body fixed frame.

Parameters

•name (String.) – Name of the body.

•mass (float/int or PyMbs.Symbolics.Symbol as returned byPyMbs.Input.MbsSystem.addParam()) – Mass of the body in kg.

•cg (3x1 Vector (PyMbs.Symbolics.Matrix or list of float/int).) – Vector, describingthe position of the Centre of Gravity with respect to the body fixed frame.

•inertia (You can either specify a matrix (which must be symmetric) or pass a 6x1vector having the elements [𝐼𝑥𝑥, 𝐼𝑥𝑦 , 𝐼𝑦𝑦 , 𝐼𝑥𝑧 , 𝐼𝑦𝑧 , 𝐼𝑧𝑧]) – Tensor of inertia at the centreof gravity for this body written with respect to the body fixed frame.

ReturnsReference to the generated Body object

Return typePyMbs.Input.Body

Note: A newly generated body needs to be connected to other bodies via a joint.(PyMbs.Input.MbsSystem.addJoint())

addConstraint(CS1, CS2, transLock=[0, 0, 0], rotLock=[0, 0, 0], name=None)One way of closing kinematic loops is through the use constraints. This will introduce constraint forces atboth coordinate systems as well as a set of constraint equations inhibiting certain relative movements whichare specified by transLock and rotLock. This will ultimately lead to formulation as a DAE (DifferentialAlgebraic Equations).

Parameters

•name (String.) – Name of the constraint.

•CS1 (MbsSystem, Body or Coordinate System.) – Parent coordinate systemon the parent body.

•CS2 (MbsSystem, Body or Coordinate System.) – Child coordinate systemon the child body.

14 Chapter 3. Command Reference

Page 19: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

•transLock – Vector [x,y,z] that defines which relative translations are forbidden. Use 0to allow relative motion along the corresponding axis and 1 to inhibit it.

•rotLock – Vector [x,y,z] that defines which relative rotations are forbidden. Use 0 toallow relative motion around the corresponding axis and 1 to inhibit it.

addContactSensorsLoads(name, CS_C)Add all sensors and force elements needed for a contact: * Position * Orientation * Velocity * AngularVelocity * CmpForce with 3x1 vector input * CmpTorque with 3x1 vector input

Parameters

•name – Name of this sensors (using r_, T_, v_, om_ as prefixes)

•CS_C (Body or Coordinate System) – Contact-Frame

addController(symbol_str, controlfunc, shape=None, name=None)Add a controller to the system. This will call the supplied controlfunc function and store its return value,so that it can be used later, e.g. as a load. Because this will execute any valid python function, this is notavailable for exporting to other languages.

Parameters

•name (String.) – Name of the controller.

•symbol_str (String.) – Symbol that shall be used for the controller.

•controlfunc (function) – Python function taking the time and current state, e.g.myfunction(t, y, sensors). Return value can be used e.g. as load.

•shape (Tuple of two numbers (int/float).) – Optional parameter, defin-ing the shape of the controller. Use (m,n) if it is a m x n Matrix. By default (1,1), i.e. ascalar input is assumed.

ReturnsSymbol representing the controller, which may consequently be used in expressions(PyMbs.Input.MbsSystem.addExpression()) and loads (ref:’Loads’).

Return typePyMbs.Symbolics.Symbol

addExpression(symbol_str, exp, name=None, category=64, positive=False, negative=False, lim-its=None)

Add an expression to the system of equations. Expressions allow the user to include calculations of, say,forces from sensors and inputs, or to define own sensors. All symbols known to PyMbs may be used insuch an expression.

Parameters

•name (String.) – Name of the expression.

•symbol (String.) – Symbol that shall be used for the parameter.

•exp (PyMbs.Symbolics.Basic) – Term to calculate the expression, likec*x[0]+d*x[1]

•category ((List of) Strings.) – (Optional) Each expression may be cate-gorised. Use VarKind.Sensor, to let PyMbs recognise it as a sensor, for example.

•positive (Boolean.) – (Optional) Let PyMbs.Symbolics assume that it is positive,which makes it easier to simplify.

ReturnsSymbol of the expression.

Return typePyMbs.Symbolics.Symbol

addFlexibleBody(filepath, name=None)With addFlexibleBody you can insert a flexible body to your multibody system.

3.1. General 15

Page 20: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Parameters

•name (String.) – Name of the body.

•mass (float/int or PyMbs.Symbolics.Symbol as returned byPyMbs.Input.MbsSystem.addParam()) – Mass of the body in kg.

•cg (3x1 Vector (PyMbs.Symbolics.Matrix or list of float/int).) – Vector, describingthe position of the Centre of Gravity with respect to the body fixed frame.

•inertia (You can either specify a matrix (which must be symmetric) or pass a 6x1vector having the elements [𝐼𝑥𝑥, 𝐼𝑥𝑦 , 𝐼𝑦𝑦 , 𝐼𝑥𝑧 , 𝐼𝑦𝑧 , 𝐼𝑧𝑧]) – Tensor of inertia at the centreof gravity for this body written with respect to the body fixed frame.

ReturnsReference to the generated Body object

Return typePyMbs.Input.Body

Note: A newly generated body needs to be connected to other bodies via a joint.(PyMbs.Input.MbsSystem.addJoint())

addFrame(name, p=zeros((3, )), R=eye((3, 3)))Add a new Coordinate System (CS) as a Child.

Parameters

•name (String) – Name of CS

•p – Position vector of coordinate origin

•R – Rotation matrix

addGraphicSensors(cs, name=None, category=256)You may use this function to manually add a Position and a Orientation sensor for a Coordinate System.

Parameters

•name (String.) – Name of the visualisation sensors (r_ and T_ are used as prefix forthe position and orientation sensor, respectively)

•cs (MbsSystem, Body, Frame.) – Coordinate System from which the position andorientation shall be measured.

•category (list of Strings.) – May be used to manually override the category(not recommended)

Returnslist of symbols for position and orientation.

Return typelist of PyMbs.Symbolics.Symbol

addHydCylSensorsLoads(name, CS1, CS2)Add all Sensors and Load Elements needed for a hydraulic cylinder: * DistanceSensor (distance andvelocity at which the distance changes) * PtP-Force with scalar input

Parameters

•CS1 (Body or Coordinate System) – Coordinate System at the bottom of a hy-draulic cylinder

•CS2 (Body or Coordinate System) – Coordinate System at the end of the rod

addInput(symbol_str, shape=None, limits=None, name=None)Add an input to the system. It may be used for values that are calculated externally, like tire forces.

16 Chapter 3. Command Reference

Page 21: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Its implementation depends on the format the generated code is exported. Look at the correspondingdocumentation for more information.

Parameters

•name (String.) – Name of the input.

•symbol_str (String.) – Symbol that shall be used for the input.

•shape (Tuple of two numbers (int/float).) – Optional parameter, defin-ing the shape of the input. Use (m,n) if it is a m x n Matrix. By default (1,1), i.e. a scalarinput is assumed.

•limits (List of (int/float), e.g. [-10, 10]) – Limits for the corre-sponding slider in the simulation tab. Default is [-1,1]

ReturnsSymbol representing the input, which may consequently be used in expressions(PyMbs.Input.MbsSystem.addExpression()) and loads (ref:’Loads’).

Return typePyMbs.Symbolics.Symbol

addJoint(CS1, CS2, dofList=None, startVals=None, startVals_d=None, name=None)addJoint introduces a joint linking two bodies together. It is defined using two coordinate systems whichdefine the position on each body. The parent coordinate system (body) should be the body which is closestto the inertial frame (world/MbsSystem). The movements allowed by this joint are defined by supplyinga dofList. It is a list of strings where each element consists of the type: * Translational (T) * Rotational(R) and the axis of the parent coordinate system: * x, y, z. Thus a translational joint along the x-axiswould be abbreviated by ‘Tx’. A rotational joint around the z-axis would be ‘Rz’. By supplying a listof such elementary rotations and translations more complex joints may be defined. A 6dof joint usingcardan-angles, for example, is characterised by dofList = [’Tx’, ‘Ty’, ‘Tz’, ‘Rx’, ‘Ry’, ‘Rz’]. Note thateach elementary movement is carried out consecutively. In addition initial values, both for the position andthe velocity, may be supplied for each elementary movement.

Parameters

•name (String.) – Name of the joint.

•CS1 (MbsSystem, Body or Coordinate System.) – Parent coordinate systemon the parent body.

•CS2 (Body or Coordinate System.) – Child coordinate system on the childbody.

•dofList (List of Strings.) – List of strings describing the allowed elementarymovements. ‘Ty’ stands for translation along the y-axis. ‘Rx’ allows rotations around thex-axis. dofList = [], creates a fixed joint.

•startVals (List of int/float. Dimension must be the same as dofList) – Initial positionfor each elementary movement.

•startVals_d (List of int/float. Dimension must be the same as dofList) – Initial veloc-ity for each elementary movement.

ReturnsReference to the newly generated joint.

Return typePyMbs.Input.Joint

Note: A joint may not be used to close a kinematic loop. This can onlybe achieved by using Loops (Explicit Handling of Kinematic Loops) or Constraints(PyMbs.Input.MbsSystem.addConstraint())

3.1. General 17

Page 22: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

addJointLoad(loadSymb, thejoint, name=None)Adds a load object to the joint. The load is a force or a torqe, depending on the type of the joint

ReturnsNone

addLoad = NoneaddLoad contains a PyMbs.Input.MbsSystem.AddLoad instance, see Loads (Forces and Torques)for the different load types available

>>> world.addLoad.PtPForce(F, body_one, body_two)

addLoop = NoneaddLoop contains a PyMbs.Input.MbsSystem.AddLoop instance, see Kinematic Loops for the dif-ferent loops available

>>> world.addLoop.FourBar(body_one, body_two)

addMotionSystemSensors(CS_D, name=’BWS’)Add all sensors that are needed for the motion platform, i.e. * Position * Orientation * Velocity * AngularVelocity * Acceleration * Angular Acceleration

ParametersCS_D (Body, Coordinate System) – Coordinate System where the driversits

addParam(symbol_str, defaultValue, positive=False, negative=False, name=None)Creates a new parameter. A parameter is considered to be a value which is constant during simulation butmay vary between different simulation runs. The dimension of a parameter is determined by its default-Value. Furthermore, it is possible to supply a positive flag which, when set, allows simplifications like√𝑥2 = 𝑥 , otherwise it would be |𝑥|.

Parameters

•name (String.) – Name of the parameter.

•symbol_str (String.) – Symbol that shall be used for the parameter.

•defaultValue (int/float, list of int/float, symbolic term.) –Value which is used by default. Note that this option defines the dimension of this param-eter. The defaultValue may also be formula consisting of parameters.

•positive (Boolean.) – Will the parameter always be positive, which holds true for amass, for example.

ReturnsSymbol to the parameter.

Return typePyMbs.Symbolics.Symbol

addSensor = NoneaddSensor contains a PyMbs.Input.MbsSystem.AddSensor instance, see Sensors for the differentsensors available

>>> world.addSensors.Acceleration('a', CS1, CS2)

addTyreSensorsLoads(name, CS_C, CS_R)Add all sensors and force elements needed for a tire model: * Position * Orientation * Velocity * AngularVelocity * CmpForce with 3x1 vector input * CmpTorque with 3x1 vector input

Parameters

•name – Name of this sensors (using r_, T_, v_, om_ as prefixes)

•CS_C (Body or Coordinate System) – Carrier-Frame - Wheel centre, attached tothe vehicle (does not rotate with the wheel)

18 Chapter 3. Command Reference

Page 23: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

•CS_R – Rim-Frame - Wheel centre, attached to the wheel (does rotate with the wheel)

addVisualisation = NoneaddVisualisation contains a PyMbs.Input.MbsSystem.AddVisualisation instance, see Visual-isation for the various visualisation options

>>> world.addVisualisation.Box(body, length=1, width=1, height=1)

exportGraphReps(fileName)Create a text file for saving the information / parameters of the graphical representations of the system.Data is stored plain text in a *.cfg file which can be used by other tools.

ParametersfileName (String.) – Path and file name for saving the generated ouput.

genCode = NonegenCode contains a PyMbs.Input.MbsSystem.GenCode instance, see Code generation for all thewriters and options available

>>> world.genCode.Python()

genEquations = NonegenEquations contains a PyMbs.Input.MbsSystem.GenEqns instance, see Equation generation forthe different equation generators and their options

>>> world.genEquations.Recursive()

genMatlabAnimation(modelname, dirname=’.’, **kwargs)Use genMatlabAnimation to generate a MATLAB Animation file which will visualise your graphical ob-jects using the simulation results from the MATLAB script which has been generated using genCode.

Parameters

•modelname (String.) – Name of the model - will be used as filename.

•dirname (String.) – Directory where the MATLAB-Files will be put.

•kwargs (Dictionary.) – Additional Settings may be passed as kwargs: * axislimits= list of six values [Xmin, Xmax, Ymin, Ymax, Zmin, Zmax]

genSarturisXml(modelname, dirname=’.’)This function writes an XML-File for the Simulation Framework SARTURIS (ref:’http://www.sarturis.de’)developed at the institute of mobile machinery at Dresden University. The XML-File includes a sampledefinition of the HDAE-System as well as all graphical nodes for OpenSceneGraph. In order to use thisoutput lxml needs to be installed.

Parameters

•modelname (String.) – Name of the model - will be used as filename.

•dirname (String.) – Directory where the XML-File will be put.

getController()Returns symbol and shape of the controller in a dictionary.

getMotionEquations()liefert eine Liste von symbolischen Ausdrücken aus denen man qdd für gegebene q, qd berechnen kann

getParameters()Returns dictionary with all the parameters (added with addParam) and their values.

getSensorEquations()liefert eine Liste von symbolischen Ausdrücken aus denen man jeden Sensor-Wert für gegebene q, qdWerte berechnen kann

3.1. General 19

Page 24: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

setGravity(value)setGravity may be used to change the value of the gravitational acceleration which is set by default to 9.81.

Parametersvalue (float or integer) – New value of gravitational acceleration

ReturnsNothing

Note: With this function only the value but not the direction of gravity can be changed. Changingdirection can be achieved through the constructor of PyMbs.Input.MbsSystem

setJointRange(joint, minVal, maxVal)Use this function to set the range in which the joint coordinate can be adjusted by the corresponding sliderin the GUI.

Parameters

•joint (Joint-Object) – Reference to joint

•minVal (int/float) – Minimum Value

•maxVal (int/float) – Maximum Value

show(modelname=None, options={}, **kwargs)Produces a GUI (graphical user interface) in which your model will be displayed as long as you providedgraphic objects using PyMbs.Input.MbsSystem.addVisualisation(). Next to the modelthere will be sliders with which you can manipulate each joint coordinate directly and thus test yourassembly.

Note: You must call PyMbs.Input.MbsSystem.genEquations() before you may call show!

Parameters

•modelname (String.) – Name of the model - will be displayed in the title bar.

•options (Dict.) – used to customise some gui features. Example showing the defaultvalues of the keys

>>> options = {'qFlexScaling':20,'qTransRange' :[-3, 3],'qRotRange':[-3.14, 3.14]}

qFlexScaling - a factor to scale the state of a flexible body

qTransRange - 2-list or tuple setting the limits of translational / prismatic joints valuesare interpreted as SI-unit [m]

qRotRange - dito for rotational /revoule joints values are interpreted as SI-unit [rad]

simulate(q0, t, modelname=None, text_output=False)Simulates the motion of your system with the initial conditions given by q0 up to the time t and outputs thecoordinates to a file.

Parameters•q0 (List) – Initial conditions•t (Float) – Length of simulation•modelname (String.) – Name of the model - will be used as output filename•text_output (Boolean) – Set to True for CSV output instead of binary numpy file

20 Chapter 3. Command Reference

Page 25: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

3.2 Kinematic Loops

3.2.1 Loops

class PyMbs.Input.MbsSystem.AddLoop(world)Class that provides functions to create loops

CrankSlider(CS1, CS2, name=None)Close a loop which we call a CrankSlider. It is a planar mechanism consisting of a series of three revoluteand one translational joints. Its best example is the piston in an engine.

Parameters•CS1 (Coordinate System, Body or MbsSystem.) – Reference to parent coordi-nate system / parent frame.

•CS2 (Coordinate System, Body or MbsSystem.) – Reference to child coordinatesystem / child frame.

•name (string) – A name may be assigned to each loop. If no name is given, then a namelike loop_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

ExpJoint(j, exp, name=None)The ExpJoint allows the user to provide an expression for the joint coordinate. Currently, only kinematiccalculations is supported.

Parameters•j (Joint-Object.) – joint.•exp (Expression.) – Expression for joint coordinate•name (string) – A name may be assigned to each loop. If no name is given, then a namelike loop_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

FourBar(CS1, CS2, posture=1, name=None)Handles a classic planar four bar linkage mechanism comprising four revolute joints. The posture parameterspecifies which solution shall be used (crossing beams or not).

Parameters•CS1 (Coordinate System, Body or MbsSystem.) – Reference to parent coordi-nate system / parent frame.

•CS2 (Coordinate System, Body or MbsSystem.) – Reference to child coordinatesystem / child frame.

•posture (int - either 1 or -1) – Specifying the solution which shall be used -most time it means, if beams are crossed

•name (string) – A name may be assigned to each loop. If no name is given, then a namelike loop_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

FourBarTrans(CS1, CS2, posture=1, name=None)The FourBarTrans is an extension to the FourBarLinkage. Whereas the classical four bar linkage consistsof only four revolute joints, the FourBarTrans is extended by a translational joint. This mechanism is oftenfound in wheel loaders.

Parameters•CS1 (Coordinate System, Body or MbsSystem.) – Reference to parent coordi-nate system / parent frame.

•CS2 (Coordinate System, Body or MbsSystem.) – Reference to child coordinatesystem / child frame.

•name (string) – A name may be assigned to each loop. If no name is given, then a namelike loop_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

3.2. Kinematic Loops 21

Page 26: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Hexapod(CS1, CS2, name=None)Close a loop which we call a ThreeBarTrans. It is a planar mechanism consisting of a series of three revoluteand one translational joints. It often occurs in conjunction with hydraulic cylinders.

Parameters•CS1 (Coordinate System, Body or MbsSystem.) – Reference to parent coordi-nate system / parent frame.

•CS2 (Coordinate System, Body or MbsSystem.) – Reference to child coordinatesystem / child frame.

•name (string) – A name may be assigned to each loop. If no name is given, then a namelike loop_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

Hexapod_m_AV(CS1, CS2, name=None)Close a loop which we call a ThreeBarTrans. It is a planar mechanism consisting of a series of three revoluteand one translational joints. It often occurs in conjunction with hydraulic cylinders.

Parameters•CS1 (Coordinate System, Body or MbsSystem.) – Reference to parent coordi-nate system / parent frame.

•CS2 (Coordinate System, Body or MbsSystem.) – Reference to child coordinatesystem / child frame.

•name (string) – A name may be assigned to each loop. If no name is given, then a namelike loop_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

Steering(CS1, CS2, setUpH=1, setUpS=1, name=None)Close a loop which we call Steering. More detailed explanation follows.

Parameters•CS1 (Coordinate System, Body or MbsSystem.) – Reference to parent coordi-nate system / parent frame.

•CS2 (Coordinate System, Body or MbsSystem.) – Reference to child coordinatesystem / child frame.

•setUp – Specifying the solution which shall be used - most time it means, if beams are crossed•name (string) – A name may be assigned to each loop. If no name is given, then a namelike loop_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

ThreeBarTrans(CS1, CS2, name=None)Close a loop which we call a ThreeBarTrans. It is a planar mechanism consisting of a series of three revoluteand one translational joints. It often occurs in conjunction with hydraulic cylinders.

Parameters•CS1 (Coordinate System, Body or MbsSystem.) – Reference to parent coordi-nate system / parent frame.

•CS2 (Coordinate System, Body or MbsSystem.) – Reference to child coordinatesystem / child frame.

•name (string) – A name may be assigned to each loop. If no name is given, then a namelike loop_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

Transmission(j1, j2, ratio=1, name=None)The transmission loop introduces a relation between two joints, such that their joint coordinates q1 and q2are related by the following equation: j1 = ratio * v2; This can either be used to synchronise joints or tocreate a fixed joint by choosing ratio =0.

Parameters•j1 (Joint-Object.) – First joint.•j2 (Joint-Object.) – Second Joint.•ratio (int/float.) – Ratio between two joints.

22 Chapter 3. Command Reference

Page 27: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

•name (string) – A name may be assigned to each loop. If no name is given, then a namelike loop_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

3.3 Loads (Forces and Torques)

In order to model internal as well as external forces and torques, the concept of LoadElements has been introduced. Inthe following all LoadElements are described which are currently available.

3.3.1 Loads

class PyMbs.Input.MbsSystem.AddLoad(world)Class that provides functions to create load elements

CmpForce(symbol, CS1, CS2, name=None, CSref=None)Use addLoad.CmpForce to add a vectorial force, acting between two coordinate systems. The force, speci-fied with respect to the parent or reference frame, acts in positive direction on the parent coordinate system(CS1) and in negative direction on the child coordinate system.

Parameters•CS1 (Coordinate System, Body or MbsSystem.) – Reference to parent coordi-nate system / parent frame.

•CS2 (Coordinate System, Body or MbsSystem.) – Reference to child coordinatesystem / child frame.

•symbol (Expression as returned by addInput, addExpression oraddSensor.) – Symbol representing a three dimensional vector variable whose compo-nents are interpreted as force values in x, y, and z-direction. The direction of x,y and z is givenby the parent frame (CS1) or by the reference frame (CSref).

•CSref (Coordinate System, Body or MbsSystem.) – Reference to reference co-ordinate system / reference frame.

•name (string) – A name may be assigned to each force. If no name is given, then a namelike load_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

ReturnsReference to the generated LoadElementReturn typeLoadElement

CmpTorque(symbol, CS1, CS2, CSref=None, name=None)Use addLoad.CmpTorque to add a vectorial torque, acting between two coordinate systems. The torque,specified with respect to the parent or reference frame, acts in positive direction on the parent coordinatesystem (CS1) and in negative direction on the child coordinate system.

Parameters•CS1 (Coordinate System, Body or MbsSystem.) – Reference to parent coordi-nate system / parent frame.

•CS2 (Coordinate System, Body or MbsSystem.) – Reference to child coordinatesystem / child frame.

•symbol (Expression as returned by addInput, addExpression oraddSensor.) – Symbol representing a three dimensional vector variable whose compo-nents are interpreted as torque values around the x, y, and z-axis. The direction of x,y and z isgiven by the parent frame (CS1) or by the reference frame (CSref).

•CSref (Coordinate System, Body or MbsSystem.) – Reference to reference co-ordinate system / reference frame.

•name (string) – A name may be assigned to each force. If no name is given, then a namelike load_1 is generated automatically. The name is used for code generation only, i.e. the

3.3. Loads (Forces and Torques) 23

Page 28: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

symbols connected with this force will contain the name.ReturnsReference to the generated LoadElementReturn typeLoadElement

Joint(symbol, joint, name=None)Use addLoad.Joint to add a torque, acting on a joint. In case of a translational joint, a force has to besupplied. In case of a rotational joint, the load represents a torque.

Parameters•joint (Joint.) – Reference to joint.•symbol (Expression as returned by addInput, addExpression oraddSensor.) – Symbol representing a scalar. Force or Torque depending on whether it is atranslational or rotational joint.

•name (string) – A name may be assigned to each force. If no name is given, then a namelike load_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

ReturnsReference to the generated LoadElementReturn typeLoadElement

PtPForce(symbol, CS1, CS2, name=None)Use addLoad.PtPForce to add a scalar force, acting between two coordinate systems along a connectingline. A positive force means that the coordinate systems are pushed apart.

Parameters•CS1 (Coordinate System, Body or MbsSystem.) – Reference to parent coordi-nate system / parent frame.

•CS2 (Coordinate System, Body or MbsSystem.) – Reference to child coordinatesystem / child frame.

•symbol (Expression as returned by addInput, addExpression oraddSensor.) – Symbol representing a scalar variable whose value is taken as forcebetween the two coordinate systems.

•name (string) – A name may be assigned to each force. If no name is given, then a namelike load_1 is generated automatically. The name is used for code generation only, i.e. thesymbols connected with this force will contain the name.

ReturnsReference to the generated LoadElementReturn typeLoadElement

3.4 Sensors

3.4.1 Sensors

class PyMbs.Input.MbsSystem.AddSensor(world)Class that provides functions to create sensors

Acceleration(symbol, CS1, CS2, CSref=None, name=None, category=256)The acceleration sensor measures the relative acceleration between CS1 and CS2 with respect to the refer-ence frame specified by CSref. If CSref has been omitted then CS1 is used.

Parameters•CS1 (MbsSystem, Body, Coordinate System.) – Parent Coordinate System.•CS2 (MbsSystem, Body, Coordinate System.) – Child Coordinate System.•CSref (MbsSystem, Body, Coordinate System.) – Reference Frame.•symbol (String.) – Symbol representing a the sensor result.•name (String.) – A name may be assigned to each sensor. If no name is given, then a namelike sensor_1 is generated automatically.

ReturnsSymbol of the sensor

24 Chapter 3. Command Reference

Page 29: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Return typePyMbs.Symbolics.Symbol

AngularAcceleration(symbol, CS1, CS2, CSref=None, name=None, category=256)The AngularAcceleration sensor measures the relative angular acceleration between CS1 and CS2 withrespect to the reference frame specified by CSref. If CSref has been omitted then CS1 is used.

Parameters•CS1 (MbsSystem, Body, Coordinate System.) – Parent Coordinate System.•CS2 (MbsSystem, Body, Coordinate System.) – Child Coordinate System.•CSref (MbsSystem, Body, Coordinate System.) – Reference Frame.•symbol (String.) – Symbol representing a the sensor result.•name (String.) – A name may be assigned to each sensor. If no name is given, then a namelike sensor_1 is generated automatically.

ReturnsSymbol of the sensorReturn typePyMbs.Symbolics.Symbol

AngularVelocity(symbol, CS1, CS2, CSref=None, name=None, category=256)The AngularVelocity sensor measures the relative angular velocity between CS1 and CS2 with respect to thereference frame specified by CSref. If CSref has been omitted then CS1 is used.

Parameters•CS1 (MbsSystem, Body, Coordinate System.) – Parent Coordinate System.•CS2 (MbsSystem, Body, Coordinate System.) – Child Coordinate System.•CSref (MbsSystem, Body, Coordinate System.) – Reference Frame.•symbol (String.) – Symbol representing a the sensor result.•name (String.) – A name may be assigned to each sensor. If no name is given, then a namelike sensor_1 is generated automatically.

ReturnsSymbol of the sensorReturn typePyMbs.Symbolics.Symbol

CenterofMass(symbol_str, Bodies=None, name=None, category=256)The CenterofMass sensor measures the total mass and the position of it. If body is the world (MbsSystem)then the sensor measures the total mass of the system.

Parameters•Bodies – Bodies of which the total mass shall be measured. Pass the world/ MbsSystem ifthe total mass of all bodies shall be measured.

•symbol (String.) – Symbol representing a the sensor result.ReturnsSymbol of the sensorReturn typePyMbs.Symbolics.Symbol

ConstraintForce(symbol, joint, name=None, category=256)The Joint sensor returns the joint’s constraint force

Parameters•joint (Joint-Object.) – Joint of which the constraint force shall be measured.•symbol (String.) – Symbol representing a the sensor result.

ReturnsSymbol of the sensorReturn typePyMbs.Symbolics.Symbol

ConstraintTorque(symbol, joint, name=None, category=256)The Joint sensor returns the joint’s constraint torque

Parameters•joint (Joint-Object.) – Joint of which the constraint torque shall be measured.•symbol (String.) – Symbol representing a the sensor result.

ReturnsSymbol of the sensorReturn typePyMbs.Symbolics.Symbol

Distance(symbol, CS1, CS2, name=None, category=256)A distance sensor measures the scalar distance (always positive) between two coordinate systems. Further-more it measures the velocity, i.e. the rate at which the distance changes with time. If you want to measure

3.4. Sensors 25

Page 30: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

the distance vector have a look at the PositionSensor (ref:’Position’).Parameters

•CS1 (MbsSystem, Body, Coordinate System.) – Parent Coordinate System.•CS2 (MbsSystem, Body, Coordinate System.) – Child Coordinate System.•symbol (String.) – Symbol representing a the sensor result.•name (String.) – A name may be assigned to each sensor. If no name is given, then a namelike sensor_1 is generated automatically.

ReturnsSymbol of the sensorReturn typePyMbs.Symbolics.Symbol

Energy(symbol_str, body, name=None, category=256)The Energy sensor measures the potential and the kinetic energy of body. If body is the world (MbsSystem)then the sensor measures the sum of the energies of each body in the system.

Parameters•body (MbsSystem, Body, Coordinate System) – Body of which the energy shallbe measured. Pass the world/ MbsSystem if the energy of all bodies shall be measured.

•symbol (String.) – Symbol representing a the sensor result.ReturnsSymbol of the sensorReturn typePyMbs.Symbolics.Symbol

Joint(symbol, joint, name=None, category=256)The Joint sensor returns the joint coordinate as well as the joint velocity.

Parameters•joint (Joint-Object.) – Joint of which the coordinate shall be extracted.•symbol (String.) – Symbol representing a the sensor result.

ReturnsSymbol of the sensorReturn typePyMbs.Symbolics.Symbol

Orientation(symbol, CS1, CS2, name=None, category=256)The Orientation sensor measures the relative orientation between CS1 and CS2, described by a transforma-tion matrix.

Parameters•CS1 (MbsSystem, Body, Coordinate System.) – Parent Coordinate System.•CS2 (MbsSystem, Body, Coordinate System.) – Child Coordinate System.•symbol (String.) – Symbol representing a the sensor result.•name (String.) – A name may be assigned to each sensor. If no name is given, then a namelike sensor_1 is generated automatically.

ReturnsSymbol of the sensorReturn typePyMbs.Symbolics.Symbol

Position(symbol, CS1, CS2, CSref=None, name=None, category=256)A position sensor measuring the distance vector between CS1 and CS2 with the arrow pointing to CS2. Thevector is written with respect to the reference frame specified by CSref. If CSref has been omitted then CS1is used.

Parameters•CS1 (MbsSystem, Body, Coordinate System.) – Parent Coordinate System.•CS2 (MbsSystem, Body, Coordinate System.) – Child Coordinate System.•CSref (MbsSystem, Body, Coordinate System.) – Reference Frame.•symbol (String.) – Symbol representing a the sensor result.•name (String.) – A name may be assigned to each sensor. If no name is given, then a namelike sensor_1 is generated automatically.

ReturnsSymbol of the sensorReturn typePyMbs.Symbolics.Symbol

Velocity(symbol, CS1, CS2, CSref=None, name=None, category=256)The velocity sensor measures the relative velocity between CS1 and CS2 with respect to the reference frame

26 Chapter 3. Command Reference

Page 31: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

specified by CSref. If CSref has been omitted then CS1 is used.Parameters

•CS1 (MbsSystem, Body, Coordinate System.) – Parent Coordinate System.•CS2 (MbsSystem, Body, Coordinate System.) – Child Coordinate System.•CSref (MbsSystem, Body, Coordinate System.) – Reference Frame.•symbol (String.) – Symbol representing a the sensor result.•name (String.) – A name may be assigned to each sensor. If no name is given, then a namelike sensor_1 is generated automatically.

ReturnsSymbol of the sensorReturn typePyMbs.Symbolics.Symbol

3.5 Visualisation

3.5.1 Visualisation

class PyMbs.Input.MbsSystem.AddVisualisation(world)Class that provides functions to create visual shapes

Arrow(cs, size=1, name=None)Add a arrow graphical representation to a coordinate system given by cs.

Parameters•cs (MbsSystem, Body, Coordinate System.) – Coordinate System to which theGraphical Object shall be attached.

•radius (int/float.) – Radius of the circular groundplane.•length – Length of the Arrow.•name (String.) – A name may be assigned to each visualistion. If no name is given, thena name like visual_1 is generated automatically. The name is used for the sensor and thus forcode generation.

Box(cs, length=1, width=1, height=1, name=None, color=None)Add a line object which whose dimensions are called: * x - length * y - width * z - height The origin of thisgraphical representation lies in the centre of the objet.

Parameters•cs (MbsSystem, Body, Coordinate System.) – Coordinate System to which theGraphical Object shall be attached.

•length (int/float.) – Length (x-dimension) of the box.•width (int/float.) – Width (y-dimension) of the box.•height (int/float.) – Height (z-dimension) of the box.•name (String.) – A name may be assigned to each visualistion. If no name is given, thena name like visual_1 is generated automatically. The name is used for the sensor and thus forcode generation.

•color (List, Tuple, VTK Color) – Apply a specific color to a visualisation. You canuse either an RGB list, e.g. color=[0.7, 0.3, 0.1], or any VTK color (from vtk.util.colors).

Cylinder(cs, radius=1, height=1, res=20, name=None, color=None)Add a cylindrical graphical representation to a coordinate system given by cs. Its groundplane forms a circlewith the radius given by radius and lies in the x-y-plane. The origin lies directly in the centre, at half of theheight.

Parameters•cs (MbsSystem, Body, Coordinate System.) – Coordinate System to which theGraphical Object shall be attached.

•radius (int/float.) – Radius of the circular groundplane.•height (int/float.) – Height of the cylinder.

3.5. Visualisation 27

Page 32: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

•name (String.) – A name may be assigned to each visualistion. If no name is given, thena name like visual_1 is generated automatically. The name is used for the sensor and thus forcode generation.

•color (List, Tuple, VTK Color) – Apply a specific color to a visualisation. You canuse either an RGB list, e.g. color=[0.7, 0.3, 0.1], or any VTK color (from vtk.util.colors).

File(cs, fileName, scale=1, name=None, color=None)Attach a File-Object given by fileName to the Coordinate System given by cs. Since the python visualisationis based on VTK, all file formats that are compatible to VTK are supported. MATLAB Animations, however,only support STL-Files.

Parameters•cs (MbsSystem, Body, Coordinate System.) – Coordinate System to which theGraphical Object shall be attached.

•fileName (String.) – Filename of the graphics file.•scale (int/float.) – Can be used to scale down the Graphic. Use 1000 if the graphicinformation is stored in millimeters, for example.

•name (String.) – A name may be assigned to each visualistion. If no name is given, thena name like visual_1 is generated automatically. The name is used for the sensor and thus forcode generation.

•color (List, Tuple, VTK Color) – Apply a specific color to a visualisation. You canuse either an RGB list, e.g. color=[0.7, 0.3, 0.1], or any VTK color (from vtk.util.colors).

Frame(cs, size=1, name=None)Attaches a graphical representation of a coordinate system. It consists of three lines, each pointing in thedirection of an axis. Use size to vary the length of the lines.The axes can be distinguished by their color:x-axis: red y-axis: yellow z-axis: green

Parameters•cs (MbsSystem, Body, Coordinate System.) – Coordinate System to which theGraphical Object shall be attached.

•size (int/float.) – length of an axis of this coordinate system.•name (String.) – A name may be assigned to each visualistion. If no name is given, thena name like visual_1 is generated automatically. The name is used for the sensor and thus forcode generation.

Line(cs, length=1, name=None, color=None)Add a line object which starts at [0,0,0] and ends at [length,0,0], i.e. spans in x-direction.

Parameters•cs (MbsSystem, Body, Coordinate System.) – Coordinate System to which theGraphical Object shall be attached.

•length (int/float.) – Length of the line.•name (String.) – A name may be assigned to each visualistion. If no name is given, thena name like visual_1 is generated automatically. The name is used for the sensor and thus forcode generation.

•color (List, Tuple, VTK Color) – Apply a specific color to a visualisation. You canuse either an RGB list, e.g. color=[0.7, 0.3, 0.1], or any VTK color (from vtk.util.colors).

Sphere(cs, radius=1, res=50, name=None, color=None)Attaches a sphere with the radius radius to a given coordinate system cs. The origin lies directly in themiddle of the sphere.

Parameters•cs (MbsSystem, Body, Coordinate System.) – Coordinate System to which theGraphical Object shall be attached.

•radius (int/float.) – Radius of the sphere.•name (String.) – A name may be assigned to each visualistion. If no name is given, thena name like visual_1 is generated automatically. The name is used for the sensor and thus for

28 Chapter 3. Command Reference

Page 33: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

code generation.•color (List, Tuple, VTK Color) – Apply a specific color to a visualisation. You canuse either an RGB list, e.g. color=[0.7, 0.3, 0.1], or any VTK color (from vtk.util.colors).

flexible_Body(cs, flex_Body, name=None)Add a flexible body graphical representation to a coordinate system given by cs.

Parameters•cs (MbsSystem, Body, Coordinate System.) – Coordinate System to which theGraphical Object shall be attached.

•pos_nodes (tupel?) – position of the node frames (bodyframe/inertial?)•name (String.) – A name may be assigned to each visualistion. If no name is given, thena name like visual_1 is generated automatically. The name is used for the sensor and thus forcode generation.

3.6 Equation generation

class PyMbs.Input.MbsSystem.GenEqns(world)Class that provides interface to equation generation

Explicit(diff=0, kinematicsOnly=False, simplify=False, graphOptimizations=False)This function derives equations of motion for the given system. It should be run after the system has beenassembled, i.e. all bodies, joints, load elements and sensors are defined.

The explicit scheme is only recommended for small systems with up to three degree of freedoms. If themechanism is planar, then it might be suitable for up to five degrees of freedom.

Parameters•diff (list of int) – With diff the user can specify how often the algebraic constraints(on position level) shall be differentiated with respect to time (if there are any kinematic loopspresent). Valid values are: * 0 - position level * 1 - velocity level * 2 - acceleration level If youneed the constraints on more than one level, than a list of may also be supplied, i.e. [0, 1, 2]

•kinematicsOnly (Boolean) – If set to true, no equations for forces and accelarations aregenerated, only position and velocities are available

•simplify (Boolean) – If set to true, simplification of expression is performed which canbe very time consuming. Especially the simplifications done by PyMbs.Symbolics are not veryefficient.

•graphOptimizations – If set to False, Graph simplification is skipped.

OrderN(diff=0, kinematicsOnly=False, simplify=False, graphOptimizations=True)This function derives equations of motion for the given system. It should be run after the system has beenassembled, i.e. all bodies, joints, load elements and sensors are defined.

The OrderN scheme is recommended for large systems with more than twenty degree of freedoms.Parameters

•diff (list of int) – With diff the user can specify how often the algebraic constraints(on position level) shall be differentiated with respect to time (if there are any kinematic loopspresent). Valid values are: * 0 - position level * 1 - velocity level * 2 - acceleration level If youneed the constraints on more than one level, than a list of may also be supplied, i.e. [0, 1, 2]

•kinematicsOnly (Boolean) – If set to true, no equations for forces and accelarations aregenerated, only position and velocities are available

•simplify (Boolean) – If set to true, simplification of expression is performed which canbe very time consuming. Especially the simplifications done by PyMbs.Symbolics are not veryefficient.

•graphOptimizations – If set to False, Graph simplification is skipped.

3.6. Equation generation 29

Page 34: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Recursive(diff=0, kinematicsOnly=False, simplify=False, graphOptimizations=True)This function derives equations of motion for the given system. It should be run after the system has beenassembled, i.e. all bodies, joints, load elements and sensors are defined.

The recursive scheme is recommended for medium systems with more than three degree of freedoms.Parameters

•diff (list of int) – With diff the user can specify how often the algebraic constraints(on position level) shall be differentiated with respect to time (if there are any kinematic loopspresent). Valid values are: * 0 - position level * 1 - velocity level * 2 - acceleration level If youneed the constraints on more than one level, than a list of may also be supplied, i.e. [0, 1, 2]

•kinematicsOnly (Boolean) – If set to true, no equations for forces and accelarations aregenerated, only position and velocities are available

•simplify (Boolean) – If set to true, simplification of expression is performed which canbe very time consuming. Especially the simplifications done by PyMbs.Symbolics are not veryefficient.

•graphOptimizations – If set to False, Graph simplification is skipped.

3.7 Code generation

class PyMbs.Input.MbsSystem.GenCode(world)Class that provides functions to write source code of the obtained equations of motion for various languages

C(modelname, dirname=’.’, **kwargs)After the equations of motion have been generated, the simulation code for C can be generated with thisfunction.

Parameters•modelname (String) – Name of the model - will be used as a filename at least•dirname (String.) – Directory where the model shall be exported to•pymbs_wrapper (Bool) – Set to True to write python wrapper as well•sfunction (Bool) – Generate s-function for Matlab-Simulink•include_visual (Bool) – Generate code for visualisation

FMU(modelname, dirname=’.’, compile=True, **kwargs)Deprecated since version 0.2.2: Currently the FMU-Writer is not working. All the code is still in place, butwe are unable to maintain it at the moment. If this functionality would be useful to you, and you are willingto improve/maintain it, feel free to get in touch.

After the equations of motion have been generated, the simulation code for FMU can be generated with thisfunction.

Parameters•modelname (String) – Name of the model - will be used as a filename at least•dirname (String.) – Directory where the model shall be exported to•compile (Boolean.) – If a binary of the model shall be created. Compillation is done bygcc which has to be in PATH

•util_folder_path (String) – Path to FMU templates and includes

Fortran90(modelname, dirname=’.’, **kwargs)After the equations of motion have been generated, the simulation code for Fortran can be generated withthis function.

Parameters•modelname (String) – Name of the model - will be used as a filename at least•dirname (String.) – Directory where the model shall be exported to•pymbs_wrapper (Bool) – Export python wrapper as well

30 Chapter 3. Command Reference

Page 35: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Matlab(modelname, dirname=’.’, symbolic_mode=False)After the equations of motion have been generated, the simulation code for Matlab can be generated withthis function.

Parameters•modelname (String) – Name of the model - will be used as a filename at least•dirname (String.) – Directory where the model shall be exported to•symbolic_mode (Boolean.) – If symbolic_mode is True, code for the symbolic toolboxwill be written

Modelica(modelname, dirname=’.’, inputsAsInputs=True, genVisualFile=None, **kwargs)After the equations of motion have been generated, the simulation code for Modelica can be generated withthis function.

Parameters•modelname (String) – Name of the model - will be used as a filename at least•dirname (String) – Directory where the model shall be exported to•genVisualFile (String) – Name of the Visual File; if no name is supplied, no visualfile is generated

•inputsAsInputs (Bool) – Missing•package (String) – Package name

Python(modelname, dirname=’.’)After the equations of motion have been generated, the simulation code for Python can be generated withthis function.

Parameters•modelname (String) – Name of the model - will be used as a filename at least•dirname (String.) – Directory where the model shall be exported to

3.8 Interaction with PyTrajectory

PyTrajectory is a Python library for the determination of the feed forward control to achieve a transition betweendesired states of a nonlinear control system.

It is being developed at Dresden University of Technology at the Institute for Control Theory.

The aim of the following method is to provide a connection between the capabilities of PyMbs for creating andvisualising a multibody system and those of PyTrajectory for determining a feed forward control.

#!/usr/bin/python2

####################################################################### This example demonstrates how to get motion equations of a# multibody system created with PyMbs and use them to determine a# feed forward control with PyTrajectoy

# PyMbs importsfrom PyMbs.Input import *from PyMbs.utils.sympyexport import sympymbs

# PyTrajectory importsfrom pytrajectory import Trajectory

# This is now part of PyMbs#from pytrajectory.utilities import sympymbs

# additional imports

3.8. Interaction with PyTrajectory 31

Page 36: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

import numpy as np

# The following import requires some explanation:## To add a controller to the multibody system (in this example a force# that acts on the crab) the user has to provide a python module# (here: dummy_controller) that contains a function (here: controlForce)# that returns the state of the desired controller depending on the# current time.## Since we want to determine this function it has to be just a dummy# procedure by now, that will be replaced with the solution found# (hopefully) by PyTrajectory.## For more information have a look at the file: dummy_controller.pyimport dummy_controllerfrom dummy_controller import controlForce

####################################################################### PyMbs######################################################################

# Here we build a multibody system that is basically a simple pendulum.

# Create MbsSystemworld=MbsSystem([0,0,-1])

m1 = world.addParam('m1', 54)m2 = world.addParam('m2', 2.65 )m3 = world.addParam('m3', 38 )

# Add bodiescrab = world.addBody(mass=m1, cg=[0.24,0.02,0.21], inertia=diag([2.11,5.87,5.61]))hook = world.addBody(mass=m2, cg=[0,0,0.08], inertia=diag([0.01,0.01,0.1]))load = world.addBody(mass=m3, cg=[0,0,-1.28], inertia=diag([2.28,2.28,0.15]))

# Join bodiesworld.addJoint(world, crab, 'Tx', startVals=1)world.addJoint(crab, hook)world.addJoint(hook, load, 'Ry')

# Add visualization of the system

filetyp = "stl_files/%s_01.stl"world.addVisualisation.File(world, filetyp%'Traeger', name='Traeger')world.addVisualisation.File(crab, filetyp%'Laufkatze', name='Laufkatze')world.addVisualisation.File(hook, filetyp%'Haken', name='Haken' )world.addVisualisation.File(load, filetyp%'Last', name='Last' )

# Add a control force# -> by now this is just a dummy procedure that is necessary for PyMbs# to generate the motion equations (see: dummy_controller.py)F = world.addController('F', controlForce, shape=(3, ))world.addLoad.CmpForce(F, crab, world, name='DrivingForce')

# Determine motion equationsworld.genEquations.Recursive()

32 Chapter 3. Command Reference

Page 37: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

####################################################################### PyTrajectory######################################################################

# Get a function of the motion equations of the multibody system# that can be used with PyTrajectoryf = sympymbs(world)

# Now we set the desired boundary values for the swing up of the# penduluma, b = 0.0, 2.0xa = [0.0, 0.0, 0.0, 0.0]xb = [0.0, np.pi, 0.0 ,0.0]

uab = [0.0, 0.0]

# create PyTrajectory objectT = Trajectory(f, a=a, b=b, xa=xa, xb=xb, g=uab)

# change some method parametersT.setParam('kx', 5)T.setParam('use_chains', False)T.setParam('eps', 0.05)T.setParam('ierr', 5e-2)

# run iterationxt, ut = T.startIteration()

# the following definition is necessary because the determined control# function u(t) is just valid for t in (a,b)def u_fnc(t):

if a <= t <= b:return ut(t)

else:return ut(b)

# now we replace the dummy procedure with the solution from PyTrajectorydummy_controller.container[0]= u_fnc

# and visualise the systemworld.show('Laufkatze')

3.8. Interaction with PyTrajectory 33

Page 38: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

34 Chapter 3. Command Reference

Page 39: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

CHAPTER 4

Background

This chapter is supposed to provide the reader with a brief overview of the mathematical and physical background.

4.1 Deriving Equations of Motion

4.1.1 Format

PyMbs translates the description based on bodies, joints and load elements into the following system of differentialequations describing the equations of motion:

𝑀𝑞𝑑 + ℎ = 𝑓 + 𝑊𝜆

𝑞 = 𝑞𝑑

Φ(𝑞) = 0

(4.1)

where 𝑞 is vector of the generalised positions; 𝑞𝑑 is the vector of generalised velocities; 𝜆 is the vector of constraintforces; 𝑀 is the generalised Mass Matrix; ℎ is a vector containing all centrifugal and Coriolis forces; 𝑓 comprises allinternal and external loads; Φ (𝑞) describes all holonomic constraints.

Currently, PyMbs features an explicit and a recursive scheme to derive the equations of motion. The explicit schemeis best used for small systems with up to four degrees of freedom. It obtains expressions for 𝑀 , ℎ, 𝑓 , 𝑃ℎ𝑖 directly.This code is very compact for small systems but the expressions become extremely long for larger systems. For thatreason a recursive scheme has been implemented which exploits the kinematic structure of the system leading to manybut simple equations.

4.1.2 Explicit Scheme

The explicit scheme is based on the Newton-Euler-Algorithm and the symbolic calculation capabilities of PyMbsthrough the use of sympy. Since an exhaustive presentation would go far beyond the scope of this document, only theessential highlights will be discussed.

Given a rigid body 𝑖 which is able to move freely in a three dimensional space, following equations describe thetrajectory of its centre of gravity.

35

Page 40: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

[︂𝑀1,𝑖 0

0 𝑀2,𝑖

]︂⏟ ⏞

𝑀𝑖

[︂�̇�𝑖�̇�𝑖

]︂+

[︂0

�̃�𝑖𝑀2,𝑖𝜔𝑖

]︂⏟ ⏞

ℎ𝑖

=

[︂𝑓𝑒,𝑖𝑚𝑒,𝑖

]︂⏟ ⏞

𝑓𝑖

𝑣𝑖 = �̇�𝑖

𝜔𝑖 = 𝐻𝑖�̇�𝑖

(4.2)

Where 𝑟𝑖 and 𝑣𝑖 describe the position and the velocity of the centre of gravity with respect to the inertial frame; 𝜔𝑖

represents its angular velocity with respect to a body-fixed frame; 𝛼𝑖 describes the bodies orientation using CardanAngles, for example. 𝑀1,𝑖 and 𝑀2,𝑖 are sub matrices of the block diagonal matrix 𝑀𝑖, given by

𝑀1,𝑖 =

⎡⎣ 𝑚𝑖 0 00 𝑚𝑖 00 0 𝑚𝑖

⎤⎦𝑀2,𝑖 = 𝐼𝑖 =

⎡⎣ 𝐼𝑥𝑥,𝑖 𝐼𝑥𝑦,𝑖 𝐼𝑥𝑧,𝑖𝐼𝑥𝑦,𝑖 𝐼𝑦𝑦,𝑖 𝐼𝑦𝑧,𝑖𝐼𝑥𝑧,𝑖 𝐼𝑦𝑧,𝑖 𝐼𝑧𝑧,𝑖

⎤⎦with 𝑚𝑖 being the mass and 𝐼𝑖 being the symmetric tensor of inertia. The vector ℎ𝑖 contains centrifugal and Coriolis-forces; 𝑓𝑖 comprises all internal and external forces and torques.

Usually, a single body without any constraints will not be sufficient for a model of a technical system. Multiplebodies, connected by joints or governed by constraints are needed. Based on equation (4.2) one can find a moregeneral description for a system consisting of 𝑁 bodies.

[︂𝑀1 00 𝑀2

]︂⏟ ⏞

𝑀

[︂𝑧𝑑1𝑧𝑑2

]︂+

[︂0

𝑧𝑑2𝑀2𝑧𝑑2

]︂⏟ ⏞

=

[︂𝑓𝑒𝑚𝑒

]︂⏟ ⏞

𝑓

𝑧𝑑1 = �̇�1

𝑧𝑑2 = 𝐻�̇�2

(4.3)

Although equation (4.3) looks very similar to equation (4.2), the definitions of the used symbols does differ

𝑧1 =[︀𝑟𝑇1 𝑟𝑇2 . . . 𝑟𝑇𝑁

]︀𝑇𝑧𝑑2 =

[︀𝜔𝑇1 𝜔𝑇

2 . . . 𝜔𝑇𝑁

]︀𝑇𝑀1 = 𝑏𝑙𝑘𝑑𝑖𝑎𝑔 (𝑀1,1,𝑀1,2, . . . ,𝑀1,𝑁 )

𝑀2, 𝑓𝑒, 𝑚𝑒, 𝛼 and 𝐻 are generalised in a similar way.

Introducing joints between bodies leads to restrictions of their relative movements for which algebraic constraints canbe found

Φ (𝑧1, 𝑧2) = 0.

These constraints are ensured by introducing corresponding constraint forces into the equations of motion actingperpendicular to the direction of allowed displacements. Thus equation (4.3) changes to

36 Chapter 4. Background

Page 41: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

𝑀

[︂𝑧𝑑1𝑧𝑑2

]︂+ ℎ = 𝑓 +

(︂𝜕Φ

𝜕𝑧

)︂𝑇

𝜆

𝑧𝑑1 = 𝑧1

𝑧𝑑2 = 𝐻𝑧2

Φ = 0

(4.4)

with

𝑧 =[︀𝑧𝑇1 𝑧𝑇2

]︀𝑇where 𝜆 are the Lagrange Multipliers representing a vector of generalised forces.

In many applications, a set of minimal coordinates 𝑞 can be found. They can be characterised by three essentialproperties

• There exist some functions 𝐹1 and 𝐹2 such that 𝑧1 = 𝐹1 (𝑞) and 𝑧2 = 𝐹2 (𝑞)

• All elements of 𝑞 are independent, i.e. they form a basis

• All constraints are satisfied by the 𝑞, i.e. Φ (𝑞) = 0 ∀𝑞

If 𝑞 exists, the following relations hold for 𝑧1, 𝑧𝑑1 and its derivatives

𝑧1 = 𝐹1 (𝑞)

𝑧𝑑1 = �̇�1

=𝜕𝐹1

𝜕𝑞𝑞 = 𝐽𝑇 𝑞𝑑

𝑧𝑑1 = 𝐽𝑇 𝑞𝑑 + 𝐽𝑇 𝑞𝑑

(4.5)

and for 𝑧2, 𝑧𝑑2 and its derivatives

𝑧2 = 𝐹2 (𝑞)

𝑧𝑑2 = 𝐻�̇�2

= 𝐻𝜕𝐹2

𝜕𝑞𝑞

= 𝐽𝑅𝑞𝑑

𝑧𝑑2 = 𝐽𝑅𝑞𝑑 + 𝐽𝑅𝑞𝑑

(4.6)

Substituting 𝑧𝑑1 and 𝑧𝑑2 in equation (4.4) by the newly found relations, gives

𝑀

[︂𝐽𝑇𝐽𝑅

]︂⏟ ⏞

𝐽

𝑞𝑑 + 𝑀

[︂𝐽𝑇𝐽𝑅

]︂𝑞𝑑 + ℎ = 𝑓 +

(︂𝜕Φ

𝜕𝑧

)︂𝑇

𝜆(4.7)

Multiplication by 𝐽𝑇 from the left transforms the equation into the space of the minimal coordinates, eliminating allinfluences of constraint forces. This is due to the fact that no work is performed by constraint forces since they alwaysact perpendicular to the allowed displacements. Thus equation (4.7) becomes

4.1. Deriving Equations of Motion 37

Page 42: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

(︀𝐽𝑇𝑀𝐽

)︀⏟ ⏞ 𝑀𝑟𝑒𝑑

𝑞𝑑 + 𝐽𝑇(︁𝑀𝐽𝑞 + ℎ

)︁⏟ ⏞

ℎ𝑟𝑒𝑑

= 𝐽𝑇 𝑓⏟ ⏞ 𝑓𝑟𝑒𝑑

(4.8)

which can be written using the newly introduced variables

𝑀𝑟𝑒𝑑𝑞𝑑 + ℎ𝑟𝑒𝑑 (𝑞, 𝑞𝑑) = 𝑓𝑟𝑒𝑑 (𝑞, 𝑞𝑑) (4.9)

which corresponds to the general equation of motion for multibody systems (4.1).

4.1.3 Recursive Scheme

Since the explicit scheme is only suitable for small multibody systems an explicit scheme has been implemented. Thishas been done according to [FS] where a detailed explanation is given. Therefore only the implemented equations willbe given here. For each body 𝑖 following information must be provided

• Mass: 𝑚𝑖

• Inertia: 𝐼𝑖

• Position of Centre of Gravity: 𝑙𝑖

• Distance to all child bodies ℎ= 𝑝𝑧ℎ𝑖

The underlying assumption is that every joint has exactly one degree of freedom. More complex joints can be obtainedthrough a combination of such simple joints. In general each joint 𝑖 belonging to the body 𝑖 has two parameters:

• Axis of Translation: Ψ𝑖

• Axis of Rotation: Φ𝑖

The equations are generated in three steps. First there is a forward loop, where all positions and velocities of eachbody is obtained. Below you find all equations (taken from [FS]) with 𝑖 denoting the current body and ℎ denoting itsparent body. The index 𝑘 runs over all ancestor bodies.

𝜔𝑖 = 𝜔ℎ + 𝑞𝑑𝑖Φ𝑖

�̇�𝐶𝑖 = �̇�𝑐

ℎ + �̃�𝑖Φ𝑖𝑞𝑑𝑖

𝛽𝐶𝑖 = �̃�𝑖�̃�𝑖 + ˜̇𝜔𝐶

𝑖

𝛼𝐶𝑖 = 𝛼𝐶

ℎ + 𝛽𝐶ℎ 𝑝𝑧ℎ𝑖 + 2�̃�𝑖Ψ𝑖𝑞𝑑𝑖

𝑂𝑀𝑖,𝑘 = 𝑂𝑀

ℎ,𝑘 + 𝛿𝑘,𝑖Ψ𝑖

𝐴𝑀𝑖,𝑘 = 𝐴𝑀

ℎ,𝑘 + �̃�𝑀ℎ,𝑘𝑝

𝑧ℎ,𝑖 + 𝛿𝑘,𝑖Ψ𝑖

All values are initialised with 0 except for 𝛼𝐶0 = −𝑔 with 𝑔 denoting the gravity vector.

Second there is a backward loop in which all joint forces are calculated, with 𝑟 denoting all direct successors (childbodies) of the body 𝑖.

38 Chapter 4. Background

Page 43: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

𝐺𝐶𝑖 = 𝑚𝑖

(︀𝛼𝐶𝑖 + 𝛽𝐶

𝑖 𝑙𝑖)︀− 𝐹𝑒𝑥𝑡,𝑖

𝐹𝐶𝑖 =

∑︁𝐹𝐶𝑟 + 𝐺𝐶

𝑖

𝐿𝐶𝑖 =

∑︁((︀𝐿𝐶𝑟 + 𝑝𝑧𝑖,𝑟𝐹

𝐶𝑟

)︀)

𝐺𝑀𝑖,𝑘 = 𝑚𝑖

(︁𝐴𝑀

𝑖,𝑘 + �̃�𝑀𝑖,𝑘𝑙𝑖

)︁𝐹𝑀𝑖,𝑘 =

∑︁𝐹𝑀𝑟,𝑘 + 𝐺𝑀

𝑖,𝑘

𝐿𝑀𝑖,𝑘 =

∑︁(︀𝐿𝑀𝑟,𝑘 + 𝑝𝑧𝑖,𝑟𝐹

𝑀𝑟,𝑘

)︀+ �̃�𝑖𝐺

𝑀𝑖,𝑘 + 𝐼𝑖𝑂

𝑀𝑖,𝑘

Third, there is another forward loop in which expressions for the generalised accelerations are calculated.

𝐶𝑖 = Ψ𝑖𝐹𝐶𝑖 + Φ𝑖𝐿

𝐶𝑖

𝑀𝑖,𝑘 = 𝑀𝑘,𝑖 = Ψ𝑖𝐹𝑀𝑖,𝑘 + Φ𝑖𝐿

𝑀𝑖,𝑘

The so found 𝐶𝑖 and 𝑀𝑘,𝑖 are the elements of the Mass Matrix 𝑀 and a 𝐶-Vector which satisfies the following relation

𝐶 = 𝑓 + 𝑊𝜆− ℎ

Thus, the form of equation (4.1) has been achieved.

4.2 Explicit Handling of Kinematic Loops

A unique feature of PyMbs is its ability to deal with certain kinematic loops in an explicit manner. This consequentlyleads to a formulation based on minimal coordinates and thereby to explicit ordinary differential equations withoutalgebraic constraints. The underlying concept shall be presented in this section.

Currently, there are four different kinematic loops implemented as shown in Figure Kinematic loops.

Handling kinematic loops is based on the coordinate partitioning method [WH]. Given the vectors of generalisedpositions 𝑞, a set of independent coordinates 𝑢 and a set of dependent coordinates 𝑣 are chosen according to thedefinitions made in the kinematic loops.

𝑞 =

[︂𝑢𝑣

]︂

First, an explicit relation between the dependent coordinates 𝑣 and the independent coordinates 𝑢 must be providedfor each loop.

𝑣 = 𝐻 (𝑢)

Exploiting the (usually much simpler) implicit relation

4.2. Explicit Handling of Kinematic Loops 39

Page 44: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Fig. 4.1: Kinematic loopsLeft to right, top: CrankSlider, FourBarTrans. Bottom: Transmission, FourBar

40 Chapter 4. Background

Page 45: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

ℎ (𝑢, 𝑣)

of the loop 𝑗, corresponding relations on velocity and acceleration level may be derived.

ℎ̇ = ℎ𝑢�̇� + ℎ𝑣 �̇�

�̇� = −ℎ−1𝑣 ℎ𝑢�̇�

= 𝐵𝑣𝑢�̇�

with 𝐵𝑣𝑢 = −ℎ−1𝑣 ℎ𝑢. The same can be achieved for finding a relationship on acceleration level.

ℎ̈ = ℎ𝑢�̈� + ℎ𝑣𝑣 + ℎ̇𝑢�̇� + ℎ̇𝑣 �̇�

𝑣 = −ℎ−1𝑣

(︁ℎ𝑢�̈� + ℎ̇𝑢�̇� + ℎ̇𝑣 �̇�

)︁= 𝐵𝑣𝑢�̈� + 𝑏′

(4.10)

with 𝑏′ = −ℎ−1𝑣

(︁ℎ̇𝑢�̇� + ℎ̇𝑣 �̇�

)︁. Thus, the equations the equations of motion can be reduced even further, so that they

only need to be solved for the set of independent coordinates. Equation (4.1) may be rewritten using equation (4.10).

𝑀

⎛⎜⎜⎜⎝[︂

𝐼𝐵𝑣𝑢

]︂⏟ ⏞

𝐽

�̈� +

[︂0𝑏′

]︂⏟ ⏞

𝑏

⎞⎟⎟⎟⎠ + ℎ = 𝐹 + 𝑊𝜆

𝑀𝐽�̈� + 𝑀𝑏 + ℎ = 𝐹 + 𝑊𝜆

Multiplying this equation with 𝐽𝑇 from the left yields

𝐽𝑇𝑀𝐽�̈� + 𝐽𝑇 (𝑀𝑏 + ℎ) = 𝐽𝑇𝐹 + 𝐽𝑇𝑊⏟ ⏞ =0

𝜆

𝑀𝑟𝑒𝑑�̈� + ℎ𝑟𝑒𝑑 = 𝐹𝑟𝑒𝑑

(4.11)

with 𝑀𝑟𝑒𝑑 = 𝐽𝑇𝑀𝐽𝑇 ; ℎ𝑟𝑒𝑑 = 𝐽𝑇 (𝑀𝑏 + ℎ); 𝐹𝑟𝑒𝑑 = 𝐽𝑇𝐹 . Clearly, equation (4.11) has the form of (4.1) and istherefore compatible.

In order to implement explicit handling for a new kinematic loop, the following information must be provided:

• partitioning of joint coordinates into 𝑢 and 𝑣

• 𝐻 , such that 𝑣 = 𝐻 (𝑣)

• 𝐵𝑣𝑢, 𝑏′, such that �̇� = 𝐵𝑣𝑢�̇� and 𝑣 = 𝐵𝑣𝑢�̈� + 𝑏′

Note, that saving 𝐵𝑣𝑢 and 𝑏𝑝𝑟𝑖𝑚𝑒 directly, although they can be derived from ℎ (𝑢, 𝑣) = 0 automatically, saves timewhen assembling a model and leaves room for optimising these expressions towards brevity.

4.2. Explicit Handling of Kinematic Loops 41

Page 46: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

42 Chapter 4. Background

Page 47: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

CHAPTER 5

PyMbs Architecture and Design

5.1 Overview

PyMbs consists of three main components: input, processing / analysis and output (see figure Basic structure ofPyMbs), whereas the processing and analysis layer can be considered to be the heart of PyMbs.

Fig. 5.1: Basic structure of PyMbs

The input layer provides the user interface for the description of the mechanical system. The model description iscompletely text based. The script created by the user is translated into an abstract syntax suitable for the generationof equations of motion by the processing module. This intermediate step prepares PyMbs for other user interfaces,i.e. graphical modeling, as any kind of model description can be used as long as an appropriate translator is provided.The analysis module simplifies and reduces the set of equations generated by the processing module and passes themto the code generator. The code generator provides a set of writers for several target languages and creates the outputfiles. Optionally, the graphical output module evaluates a function created by the python code generator to calculatethe positions and orientations of the elements of the mechanical system. The system can be visualised in an interactivescenegraph.

43

Page 48: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

5.2 Analysis

5.2.1 Introduction

The equations generated by the processing module are unsuitable for the calculation process. The generated system ofequation has many equations which are not useful to calculate the outputs of the system. Outputs are the values you areinterested in. In the case of PyMbs these are usually sensors. An example for equations that are easy to simplify arevariables that are zero/one or equal to another variable. The goal is to speed up the calculation by reducing the effort.The effort can be reduced by an analyses of the system of equations on the equation level and the system level. Theresulting system of equations contains only the essential steps to calculate the outputs. Take for example this graph

The corresponding system of equations is

𝑎 = 1

𝑏 = 0

𝑐 = 5 · 𝑘𝑑 = 𝑎 · 𝑐𝑒 = 2 · 𝑎 + 2

𝑓 = 𝑏 · 𝑘𝑔 = 𝑑 + 𝑒 + 𝑓

(5.1)

with the output 𝑔. Seven steps needed to calculate 𝑔. In order to reduce the system all zeros are eliminated. The secondstep is to do the same for all variables equal one. The last step is to replace all variables used only once. The resultingsystem of equations reads as follows

𝑐 = 5 · 𝑘𝑔 = 𝑐 + 4

(5.2)

Now, only two steps are required to calculate 𝑔.

Furthermore an abstract syntax tree of the system of equations is useful to calculate the dimensions from all variablesand to sort the equations. Not all supported languages and corresponding simulation tools are able to derive thedimension of an variable from the equation. To sort the equations is necessary because not all supported simulationtools are able to do this. Note, that the implemented algorithm is not able to handle loops in the system of equations.For example the given system of equations

𝑎 = 5

𝑏 = 𝑐 + 2𝑎

𝑐 = 𝑏 + 𝑎

𝑑 = 𝑏 + 𝑐

(5.3)

contains a loop for the variables 𝑏 and 𝑐. The methods used in implementing the aforementioned tasks are describedin the next section.

44 Chapter 5. PyMbs Architecture and Design

Page 49: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

5.2.2 Generating the Abstract Syntax Tree

The input from the Analysis Layer is a list of Expression objects. These objects have the following important infor-mation.

• The name of the variable called symbol, which represents the left hand side of the expression.

• The equation, which is the right hand side of the expression.

All information is stored in an node of the abstract syntax tree. A list of all required variables for each node can begenerated using the symbolics module. With the list of required variables from each node the edges of the tree canbe constructed. To store the edges, every node has two list. One for the parent nodes and one for the child nodes. Aparent node is a node which is used to calculate the expression of the node. In addition a global list of all nodes existsto avoid to iterate through the tree when searching nodes.

5.2.3 Reducing the System of Equation

The reduce algorithm has to find all nodes, which are

1. equal to zero or one or

2. have only one parent.

Because this is one of the main parts of the analysing module it should work efficient and fast.

The algorithm for the first point is divided in the following four steps. The first step is to find all nodes with no parentsto extract all constants. This can be done simple by looking on the list of parents from each node. The second step isto check whether the node is replaceable. Not all nodes are replaceable, for example parameters or sensors should notdisappear. To decide whether a node is replaceable or not categories were established. There are categories for statevariables, parameter variables or sensor variables. The third step is to check whether the node is equal to one or zero.If this conditions is true the last step starts and replaces the node in the equations of the children and rearranges theabstract syntax tree by removing the corresponding edges. After this changes it is possible that a child node equationbecomes equal to zero or one. Also this node should be replaced to obtain an equation system that is suitable forcalculating the outputs efficiently. These four steps are executed recursively for each child node.

The algorithm for the second point looks similar to the algorithm for the first point. The difference is that this algorithmdoes not work recursively. The algorithm is executed for each node of the global list of nodes.

5.2.4 Obtaining Sorted Equations

To sort the equations the nodes within the abstract syntax tree have to be marked with a level of depth. The level ofdepth is the longest path from a child to parent with no parents. This is done by a recursive algorithm that is executedfor a list of nodes. The first list contains all nodes with no parent node. The level of depth is default set to zero foreach node. This means all nodes have the same level of depth. The algorithm starts and tries to increase the level ofdepth for all children from a node of the list. If the level of depth of a child is not increased, the algorithm takes thenext node from the list. The level of depth can be increased if the new value is greater than the old one. In addition thisalgorithm is used to find loops inside the system of equations. Therefore each node has a flag that indicates if the nodehas been checked. If the flag is active and it will be visited again a loop is detected and an error message is thrown. Ifthe level of depth is set for all nodes the next step is to collect all nodes according to the desired category. Therefore aloop runs through the global list of nodes and collects the required nodes in a list. The next step is to collect all parentsfrom the nodes inside the list. This is done by an recursive algorithm and a following loop. The recursive algorithmgets the list of required nodes. It steps through all parents of the nodes and sets the required flag. Afterwards the loopchecks the global list of nodes and collects all nodes with active requried flag. With the list of all required nodes thethird step starts to arrange the required nodes in a way that every expression of a node can be calculated. Thereforeevery variable inside the expression has to be calculated beforehand. This problem is solved by the level of depth. Allnodes with equal level of depth are collected inside one list. Afterwards the lists are ordered by increasing level of

5.2. Analysis 45

Page 50: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

depth and concatenated. The last step is to calculate the dimension of each expression and collect the expressions in alist according to the sequence.

5.2.5 Calculating Value and Dimension of an Equation

For some layers there is a need to know the dimension of a variable. For example models designed in Modelica orC-code need the dimension for a variable. To get the dimension of a variable the expression need to be evaluated.To evaluate a expression all variables need to be known. This process is done recursively until a expression can beevaluated because it is a constant. The expression is evaluated using the symbolics module, which also returns thedimension of each variable.

5.3 Output

The output module is used to create code from a given set of equations for a specific target language. PyMbs is capableof generating code for

• Python

• Matlab

• Modelica

• C/C++

• Fortran.

This section will explain the mechanism of code generation and enable you to create custom writers for languages notlisted above. Therefore we strongly advise you to take a look at the source code of the involved classes to get a betterunderstanding of how things work.

5.3.1 The Code Generation Process

Code generation is now handled in the C++ backend of PyMbs and unfortunately has not been documented yet.

5.4 Simulation

If you choose to use the graphical user interface (usually invoked with PyMbs.Input.MbsSystem.show()),you can use PyMbs to simulate the behaviour of your system. Essentially, what this does is writing the equations ofmotions to a Python file in a temporary directory using the usual code generation mechanism of PyMbs. Then it usesan ODE integrator from scipy to calculate the coordinates of the system at the next point in time. These can then bevisualised in the GUI, provided you have supplied visualisation information in your script.

For larger systems, Python can become too slow to evaluate the time derivate for a smooth display of the mo-tion of the system. In this case, you can use the buttons Compile Model in Fortran or Compile Model in C tospeed up the calculation. Basically, this writes the time derivate as a Fortran or C function, as you would withPyMbs.Input.MbsSystem.GenCode, compiles it to a shared library, and calls this function using a Pythonwrapper.

46 Chapter 5. PyMbs Architecture and Design

Page 51: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

5.5 Control

The controller functionality provides the possibility to introduce loads whose value is determined by arbitrary Pythoncode.

When you use PyMbs.Input.MbsSystem.addController(), the control function you supply is importedinto the Python file containing the time derivative function. So for each time step, your control function is called, andthen the result is used in the time derivative. This also works in conjunction with the Compile Model in C button,where your function is called from the Python wrapper. Currently, compiling a model with Fortran with a controller isnot supported.

For an introduction on how to use controllers take a look at the Inverted Pendulum example. Additional examples withcontrollers can be found at Examples/controlledExamples.

5.5. Control 47

Page 52: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

48 Chapter 5. PyMbs Architecture and Design

Page 53: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

CHAPTER 6

Troubleshooting

In this chapter we rty to gather all problems which might occur during the usage of PyMbs and how they can be solved.

6.1 Error: PyScripter throws strange errors in Gui.py

Unfortunately, PyScripter does not reinitialise its Python engine properly which can cause very strange errors. Youhave the following options to resolve this:

• Restart PyScripter

• Use remote Python Engine (Run -> Python Engine -> Remote) which can be reinitialised

• Use a different editor

These strange errors are most commonly caused by a module that has been already imported and have changed (auto-matically or manually) since as is the case with some parts of the GUI. The Python engine does not recognise this anddoes not reload the module. Hence you are still working with the old version which can lead to unexpected behaviour.

6.2 Anything Else

Please contact Christian (christian.schubert @ <tud>). He will be happy to assist you.

<tud> = tu-dresden.de

49

Page 54: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

50 Chapter 6. Troubleshooting

Page 55: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

CHAPTER 7

Examples

In the following sections, a couple of examples files will be shown and the usage of PyMbs commands discussed. Usethese as an introduction and to get a feel for the capabilities of PyMbs.

7.1 Simple Pendulum

A very easy problem, and therefore used as an introduction here for PyMbs, is that of a swinging pendulum. If youwant to try it first, or look at the complete source code, see SimplePendulum.py.

First, we import PyMbs functions and classes from PyMbs.Input:

from PyMbs.Input import *

Then we set up our initial reference frame, which will also serve as an item to collect all the elements we add to ourmodel. The three item list gives the direction of the gravity vector, i.e. gravity will point in negative Z-direction in thisexample:

world = MbsSystem([0, 0, -1])

Now we list our parameters, in this case the mass, length and inertia of the pendulum. Each gets a symbol, and youcan use floating-point numbers or expressions to set their values:

m = world.addParam('m', 1.0)l = world.addParam('l', 1.0)I = world.addParam('Inertia', (m*l**2)/12)

We add a body to the system, representing the pendulum. It has a mass m and an inertia I:

pend = world.addBody(mass=m, inertia=diag([0, I, 0]))

Sometimes it is convenient or even necessary to be able to refer to the current position and orientation of a point ona body. To do this, you can add additional coordinate systems to a body. Here, we would like on at the top of thependulum, link, where the pendulum will be suspended from. You can specify the point at which the coordinatesystem is located and its orientation. Here, we only set the location to 1

2 𝑙, i.e. the end of the pendulum:

pend.addFrame('link', [0,0,0.5*l])

To limit the degree of freedom of our pendulum, we now add a joint to our model. The pendulum is supposed to swingaround top end (link), so we connect the world with pend.link, and supply Ry to the dofList. Ry meansrotation around y-axis:

51

Page 56: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

world.addJoint(world, pend.link, 'Ry')

Before we take a look at the behaviour of our system, we need to define a visualization for the pendulum. A box willdo nicely here:

world.addVisualisation.Box(pend, length=0.1, width=0.1, height=1.0)

Now we can generate the equations of motion for our system:

world.genEquations.Recursive()

Finally we can take a look at our system and check how it behaves:

world.show('SimplePendulum')

This is what it should look like:

In the end, the complete source looks like this:

# -*- coding: utf-8 -*-'''This file is part of PyMbs.

PyMbs is free software: you can redistribute it and/or modifyit under the terms of the GNU Lesser General Public License aspublished by the Free Software Foundation, either version 3 ofthe License, or (at your option) any later version.

PyMbs is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General PublicLicense along with PyMbs.If not, see <http://www.gnu.org/licenses/>.

Copyright 2011, 2012 Carsten Knoll, Christian Schubert,Jens Frenkel, Sebastian Voigt

'''# Warning: The source code of the examples is quoted in the documentation. If# you change this file, you'll have to change the corresponding file in the# documentation (see doc/examples).

# import PyMbs functionalityfrom PyMbs.Input import *

# create main object and inital reference frameworld = MbsSystem([0, 0, -1])

# mass, length and inertia of the rod

52 Chapter 7. Examples

Page 57: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

m = world.addParam('m', 1.0)l = world.addParam('l', 1.0)I = world.addParam('Inertia', (m*l**2)/12)

# add pendulumpend = world.addBody(mass=m, inertia=diag([0, I, 0]))# add additional coordinate system at upper end of the rodpend.addFrame('link', [0,0,0.5*l])

# add joint to constrain motion of the pendulumworld.addJoint(world, pend.link, 'Ry')

# use a Box to represente the pendulumworld.addVisualisation.Box(pend, length=0.1, width=0.1, height=1.0)

# generate equations of motionworld.genEquations.Recursive()

# show guiworld.show('SimplePendulum')

7.2 Mass-Spring-Damper System

Another commonly used introductory system is the mass-spring-damper system. A mass connected to a spring and adamper is displaced and then oscillates in the absence of other forces. If you want to try it first, or look at the completesource code, see MassSpringDamper.py.

As in the previous example, we import PyMbs, set up an intial reference frame and add a few parameters:

from PyMbs.Input import *world = MbsSystem([0, 0, -1])

m = world.addParam('m', 1)c = world.addParam('c', 10)d = world.addParam('d', 0.2)

Now we add the mass to the system and add a joint. Tz means that the mass can only undergo translation in z-direction. None if this is really new, but we add another parameter to the joint, startVals=1, which means themass will have an initial displacement of one:

movingBody = world.addBody(m)world.addJoint(world, movingBody, 'Tz', startVals=1)

This is where it gets interesting. We want to add a force to the system to simulate the influence of a spring and damperon the mass. First, we need know the displacement and velocity of the mass. Therefore, we add a distance sensor:

l = world.addSensor.Distance('l', movingBody, world)

The Distance sensor measures the scalar distance between two coordinate systems, here the systems ofmovingBody and world. Additionally, it measures the velocity. You can access the distance with l[0] andthe velocity with l[1]. The force for a spring is 𝐹𝑠 = −𝑐𝑥, with 𝑐 being the spring constant, and for a damper witha damping coefficient of 𝑑 the force is 𝐹𝑑 = −𝑑�̇�. Therefore, we add an expression that includes both:

F = world.addExpression('F', -(c*l[0] + d*l[1]))

So far, this only calculates the value of the force, but it isn’t applied to the system. To change this, we add a PtPForcebetween the body and the world:

7.2. Mass-Spring-Damper System 53

Page 58: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

world.addLoad.PtPForce(F, movingBody, world)

As in the previous example, we need to add visualisations so that we can see the movement of our system:

world.addVisualisation.Box(movingBody, 1, 1, 1)world.addVisualisation.Frame(world)

In the end, we generate the equations of motion for our system and start the representation:

world.genEquations.Recursive()world.show('MassSpringDamper')

This is what it should look like:

In the end, the complete source looks like this:

# -*- coding: utf-8 -*-'''This file is part of PyMbs.

PyMbs is free software: you can redistribute it and/or modifyit under the terms of the GNU Lesser General Public License aspublished by the Free Software Foundation, either version 3 ofthe License, or (at your option) any later version.

PyMbs is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General PublicLicense along with PyMbs.If not, see <http://www.gnu.org/licenses/>.

Copyright 2011, 2012 Carsten Knoll, Christian Schubert,Jens Frenkel, Sebastian Voigt

'''# Warning: The source code of the examples is quoted in the documentation. If# you change this file, you'll have to change the corresponding file in the# documentation (see doc/examples).

# set up PyMbs and the multi-body systemfrom PyMbs.Input import *world = MbsSystem([0, 0, -1])

54 Chapter 7. Examples

Page 59: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

# add parametersm = world.addParam('m', 1)c = world.addParam('c', 10)d = world.addParam('d', 0.2)

# add the body and constrain its movementmovingBody = world.addBody(m)world.addJoint(world, movingBody, 'Tz', startVals=1)

# add force to simulate a spring-damper combinationl = world.addSensor.Distance('l', movingBody, world)F = world.addExpression('F', -(c*l[0] + d*l[1]))world.addLoad.PtPForce(F, movingBody, world)

# add visualisationsworld.addVisualisation.Box(movingBody, 1, 1, 1)world.addVisualisation.Frame(world)

# generate equations and show the systemworld.genEquations.Recursive()world.show('MassSpringDamper')

7.3 Rope

Now we’ll try to simulate a rope. Here you’ll see the advantage of PyMbs in that it is fully scriptable using Python. Ifyou want to try it first, or look at the complete source code, see Rope.py.

We start with importing time (you’ll see why in a moment) and PyMbs, and set up our initial frame of reference asbefore:

import timefrom PyMbs.Input import *

world = MbsSystem([0, 0, -1])

To make our script a bit more flexible, we add the length of the rope, the rotational damping, the mass density, theradius and the number of segments used to simulate it as variables. Additionally, we choose which method is to beused to derive the equations of motion:

L = 3.0 # Total Lengthd = 0.2 # Rotational Dampingrho = 500.0 # 500 kg/m^3r = 0.1 # radiussegments = 15

# Choose between "Explicit", "OrderN" and "Recursive"method = "Recursive"

Now we initialize the lists that will hold our bodies and joints. Also, we calculate the length, mass and inertia of eachrope segment:

bodies = [None]*segmentsjoints = [None]*segments

# Parametersl = L/segments

7.3. Rope 55

Page 60: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

m = rho*pi*r**2*lI = 1/12*m*l**2*diag([1, 1, 1])

The interesting part is creating all the bodies and joints. We loop over the number of segments, create a body and anadditional frame at the end for each segment. We then connect the first segment to the world and the other segments toeach other. A simple line is used for visualisation. In the end, a joint load is added to each joint, with its value beingcalculated from multiplying the angular velocity (s[1]) with the rotational damping d:

for i in xrange(0, segments):# Create Body and Framebodies[i] = world.addBody(m, cg=[l/2, 0, 0], inertia=I)bodies[i].addFrame(name='end', p=[l, 0, 0])

# Create Jointsif (i==0):

joints[i] = world.addJoint(world, bodies[i], 'Ry')else:

joints[i] = world.addJoint(bodies[i-1].end, bodies[i], 'Ry')

world.addVisualisation.Line(bodies[i], l)

# Add Dampings = world.addSensor.Joint(symbol='state%i_'%i, joint=joints[i])D = world.addExpression(symbol_str='T%i_'%i, exp=-d*s[1])world.addLoad.Joint(joint=joints[i], symbol=D)

7.3.1 Method of Equation Generation

Now we get to the issue of which method to choose for generating the equations of motion. The choice is betweenExplicit, Recursive and OrderN. The explicit generation scheme is comparatively slow and should not be used for largersystems. On my system, using eight segments as a benchmark, the Explicit scheme took 12.9 seconds to generate theequations, OrderN took 1.06 seconds and the Recursive one 0.05 seconds.

You can test these for yourself using the time module:

t = time.clock()if method == "OrderN":

world.genEquations.OrderN()elif method == "Recursive":

world.genEquations.Recursive()elif method == "Explicit":

world.genEquations.Explicit()print "Time needed for generating equations: %5.2f s" % (time.clock() - t)

Not only is the time to generate the equations different, the complexity of the equations differs as well. Again foreight segments, the python code generated that is used for the simulation has 26.6 million characters (!) when usingExplicit, but only 172 thousand when using OrderN and 34 thousand for Recursive. So in this case you should use theRecursive scheme; for other models OrderN might be beneficial.

Now we can take a look at our rope swinging:

world.show('Rope')

This is what it should look like:

56 Chapter 7. Examples

Page 61: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

If you hit simulate with more than say six segments, the simulation will be quite slow, because the time integrationhas to evaluate a python function to obtain the accelerations for each time step. However, you can use the CompileModel in Fortran or Compile Model in C buttons to automatically export the equations to Fortran or C, compile themand reimport them for faster integration. This way, even 20 segments appear smooth on my machine.

In the end, the complete source looks like this:

# -*- coding: utf-8 -*-'''This file is part of PyMbs.

PyMbs is free software: you can redistribute it and/or modifyit under the terms of the GNU Lesser General Public License aspublished by the Free Software Foundation, either version 3 ofthe License, or (at your option) any later version.

PyMbs is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General PublicLicense along with PyMbs.If not, see <http://www.gnu.org/licenses/>.

Copyright 2011, 2012 Carsten Knoll, Christian Schubert,Jens Frenkel, Sebastian Voigt

'''# Warning: The source code of the examples is quoted in the documentation. If# you change this file, you'll have to change the corresponding file in the# documentation (see doc/examples).import timefrom PyMbs.Input import *

world = MbsSystem([0, 0, -1])

L = 3.0 # Total Lengthd = 0.2 # Rotational Dampingrho = 500.0 # 500 kg/m^3r = 0.1 # radiussegments = 15

# Choose between "Explicit", "OrderN" and "Recursive"

7.3. Rope 57

Page 62: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

method = "Recursive"

# Initialize Listsbodies = [None]*segmentsjoints = [None]*segments

# Parametersl = L/segmentsm = rho*pi*r**2*lI = 1/12*m*l**2*diag([1, 1, 1])

# Create Bodies and connect themfor i in xrange(0, segments):

# Create Body and Framebodies[i] = world.addBody(m, cg=[l/2, 0, 0], inertia=I)bodies[i].addFrame(name='end', p=[l, 0, 0])

# Create Jointsif (i==0):

joints[i] = world.addJoint(world, bodies[i], 'Ry')else:

joints[i] = world.addJoint(bodies[i-1].end, bodies[i], 'Ry')

world.addVisualisation.Line(bodies[i], l)

# Add Dampings = world.addSensor.Joint(symbol='state%i_'%i, joint=joints[i])D = world.addExpression(symbol_str='T%i_'%i, exp=-d*s[1])world.addLoad.Joint(joint=joints[i], symbol=D)

t = time.clock()if method == "OrderN":

world.genEquations.OrderN()elif method == "Recursive":

world.genEquations.Recursive()elif method == "Explicit":

world.genEquations.Explicit()print "Time needed for generating equations: %5.2f s" % (time.clock() - t)

world.show('Rope')

7.4 Four Bar Linkage

We will simulate a four bar linkage and introduce the command for handling kinematic loops like this. If you want totry it first, or look at the complete source code, see FourBarLinkage.py.

As usual, we start with importing PyMbs, creating a model system and adding various parameters. Here, they are thelengths, masses and interia of the bars to be connected:

world = MbsSystem([0, 0, -1])

# Parameterl1 = world.addParam('l1', 1)

m2 = world.addParam('m2', 1)

58 Chapter 7. Examples

Page 63: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

l2 = world.addParam('l2', 4)...

Now we create our additional three bars (world will act as the first bar) and add the coordinate systems 𝐴 through 𝐷at the corners:

world.addFrame(name='CS_D', p=[l1, 0, 0])

bar2 = world.addBody(name='Bar2', mass=m2, cg=[l2/2, 0, 0],inertia=diag([0, I2, I2]))

bar2.addFrame(name='CS_A')bar2.addFrame(name='CS_B', p=[l2, 0, 0])

bar3 = world.addBody(name='Bar3', mass=m3, cg=[l3/2, 0, 0],inertia=diag([0, I3, I3]))

bar3.addFrame(name='CS_B')bar3.addFrame(name='CS_C', p=[l3, 0, 0])

bar4 = world.addBody(name='Bar4', mass=m4, cg=[l4/2, 0, 0],inertia=diag([0, I4, I4]))

bar4.addFrame(name='CS_D')bar4.addFrame(name='CS_C', p=[l4, 0, 0])

Then we can connect three of them using normal joints:

jB = world.addJoint(bar2.CS_B, bar3.CS_B, 'Ry')jD = world.addJoint(world.CS_D, bar4.CS_D, 'Ry')

However, the last one (here its 𝐶) has to be connected using the command addLoop.FourBar to correctly handlethe kinematic loop:

world.addLoop.FourBar(bar3.CS_C, bar4.CS_C, posture=1)

With the posture parameter, either 1 or -1, you can choose which solution is being used. Usually, this switchesbetween the bars intersecting or not.

In the end, we add a line of each of the bars for visualisation, generate our equations of motion and start the GUI:

world.addVisualisation.Line(bar3, 4)world.addVisualisation.Line(bar4, 5)

world.genEquations.Recursive()world.show('FourBarLinkage')

The result should look roughly like this:

7.4. Four Bar Linkage 59

Page 64: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

In the end, the complete source looks like this:

# -*- coding: utf-8 -*-'''This file is part of PyMbs.

PyMbs is free software: you can redistribute it and/or modifyit under the terms of the GNU Lesser General Public License aspublished by the Free Software Foundation, either version 3 ofthe License, or (at your option) any later version.

PyMbs is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General PublicLicense along with PyMbs.If not, see <http://www.gnu.org/licenses/>.

Copyright 2011, 2012 Carsten Knoll, Christian Schubert,Jens Frenkel, Sebastian Voigt

'''# Warning: The source code of the examples is quoted in the documentation. If# you change this file, you'll have to change the corresponding file in the# documentation (see doc/examples).from PyMbs.Input import *

world = MbsSystem([0, 0, -1])

# Parameterl1 = world.addParam('l1', 1)

m2 = world.addParam('m2', 1)l2 = world.addParam('l2', 4)I2 = world.addParam('I2', m2/12*l2**2)

m3 = world.addParam('m3', 1)l3 = world.addParam('l3', 4)I3 = world.addParam('I3', m3/12*l3**2)

m4 = world.addParam('m4', 1)l4 = world.addParam('l4', 5)I4 = world.addParam('I4', m4/12*l4**2)

# Create Bodies with Coordinate Systemsworld.addFrame(name='CS_A')world.addFrame(name='CS_D', p=[l1, 0, 0])

bar2 = world.addBody(name='Bar2', mass=m2, cg=[l2/2, 0, 0],inertia=diag([0, I2, I2]))

bar2.addFrame(name='CS_A')bar2.addFrame(name='CS_B', p=[l2, 0, 0])

bar3 = world.addBody(name='Bar3', mass=m3, cg=[l3/2, 0, 0],inertia=diag([0, I3, I3]))

bar3.addFrame(name='CS_B')bar3.addFrame(name='CS_C', p=[l3, 0, 0])

60 Chapter 7. Examples

Page 65: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

bar4 = world.addBody(name='Bar4', mass=m4, cg=[l4/2, 0, 0],inertia=diag([0, I4, I4]))

bar4.addFrame(name='CS_D')bar4.addFrame(name='CS_C', p=[l4, 0, 0])

# Insert JointsjA = world.addJoint(world.CS_A, bar2.CS_A, 'Ry', pi/2)jB = world.addJoint(bar2.CS_B, bar3.CS_B, 'Ry')jD = world.addJoint(world.CS_D, bar4.CS_D, 'Ry')

world.addLoop.FourBar(bar3.CS_C, bar4.CS_C, posture=1)

world.addVisualisation.Line(bar2, 4)world.addVisualisation.Line(bar3, 4)world.addVisualisation.Line(bar4, 5)

world.genEquations.Recursive()world.show('FourBarLinkage')

7.5 Inverted Pendulum

In this example, we would like to introduce the controller functionality of PyMbs. With it, you can introduce loadsdepending on the state of the system using arbitrary python code. We want to simulate a simple pendulum hangingfrom a travelling trolley, with a force acting on the trolley to keeep the pendulum in an upright position. If youwant to try it first, or look at the complete source code, see InvertedPendulum.py. Note: You’ll also need thecorresponding controller.py to run the example.

We will start again with importing PyMbs, but also importing the controlForce residing in ourcontroller.py. We also set up our initial frame of reference:

from PyMbs.Input import MbsSystemfrom controller import controlForce

world = MbsSystem([0, 0, -1])

We add the masses of the trolley and the load, as well as the two bodies themselves:

M1 = world.addParam('m1', 0.8)M2 = world.addParam('m2', 0.3)

Trolley = world.addBody(M1)Load = world.addBody(M2, cg=[0, 0, -0.5])

The trolley can move translational and the pendulum rotates around the mounting point on the trolley:

world.addJoint(world, Trolley, 'Tx')world.addJoint(Trolley, Load, 'Ry')

Now the interesting bit. First, we add a controller, which gets a symbol ’F’, the handle of the function describing thecontroller controlForce and for non-scalar controllers, the resulting shape (3, ), i.e. this controller returns avector:

F = world.addController('F', controlForce, shape=(3, ))

Now we can use this object in any expression or load we would like. Here we add a CmpForce between the worldand the trolley:

7.5. Inverted Pendulum 61

Page 66: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

world.addLoad.CmpForce(F, Trolley, world, name='DrivingForce')

Let’s take a quick look at the controller itself. The source code is

import numpy as np

def controlForce(t, y, sensors):k = [ 25.4841998, 83.5330999, 20.38735984, 18.19367992]y0 = np.r_[0, np.pi, 0 ,0]F = np.dot(y-y0, k)return np.r_[F, 0, 0]

If you want to supply your own controller, the function has to adhere to the format functionname(time,coordinatevec, sensors), where time is the current simulation time, coordinatevec is a vector con-taining the generalised coordinates and their time derivative. In this example, we take the difference between thecurrent generalised coordinates y and the point we would like to reach y0 and multiply this by the vector k, whichwas predetermined for the particular parameters of this example. Of course, you could just as well calculate it in thisfunction. The result is the x-component of our force.

All that is left is to define the visualisations, generate our equations of motion and take a look at the system:

world.addVisualisation.Box(world, length=3, width=0.05, height=0.05)world.addVisualisation.Box(Trolley, length=0.1, width=0.1, height=0.1)world.addVisualisation.File(Load, 'Last_01.stl')

world.genEquations.Recursive()world.show('InvertedPendulum')

This results from running the simulation:

In the end, the complete source looks like this:

# -*- coding: utf-8 -*-'''Controlled pendulum

Single pendulum with controlling force acting on the joint. The control forceis defined in `controller.py` and tries to keep the pendulum upright.If you set the initial angle to 2.4 or more, the controller should reachequilibrium.'''# Warning: The source code of the examples is quoted in the documentation. If# you change this file, you'll have to change the corresponding file in the# documentation (see doc/examples).from PyMbs.Input import MbsSystemfrom controller import controlForce

world = MbsSystem([0, 0, -1])

62 Chapter 7. Examples

Page 67: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

M1 = world.addParam('m1', 0.8)M2 = world.addParam('m2', 0.3)

Trolley = world.addBody(M1)Load = world.addBody(M2, cg=[0, 0, -0.5])

world.addJoint(world, Trolley, 'Tx')world.addJoint(Trolley, Load, 'Ry')

F = world.addController('F', controlForce, shape=(3, ))world.addLoad.CmpForce(F, Trolley, world, name='DrivingForce')

# Visualisierungworld.addVisualisation.Box(world, length=3, width=0.05, height=0.05)world.addVisualisation.Box(Trolley, length=0.1, width=0.1, height=0.1)world.addVisualisation.File(Load, 'Last_01.stl')

# Bewegungsgleichungen berechnen und Modell darstellenworld.genEquations.Recursive()world.show('InvertedPendulum')

7.5. Inverted Pendulum 63

Page 68: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

64 Chapter 7. Examples

Page 69: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

CHAPTER 8

Developer Notes

8.1 Development History

PyMbs started off as a tool to generate the equations of motions of multibody system for external tools, such asMATLAB or Modelica. This is still at the core of PyMbs. Initially, sympy was used to generate these equations. Thisturned out to be inadequate in terms of performance for larger systems, so a dedicated symbolic computation modulehas been written in C++. Over time, a graphical user interface with the ability to simulate the model has been added, aswell the ability to define sensors and kinematic loops. Recently, the ability to influence the behaviour of your systemby use of a controller has been implemented.

8.2 Structure of the Repository

To get a feel for the project and where a particular peace of code is residing, here is a quick rundown of the mostcommonly used files and directories.

setup.py is the starting point for building, distributing and installing a Python module, this goes for PyMbs as well.

builder.py handles the extra steps required to build the symbolics module from C++ using CMake. It is calledfrom setup.py when necessary.

Common/ contains the base classes for bodies, frames, etc.

doc/ contains the Sphinx documentation for PyMbs.

Examples/ contains various examples of PyMbs models. Take a look at Examples/controlledExamplesfor models using a controller. Under Èxamples/miscExamples you’ll find old examples that may or may notwork with current versions of PyMbs.

Graphics/ includes all the code responsible for creating the graphical user interface.

Input/ is the main module that defines the user interface of PyMbs scripting. In particular,Input/MbsSystem.py is the starting point in all PyMbs scripts. Start here if you want to find out how a par-ticular feature is implemented.

Processing/ the code for Loads (Forces and Torques), Sensors, Kinematic Loops, etc. resides here.

Symbolics/ all of the “heavy lifting” is done in this C++ module. If you want to change the output for a codegenerator, you’ll have to modify the respective file in Symbolics/Writer/.

Test/ contains the unittests. Some of them are obsolete, others need expansion. Writing new tests is a great way toget started on improving PyMbs!

65

Page 70: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

8.3 Building PyMbs under Windows

To build PyMbs under Windows, you need CMake and Visual Studio (Express). Once you have VS installed, start aVisual Studio command prompt (the normal windows command prompt will not work, take a look under Visual Studioin the Start Menu), cd to your PyMbs source directory and execute:

python setup.py install

This should generate all the files necessary and copy them to the appropriate locations. Alternatively, you can use theCMake GUI and generate a Visual Studio project file which you can then build using the Visual Studio IDE.

8.4 Running the Tests

There are a couple of files containing unittests. Running each of these commands should result in no error:

python Test/test_symbolics.pypython Test/test_input.pypython Symbolics/SympyWrapper/test_symbolics.pypython Examples/testExamples.py

8.5 Working on the Documentation

A very good, short introduction to the Sphinx syntax can be found at Documenting Your Project Using Sphinx.

8.5.1 Building the Documentation

The documentation at Read the Docs is automatically build on every commit.

For building a local copy of the HTML documentation, you can call Sphinx like this:

sphinx-build <documentation-directory> <target-directory>

Commonly, if you are in the PyMbs source directory, you would call:

sphinx-build doc doc/.build

To then take a look at your newly built documentation, direct your browser to doc/.build/index.html.

If you want to build the PDF documentation, you need to have LaTeX installed as well. Then you need to call Sphinxwith the option -b latex to select the LaTeX builder, e.g.:

sphinx-build -b latex doc doc/.latex

This generates all the necessary .tex files, but does not execute PDF generation. To do this, go to the target directory(doc/.latex) and call make. This will call pdflatex a number of times and result in a file called PyMbs.pdfin that directory.

8.5.2 Sphinx Hints

In some cases it has been necessary to use some of the more obscure features of Sphinx. These are documented here.

66 Chapter 8. Developer Notes

Page 71: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Avoid substitutions in autodoced function definitions

The autodoc extension will execute some of your Python code as it imports your module/class. In some cases, thiswill lead to unwanted results. Consider this example code:

x = 3def my_function(foo_bar=x):

pass

This would be rendered as

my_function(foo_bar=3)

by autodoc. If you want to circumvent this, you have to duplicate the function definition in the first line of thedocstrings, i.e.:

x = 3def my_function(foo_bar=x):

"""my_function(foo_bar=x)"""pass

which now renders as intended

my_function(foo_bar=x)

In PyMbs, this has been used to document e.g. PyMbs.Input.MbsSystem.addFrame().

Document instance variables

Autodoc extracts the docstrings of your classes and methods to build parts of the documentation, in our case most ofthe Command Reference section. Variables and instance variables usually don’t have docstrings though. However,we expose the interfaces to Loads (Forces and Torques), Kinematic Loops, Sensors, etc. using instance variables.To document these entities, precede them with Python comments, followed by a colon. For example, the interfacePyMbs.Input.MbsSystem.addLoad has been documented like this:

#: addLoad contains a :class:`PyMbs.Input.MbsSystem.AddLoad` instance,#: see :ref:`loads` for the different load types available#:#: >>> world.addLoad.PtPForce(F, body_one, body_two)self.addLoad = AddLoad(self)

Alternativly use can add an ivar (instance variable) info field to the docstring of the class. However, these can not belinked to and should therefore be using sparingly.

Animation in HTML output, static image in PDF

The examples have a small animation of the simulation attached to them. They are in the form of .gif files; however,they can’t be included in the LaTeX version of the documentation. Because of this, a different file is to be includeddepending on the builder:

.. only:: html

.. image:: SimplePendulum.gif

.. only:: latex

.. image:: SimplePendulum.jpg:scale: 50 %

8.5. Working on the Documentation 67

Page 72: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

Source code from Examples

The Examples are documented by including the actual source code from <pymbs-root>/Examples with theliteralinclude directive, e.g.:

.. literalinclude:: ../../Examples/SimplePendulum.py:lines: 29-31

This includes the lines 29 through 31 in the documentation.

Warning: When you change the example .py files in <pymbs-root>/Examples, make sure you also changethe line numbers in the documentation accordingly!

68 Chapter 8. Developer Notes

Page 73: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

CHAPTER 9

Indices and tables

• genindex

• modindex

• search

69

Page 74: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

70 Chapter 9. Indices and tables

Page 75: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

Bibliography

[FS] Fisette, P; Samin, J. C.: Symbolic generation of large multibody system dynamic equations using a new semi-explicit Newton/Euler recursive scheme. In: Archive of applied mechanics Vol. 66, No 3. (1996) pp. 187-199

[WH] Wehage, R. A.; Hung, E. I.: Generalized coordinate partitioning for dimension reduction in analysis of con-strained dynamic systems. I, Mech. Design 134 (1982) pp. 247-255

71

Page 76: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

72 Bibliography

Page 77: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

Index

AAcceleration() (PyMbs.Input.MbsSystem.AddSensor

method), 24addBody() (PyMbs.Input.MbsSystem method), 14addConstraint() (PyMbs.Input.MbsSystem method), 14addContactSensorsLoads() (PyMbs.Input.MbsSystem

method), 15addController() (PyMbs.Input.MbsSystem method), 15addExpression() (PyMbs.Input.MbsSystem method), 15addFlexibleBody() (PyMbs.Input.MbsSystem method),

15addFrame() (PyMbs.Input.MbsSystem method), 16addGraphicSensors() (PyMbs.Input.MbsSystem method),

16addHydCylSensorsLoads() (PyMbs.Input.MbsSystem

method), 16addInput() (PyMbs.Input.MbsSystem method), 16addJoint() (PyMbs.Input.MbsSystem method), 17addJointLoad() (PyMbs.Input.MbsSystem method), 17AddLoad (class in PyMbs.Input.MbsSystem), 23addLoad (PyMbs.Input.MbsSystem attribute), 18AddLoop (class in PyMbs.Input.MbsSystem), 21addLoop (PyMbs.Input.MbsSystem attribute), 18addMotionSystemSensors() (PyMbs.Input.MbsSystem

method), 18addParam() (PyMbs.Input.MbsSystem method), 18AddSensor (class in PyMbs.Input.MbsSystem), 24addSensor (PyMbs.Input.MbsSystem attribute), 18addTyreSensorsLoads() (PyMbs.Input.MbsSystem

method), 18AddVisualisation (class in PyMbs.Input.MbsSystem), 27addVisualisation (PyMbs.Input.MbsSystem attribute), 19AngularAcceleration() (PyMbs.Input.MbsSystem.AddSensor

method), 25AngularVelocity() (PyMbs.Input.MbsSystem.AddSensor

method), 25Arrow() (PyMbs.Input.MbsSystem.AddVisualisation

method), 27

BBox() (PyMbs.Input.MbsSystem.AddVisualisation

method), 27

CC() (PyMbs.Input.MbsSystem.GenCode method), 30CenterofMass() (PyMbs.Input.MbsSystem.AddSensor

method), 25CmpForce() (PyMbs.Input.MbsSystem.AddLoad

method), 23CmpTorque() (PyMbs.Input.MbsSystem.AddLoad

method), 23ConstraintForce() (PyMbs.Input.MbsSystem.AddSensor

method), 25ConstraintTorque() (PyMbs.Input.MbsSystem.AddSensor

method), 25CrankSlider() (PyMbs.Input.MbsSystem.AddLoop

method), 21Cylinder() (PyMbs.Input.MbsSystem.AddVisualisation

method), 27

DDistance() (PyMbs.Input.MbsSystem.AddSensor

method), 25

EEnergy() (PyMbs.Input.MbsSystem.AddSensor method),

26ExpJoint() (PyMbs.Input.MbsSystem.AddLoop method),

21Explicit() (PyMbs.Input.MbsSystem.GenEqns method),

29exportGraphReps() (PyMbs.Input.MbsSystem method),

19

FFile() (PyMbs.Input.MbsSystem.AddVisualisation

method), 28flexible_Body() (PyMbs.Input.MbsSystem.AddVisualisation

method), 29

73

Page 78: PyMbs Documentation - Read the Docs · As we don’t have a Mac available for testing, we can’t give any instructions for installing. Basically, if you have Python and its modules

PyMbs Documentation, Release 2

FMU() (PyMbs.Input.MbsSystem.GenCode method), 30Fortran90() (PyMbs.Input.MbsSystem.GenCode

method), 30FourBar() (PyMbs.Input.MbsSystem.AddLoop method),

21FourBarTrans() (PyMbs.Input.MbsSystem.AddLoop

method), 21Frame() (PyMbs.Input.MbsSystem.AddVisualisation

method), 28

GGenCode (class in PyMbs.Input.MbsSystem), 30genCode (PyMbs.Input.MbsSystem attribute), 19GenEqns (class in PyMbs.Input.MbsSystem), 29genEquations (PyMbs.Input.MbsSystem attribute), 19genMatlabAnimation() (PyMbs.Input.MbsSystem

method), 19genSarturisXml() (PyMbs.Input.MbsSystem method), 19getController() (PyMbs.Input.MbsSystem method), 19getMotionEquations() (PyMbs.Input.MbsSystem

method), 19getParameters() (PyMbs.Input.MbsSystem method), 19getSensorEquations() (PyMbs.Input.MbsSystem

method), 19

HHexapod() (PyMbs.Input.MbsSystem.AddLoop method),

21Hexapod_m_AV() (PyMbs.Input.MbsSystem.AddLoop

method), 22

JJoint() (PyMbs.Input.MbsSystem.AddLoad method), 24Joint() (PyMbs.Input.MbsSystem.AddSensor method), 26

LLine() (PyMbs.Input.MbsSystem.AddVisualisation

method), 28

MMatlab() (PyMbs.Input.MbsSystem.GenCode method),

30MbsSystem (class in PyMbs.Input), 14Modelica() (PyMbs.Input.MbsSystem.GenCode method),

31my_function() (built-in function), 67

OOrderN() (PyMbs.Input.MbsSystem.GenEqns method),

29Orientation() (PyMbs.Input.MbsSystem.AddSensor

method), 26

PPosition() (PyMbs.Input.MbsSystem.AddSensor

method), 26PtPForce() (PyMbs.Input.MbsSystem.AddLoad method),

24Python() (PyMbs.Input.MbsSystem.GenCode method),

31

RRecursive() (PyMbs.Input.MbsSystem.GenEqns

method), 29

SsetGravity() (PyMbs.Input.MbsSystem method), 19setJointRange() (PyMbs.Input.MbsSystem method), 20show() (PyMbs.Input.MbsSystem method), 20simulate() (PyMbs.Input.MbsSystem method), 20Sphere() (PyMbs.Input.MbsSystem.AddVisualisation

method), 28Steering() (PyMbs.Input.MbsSystem.AddLoop method),

22

TThreeBarTrans() (PyMbs.Input.MbsSystem.AddLoop

method), 22Transmission() (PyMbs.Input.MbsSystem.AddLoop

method), 22

VVelocity() (PyMbs.Input.MbsSystem.AddSensor

method), 26

74 Index