plotSensorTest.py

You can view and download this file on Github: plotSensorTest.py

  1#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  2# This is an EXUDYN example
  3#
  4# Details:  Test model and example for exudyn.plot.PlotSensor, using several sensors and plotting results; data given
  5#           as numpy array, also with an output directory set
  6#
  7# Author:   Johannes Gerstmayr
  8# Date:     2021-07-01
  9#
 10# Copyright:This file is part of Exudyn. Exudyn is free software. You can redistribute it and/or modify it under the terms of the Exudyn license. See 'LICENSE.txt' for more details.
 11#
 12#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 13
 14import exudyn as exu
 15from exudyn.utilities import * #includes itemInterface and rigidBodyUtilities
 16import exudyn.graphics as graphics
 17
 18from math import sin, cos, pi
 19import numpy as np
 20
 21testIsActive = exu.sys.get('testIsActive', False)
 22
 23SC = exu.SystemContainer()
 24mbs = SC.AddSystem()
 25# testIsActive = True
 26
 27#background
 28color = [0.1,0.1,0.8,1]
 29L = 0.4 #length of bodies
 30d = 0.1 #diameter of bodies
 31
 32#create background, in order to have according zoom all
 33zz=2*L
 34#background0 = GraphicsDataRectangle(-zz,-zz,zz,zz,graphics.color.white)
 35oGround=mbs.AddObject(ObjectGround(referencePosition= [0,0,0])) #,visualization=VObjectGround(graphicsData= [background0])))
 36mGround = mbs.AddMarker(MarkerBodyRigid(bodyNumber = oGround, localPosition=[0,0,0]))
 37
 38p0 = [0.,0.,0] #reference position
 39vLoc = np.array([L,0,0]) #last to next joint
 40
 41g = [0,-9.81*0,0]
 42
 43inertia = InertiaCuboid(density=1000, sideLengths=[L,d,d])
 44#p0 += Alist[i] @ (0.5*vLoc)
 45p0 += (0.5*vLoc)
 46
 47ep0 = eulerParameters0 #no rotation
 48graphicsBody = graphics.Brick([0,0,0], [L,d,d], graphics.color.steelblue)
 49oRB = mbs.CreateRigidBody(inertia=inertia, 
 50                          referencePosition=p0,
 51                          gravity=g,
 52                          graphicsDataList=[graphicsBody])
 53nRB= mbs.GetObject(oRB)['nodeNumber']
 54
 55mPos0 = mbs.AddMarker(MarkerBodyRigid(bodyNumber = oRB, localPosition = [-0.5*L,0,0]))
 56mPosLast = mbs.AddMarker(MarkerBodyRigid(bodyNumber = oRB, localPosition = [0.5*L,0,0]))
 57
 58oRJ = mbs.AddObject(ObjectJointRevoluteZ(markerNumbers = [mGround, mPos0], 
 59                                  visualization=VObjectJointRevoluteZ(axisRadius=0.5*d, axisLength=1.2*d) )) 
 60    
 61def UFload(mbs,t,load):
 62    return [0,load[1]*np.cos(t*2*np.pi),0]
 63
 64lForce = mbs.AddLoad(LoadForceVector(markerNumber=mPosLast, loadVector=[0,2,0], loadVectorUserFunction=UFload))
 65
 66from exudyn.basicUtilities import OutputFilePath #resolve exudyn.config.outputDirectory (#2454)
 67filedir = 'solution/'
 68#these test are really written to files (most other tests use internal storage):
 69sLoad = mbs.AddSensor(SensorLoad(loadNumber=lForce, fileName=filedir+'plotSensorLoad.txt'))
 70sNode = mbs.AddSensor(SensorNode(nodeNumber=nRB, fileName=filedir+'plotSensorNode.txt', outputVariableType=exu.OutputVariableType.Coordinates))
 71sNode2 = mbs.AddSensor(SensorNode(nodeNumber=nRB, fileName=filedir+'plotSensorNodeRotation.txt', outputVariableType=exu.OutputVariableType.Rotation))
 72sBody = mbs.AddSensor(SensorBody(bodyNumber=oRB, fileName=filedir+'plotSensorBody.txt', localPosition=[0.5*L,0,0], outputVariableType=exu.OutputVariableType.Position))
 73sObject = mbs.AddSensor(SensorObject(objectNumber=oRJ, fileName=filedir+'plotSensorObject.txt', outputVariableType=exu.OutputVariableType.ForceLocal))
 74sMarker = mbs.AddSensor(SensorMarker(markerNumber=mPosLast, fileName=filedir+'plotSensorMarker.txt', outputVariableType=exu.OutputVariableType.Position))
 75
 76mbs.Assemble()
 77
 78simulationSettings = exu.SimulationSettings() #takes currently set values or default values
 79
 80tEnd = 1
 81h=0.01  #use small step size to detext contact switching
 82
 83simulationSettings.timeIntegration.numberOfSteps = int(tEnd/h)
 84simulationSettings.timeIntegration.endTime = tEnd
 85simulationSettings.solution.file.writePeriod = 0.01
 86simulationSettings.solution.sensors.writePeriod = 0.01
 87simulationSettings.timeIntegration.verboseMode = 1
 88# simulationSettings.timeIntegration.realtime.active = True
 89
 90# simulationSettings.timeIntegration.generalizedAlpha.spectralRadius = 0.8
 91# simulationSettings.timeIntegration.generalizedAlpha.computeInitialAccelerations=True
 92simulationSettings.timeIntegration.newton.useModifiedNewton = True
 93
 94# SC.visualizationSettings.nodes.show = True
 95# SC.visualizationSettings.nodes.drawNodesAsPoint  = False
 96# SC.visualizationSettings.nodes.showBasis = True
 97# SC.visualizationSettings.nodes.basisSize = 0.015
 98# SC.visualizationSettings.connectors.showJointAxes = True
 99 
