import pychrono.core as chrono import pychrono.irrlicht as chronoirr import matplotlib.pyplot as plt import numpy as np print ("Example: create a slider crank and plot results"); # The path to the Chrono data directory containing various assets (meshes, textures, data files) # is automatically set, relative to the default location of this demo. # If running from a different directory, you must change the path to the data directory with: #chrono.SetChronoDataPath('path/to/data') # --------------------------------------------------------------------- # # Create the simulation system and add items # mysystem = chrono.ChSystemNSC() # Some data shared in the following crank_center = chrono.ChVectorD(-1,0.5,0) crank_rad = 0.4 crank_thick = 0.1 rod_length = 1.5 # Create four rigid bodies: the truss, the crank, the rod, the piston. # Create the floor truss mfloor = chrono.ChBodyEasyBox(3, 1, 3, 1000) mfloor.SetPos(chrono.ChVectorD(0,-0.5,0)) mfloor.SetBodyFixed(True) mysystem.Add(mfloor) # Create the flywheel crank mcrank = chrono.ChBodyEasyCylinder(crank_rad, crank_thick, 1000) mcrank.SetPos(crank_center + chrono.ChVectorD(0, 0, -0.1)) # Since ChBodyEasyCylinder creates a vertical (y up) cylinder, here rotate it: mcrank.SetRot(chrono.Q_ROTATE_Y_TO_Z) mysystem.Add(mcrank) # Create a stylized rod mrod = chrono.ChBodyEasyBox(rod_length, 0.1, 0.1, 1000) mrod.SetPos(crank_center + chrono.ChVectorD(crank_rad+rod_length/2 , 0, 0)) mysystem.Add(mrod) # Create a stylized piston mpiston = chrono.ChBodyEasyCylinder(0.2, 0.3, 1000) mpiston.SetPos(crank_center + chrono.ChVectorD(crank_rad+rod_length, 0, 0)) mpiston.SetRot(chrono.Q_ROTATE_Y_TO_X) mysystem.Add(mpiston) # Now create constraints and motors between the bodies. # Create crank-truss joint: a motor that spins the crank flywheel my_motor = chrono.ChLinkMotorRotationSpeed() my_motor.Initialize(mcrank, # the first connected body mfloor, # the second connected body chrono.ChFrameD(crank_center)) # where to create the motor in abs.space my_angularspeed = chrono.ChFunction_Const(chrono.CH_C_PI) # ang.speed: 180°/s my_motor.SetMotorFunction(my_angularspeed) mysystem.Add(my_motor) # Create crank-rod joint mjointA = chrono.ChLinkLockRevolute() mjointA.Initialize(mrod, mcrank, chrono.ChCoordsysD( crank_center + chrono.ChVectorD(crank_rad,0,0) )) mysystem.Add(mjointA) # Create rod-piston joint mjointB = chrono.ChLinkLockRevolute() mjointB.Initialize(mpiston, mrod, chrono.ChCoordsysD( crank_center + chrono.ChVectorD(crank_rad+rod_length,0,0) )) mysystem.Add(mjointB) # Create piston-truss joint mjointC = chrono.ChLinkLockPrismatic() mjointC.Initialize(mpiston, mfloor, chrono.ChCoordsysD( crank_center + chrono.ChVectorD(crank_rad+rod_length,0,0), chrono.Q_ROTATE_Z_TO_X) ) mysystem.Add(mjointC) # --------------------------------------------------------------------- # # Create an Irrlicht application to visualize the system # myapplication = chronoirr.ChIrrApp(mysystem, 'PyChrono example', chronoirr.dimension2du(1024,768)) myapplication.AddTypicalSky() myapplication.AddTypicalLogo(chrono.GetChronoDataFile('logo_pychrono_alpha.png')) myapplication.AddTypicalCamera(chronoirr.vector3df(1,1,3), chronoirr.vector3df(0,1,0)) myapplication.AddTypicalLights() # ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items # in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes. # If you need a finer control on which item really needs a visualization proxy in # Irrlicht, just use application.AssetBind(myitem); on a per-item basis. myapplication.AssetBindAll(); # ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets # that you added to the bodies into 3D shapes, they can be visualized by Irrlicht! myapplication.AssetUpdateAll(); # --------------------------------------------------------------------- # # Run the simulation # # Initialize these lists to store values to plot. array_time = [] array_angle = [] array_pos = [] array_speed = [] myapplication.SetTimestep(0.005) myapplication.SetTryRealtime(True) # Run the interactive simulation loop while(myapplication.GetDevice().run()): # for plotting, append instantaneous values: array_time.append(mysystem.GetChTime()) array_angle.append(my_motor.GetMotorRot()) array_pos.append(mpiston.GetPos().x) array_speed.append(mpiston.GetPos_dt().x) # here happens the visualization and step time integration myapplication.BeginScene() myapplication.DrawAll() myapplication.DoStep() myapplication.EndScene() # stop simulation after 2 seconds if mysystem.GetChTime() > 20: myapplication.GetDevice().closeDevice() # Use matplotlib to make two plots when simulation ended: fig, (ax1, ax2) = plt.subplots(2, sharex = True) ax1.plot(array_angle, array_pos) ax1.set(ylabel='position [m]') ax1.grid() ax2.plot(array_angle, array_speed, 'r--') ax2.set(ylabel='speed [m]',xlabel='angle [rad]') ax2.grid() # trick to plot \pi on x axis of plots instead of 1 2 3 4 etc. plt.xticks(np.linspace(0, 2*np.pi, 5),['0','$\pi/2$','$\pi$','$3\pi/2$','$2\pi$'])
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |