Slide 1

Slide 1 text

Python for the Dynamicist Jim Crist 3/11/15

Slide 2

Slide 2 text

Overview • A brief Python Overview • Introduction to SymPy • Multibody Dynamics Review • Examples!

Slide 3

Slide 3 text

What is Python? “A multiple paradigm, dynamically typed, interpreted, high level language focusing on readability.”

Slide 4

Slide 4 text

Core Data Types • Integers 1, 2, 3 • Floats 1.1, 2.5, 3.14 • Strings "apple", 'apple' • Constants True, False, None

Slide 5

Slide 5 text

Core Data Types • Lists ["apple", "orange", "pear"] • Tuples ("apple", "orange", "pear") • Dictionaries {"apple": 5, "orange": 6, "pear": 4} • Sets >>> {1, 2, 3, 3} {1, 2, 3}

Slide 6

Slide 6 text

Functions def count_chars(string): """Return the number of characters in a string.""" count = 0 for char in string: count += 1 return count

Slide 7

Slide 7 text

Why use Python??? • Free • General purpose language • Great Standard Library • Fast enough (usually) • Easily extensible • Active community

Slide 8

Slide 8 text

Active Community • Someone has probably already written the code you need • Python Package Index (PyPI) • https://pypi.python.org/pypi • Use pip or conda to install • As of 3/10/15, there were 56245 packages!

Slide 9

Slide 9 text

Scientific Python Ecosystem • NumPy • Base array manipulation package • SciPy • Huge number of scientific routines • Wrappers for many Fortran libraries • Matplotlib • Plotting library • IPython • A better interactive environment • Pandas • Statistical analysis • SymPy • Computer algebra

Slide 10

Slide 10 text

Numeric Arrays in Python • Not a core datatype, added with the NumPy package • Syntax: >>> from numpy import array >>> array([[1, 2], [3, 4]]) array([[1, 2], [3, 4]])

Slide 11

Slide 11 text

Numeric “Gotchas” • Integer division by default in Python 2 >>> 4/3 1 >>> 4/3. 1.33333333333333 • In Python 3, automatic promotion to float >>> 4/3 1.33333333333333 >>> 4//3 1

Slide 12

Slide 12 text

Numeric “Gotchas” • Array multiplication is element-wise >>> a = array([[1, 2], [3, 4]]) >>> a * a array([[1, 4], [9, 16]]) • Use dot to do matrix multiplication (dot product) >>> a.dot(a) array([[7, 10], [15, 22]])

Slide 13

Slide 13 text

To Learn More • Go through the Official Python Tutorial • Installation is easy on Mac/Linux • Install with system package manager (brew, apt-get, pacman…) • Can be a bit of a pain on Windows • Recommend Anaconda distribution

Slide 14

Slide 14 text

Slide 15

Slide 15 text

What is SymPy??? • A Computer Algebra System (CAS) written in pure Python • Allows you to create expressions, and do things with them • SymPy knows about all the math needed

Slide 16

Slide 16 text

Create Expressions >>> from sympy import * # Create Symbols >>> a, b, c = symbols('a, b, c') # Combine Symbols into expressions >>> expr = sin(a) + cos(b**2)*c >>> expr sin(a) + cos(b**2)*c

Slide 17

Slide 17 text

Manipulate Expressions # subs performs substitutions on expressions >>> expr = expr.subs(b, a**(1/2)) >>> expr sin(a) + sin(a)*c # simplify reduces the size of expressions >>> expr = expr.simplify() >>> expr sin(a)*(1 + c)

Slide 18

Slide 18 text

Solve Expressions # Create another symbol x >>> x = symbols('x') # Quadratic equation >>> lhs = a*x**2 + b*x + c >>> expr = Eq(lhs, 0) >>> expr a*x**2 + b*x + c == 0 # Solve returns solutions to expressions >>> solve(expr, x) [(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]

Slide 19

Slide 19 text

Submodules (just a few…) • Calculus • Linear Algebra • Set Theory • Combinatorics • Differential Geometry • Tensors • Classical Mechanics • etc…

Slide 20

Slide 20 text

Submodules (just a few…) • Calculus • Linear Algebra • Set Theory • Combinatorics • Differential Geometry • Tensors • Classical Mechanics • etc… What this talk is about

Slide 21

Slide 21 text

A VERY BRIEF OVERVIEW OF CLASSICAL MECHANICS

Slide 22

Slide 22 text

Classical Mechanics • Describes the motion of macroscopic objects • Concerned with solving = = −1 ∙ • Many ways to do so: • Newton • Lagrange • Kane

Slide 23

Slide 23 text

Vectors & Reference Frames

Slide 24

Slide 24 text

Generalized Coordinates & Speeds

Slide 25

Slide 25 text