100SC.visualizationSettings.general.autoFitScene = False #use loaded render state
101#testIsActive = True
102if not testIsActive:
103    SC.renderer.Start()
104    SC.renderer.RestoreSavedState()
105    #SC.renderer.DoIdleTasks()
106else:
107    simulationSettings.solution.file.write = False
108
109#mbs.SolveDynamic(simulationSettings, solverType=exu.DynamicSolverType.TrapezoidalIndex2)
110mbs.SolveDynamic(simulationSettings, showHints=True)
111
112#%%+++++++++++++++++++++++++++++
113if not testIsActive:
114    #SC.renderer.DoIdleTasks()
115    SC.renderer.Stop() #safely close rendering window!
116
117
118exu.sys['testResult'] = 1
119
120import matplotlib.pyplot as plt
121
122
123closeAll = not (not testIsActive)
124mbs.PlotSensor(sensorNumbers=sLoad, components=[0,1,2], closeAll=closeAll)
125mbs.PlotSensor(sensorNumbers=sNode, components=[0,1,2,3,4,5,6], 
126           yLabel='Coordinates with offset 1\nand scaled with $\\frac{1}{1000}$', 
127           factors=1e-3, offsets=1,fontSize=12, closeAll=closeAll)
128mbs.PlotSensor(sensorNumbers=sNode2, components=[0,1,2], closeAll=closeAll)
129mbs.PlotSensor(sensorNumbers=sNode2, components=[0,1,2], closeAll=closeAll)
130mbs.PlotSensor(sensorNumbers=[sBody]*3+[sMarker]*3, components=[0,1,2,0,1,2], 
131           colorCodeOffset=3, newFigure=closeAll, fontSize=10, 
132           yLabel='Rotation $\\alpha, \\beta, \\gamma$ and\n Position $x,y,z$', closeAll=closeAll)
133mbs.PlotSensor(sensorNumbers=sObject, components=[0,1,2], title='Revolute joint forces', closeAll=closeAll)
134#a sensor given by NUMBER is read from exudyn.config.outputDirectory, a file name given here is
135#read as it is - so the model resolves it itself (#2454)
136mbs.PlotSensor(sensorNumbers=[sNode]*3+ [OutputFilePath(filedir+'plotSensorNode.txt')]*3, components=[0,1,2]*2, closeAll=closeAll)
137#data given as numpy array (time in the first column) is plotted as it is, also with an output directory set (#2836)
138import numpy as np
139dataArray = np.column_stack((np.linspace(0,1,11), np.linspace(0,1,11)**2))
140outputDirectoryBefore = exu.config.outputDirectory
141exu.config.outputDirectory = 'solution'
142try:
143    mbs.PlotSensor(sensorNumbers=[dataArray], components=[0], labels=['data as array'], closeAll=closeAll)
144finally:
145    exu.config.outputDirectory = outputDirectoryBefore
146
147if closeAll:
148    plt.close('all')
149
150import os
151for s in range(mbs.systemData.NumberOfSensors()):
152    #the solver wrote the sensor into exudyn.config.outputDirectory, so delete it there (#2454)
153    fileName=OutputFilePath(mbs.GetSensor(s)['fileName'])
154    exu.Print('remove file:', fileName)
155    os.remove(fileName)