Introduction to Python

Learn the basics of Python interoperation with Chrono::Engine, using PyChrono.

  • import the PyChrono module
  • use basic classes: vectors, matrices, etc.
  • inherit classes
1 #------------------------------------------------------------------------------
2 # Name: pychrono example
3 # Purpose:
4 #
5 # Author: Alessandro Tasora
6 #
7 # Created: 1/01/2019
8 # Copyright: (c) ProjectChrono 2019
9 #------------------------------------------------------------------------------
10 
11 print ("First tutorial for PyChrono: vectors, matrices etc.");
12 
13 
14 # Load the Chrono::Engine core module!
15 import pychrono as chrono
16 
17 # Test logging
18 chrono.GetLog().Bar()
19 chrono.GetLog() << "result is: " << 11+1.5 << "\n"
20 chrono.GetLog().Bar()
21 
22 
23 # Test vectors
24 my_vect1 = chrono.ChVectorD()
25 my_vect1.x=5
26 my_vect1.y=2
27 my_vect1.z=3
28 my_vect2 = chrono.ChVectorD(3,4,5)
29 my_vect4 = my_vect1*10 + my_vect2
30 my_len = my_vect4.Length()
31 print ('vect sum =', my_vect1 + my_vect2)
32 print ('vect cross =', my_vect1 % my_vect2)
33 print ('vect dot =', my_vect1 ^ my_vect2)
34 
35 # Test quaternions
36 my_quat = chrono.ChQuaternionD(1,2,3,4)
37 my_qconjugate = ~my_quat
38 print ('quat. conjugate =', my_qconjugate)
39 print ('quat. dot product=', my_qconjugate ^ my_quat)
40 print ('quat. product=', my_qconjugate % my_quat)
41 
42 # Test matrices
43 ma = chrono.ChMatrixDynamicD(4,4)
44 ma.FillDiag(-2)
45 mb = chrono.ChMatrixDynamicD(4,4)
46 mb.FillElem(10)
47 mc = (ma-mb)*0.1; # operator overloading of +,-,* is supported
48 print (mc);
49 mr = chrono.ChMatrix33D()
50 mr.FillDiag(20)
51 print (mr*my_vect1);
52 
53 
54 # Test frames -
55 # create a frame representing a translation and a rotation
56 # of 20 degrees on X axis
57 my_frame = chrono.ChFrameD(my_vect2, chrono.Q_from_AngAxis(20*chrono.CH_C_DEG_TO_RAD, chrono.ChVectorD(1,0,0)))
58 my_vect5 = my_vect1 >> my_frame
59 
60 # Print the class hierarchy of a chrono class
61 import inspect
62 inspect.getmro(chrono.ChStreamOutAsciiFile)
63 
64 # Use matrices
65 my_matr = chrono.ChMatrixDynamicD(6,4)
66 my_matr[1,2]=4
67 my_matrb = chrono.ChMatrixDynamicD(4,6)
68 my_matrb.FillRandom(-2,2)
69 print ( my_matrb * 4 )
70 
71 
72 # Use the ChFunction classes
73 my_funct = chrono.ChFunction_Sine(0,0.5,3)
74 print ('function f(0.2)=', my_funct.Get_y(0.2) )
75 
76 
77 # Inherit from the ChFunction, from the Python side,
78 # (do not forget the __init__ constructor)
79 
80 class MySquareFunct (chrono.ChFunction):
81  def __init__(self):
82  chrono.ChFunction.__init__(self)
83  def Get_y(self,x):
84  return x*x
85 
86 
87 my_funct2 = MySquareFunct()
88 print ('function f(2) =', my_funct2.Get_y(3) )
89 print ('function df/dx=', my_funct2.Get_y_dx(3) )
90 
91 
92 
93 
94 
95 
96 
97