Constraints • If coordinates and speeds are nonminimal, need constraints • Holonomic • Relations between coordinates • 1 , 2 , 3 , … , , = 0 • Nonholonomic • “Not-holonomic” (i.e. cannot be put in form above)

Slide 26

Slide 26 text

Constraints • Pendulum has 1 DOF, but 2 coordinates • Length is always • 1 , 2 , = 1 2 + 2 2 − 2 = 0

Slide 27

Slide 27 text

Formulations • Lagrange • Enforces constraints with Lagrange Multipliers () • Energy based formulation • Kane • Avoids need to compute Lagrange Multipliers • Uses generalized forces ( and ∗) • Can be simpler to compute for large systems

Slide 28

Slide 28 text

Equations of Motion ℎ , = 0×1 ℎ , , = 0×1 , , , = 0×1 , , , , , = 0 −+ ×1 with , ∈ ℝ , ∈ ℝ ∈ ℝ ∈ ℝ

Slide 29

Slide 29 text

Equations of Motion ℎ , = 0×1 ℎ , , = 0×1 , , , = 0×1 , , , , , = 0 −+ ×1 with , ∈ ℝ , ∈ ℝ ∈ ℝ ∈ ℝ Holonomic Constraints Nonholonomic Constraints Kinematic Equations Dynamic Equations Generalized Coordinates Generalized Speeds System Inputs Lagrange Multipliers

Slide 30

Slide 30 text

Equations of Motion Can be rearranged to form: (, ) = (, , , ) or = , −1(, , , )

Slide 31

Slide 31 text

Classical Mechanics • Inverted Pendulum, 1 Link

Slide 32

Slide 32 text

Classical Mechanics • Inverted Pendulum, 3 Links: Rendered in size 2.5 font

Slide 33

Slide 33 text

Classical Mechanics • Inverted Pendulum, 3 Links: Rendered in size 2.5 font

Slide 34

Slide 34 text

DERIVE EQUATIONS IN SYMPY Solution:

Slide 35

Slide 35 text

github.com/pydy/pydy

Slide 36

Slide 36 text

The PyDy Workflow 1. Specify system symbolically 2. Solve for EOM using either Kane’s or Lagrange’s method 3. Analyze resulting EOM symbolically 4. Compile equations, simulate system numerically 5. Visualize simulation results

Slide 37

Slide 37 text

Demo (try it at github.com/jcrist/talks/tree/master/dynamics_talk)

Slide 38

Slide 38 text

Analysis - Linearization • For systems with constraints, need to be careful! • Can’t just take Jacobian, as states are interdependent • i.e. 1 , , instead of 1 ()

Slide 39

Slide 39 text

Example – Single Link Pendulum • Derived EOM for minimal, and nonminimal formulations

Slide 40

Slide 40 text

Example – Single Link Pendulum Response for small angle deviation - simple jacobian linearization

Slide 41

Slide 41 text

Example – Single Link Pendulum Response for small angle deviation - simple jacobian linearization Wrong…

Slide 42

Slide 42 text

Linearization • Routine implemented to robustly linearize all cases • Works for formulations from Kane or Lagrange • Handles holonomic and nonholonomic constraints • Applied to Whipple bicycle model [1], matches to 14 digits the benchmark eigenvalues [1] Meijaard, J.P., Papadopoulos, J.M., Ruina, A., Schwab, A.L.: Linearized dynamics equations for the balance and steer of a bicycle: a benchmark and review. Proceedings of the Royal Society A: Mathematical, Physical and Engineering Sciences 463(2084), 1955–1982(2007)

Slide 43

Slide 43 text

Printers Symbolic Expression Fast Numeric Code Generators Wrappers • C • Fortran • Matlab/Octave • Javascript • Mathematica • Theano • C • Fortran • Matlab/Octave • Cython • F2Py • Numpy ufuncs Code Generation

Slide 44

Slide 44 text

Caveats… • C/Fortran use Floating Point numbers • Poorly conditioned expressions can give you unrealistic results • No universal way to guarantee well conditioned… • Decent solution: • Simulate at several points with multiple precision numbers (GMP) • Repeat computation with doubles, compare for accuracy • Large systems -> large expressions • Can lead to slow derivation • Most systems are fine (have done 25 link inverted pendulum easily)

Slide 45

Slide 45 text

Why? • Open Source • Other symbolic solvers (AutoLev*, SD/FAST) are proprietary • Fast • Slower generation than numeric methods • Faster simulation • Correct • No math errors for hand-calculated EOM • Automatic translation to C/Fortran -> no typing errors *Now defunct

Slide 46

Slide 46 text

Future Work • O(n) articulated methods • Featherstone/Jain • High-level specification • Specify link/joint parameters to easily build up model • Finish work on LAPACK/BLAS/ODEPACK integration • Will remove Python layer bottleneck for simulation • Integration with Ipopt/CasADi for optimization problems

Slide 47

Slide 47 text

Questions???