def Simulate(SC, mbs): #%%++++++++++++++++++++++++++++++++++++++++++++++++++++++ #assemble system and solve simulationSettings = exu.SimulationSettings() #takes currently set values or default values tEnd = 2 #simulation time h = 1e-3 #step size simulationSettings.timeIntegration.numberOfSteps = int(tEnd/h) simulationSettings.timeIntegration.endTime = tEnd simulationSettings.timeIntegration.verboseMode = 1 simulationSettings.timeIntegration.simulateInRealtime = True SC.visualizationSettings.general.autoFitScene = False SC.visualizationSettings.window.renderWindowSize=[1600,1200] SC.visualizationSettings.openGL.multiSampling = 4 # exu.StartRenderer() # if 'renderState' in exu.sys: #reload old view # SC.SetRenderState(exu.sys['renderState']) mbs.WaitForUserToContinue() #stop before simulating exu.SolveDynamic(mbs, simulationSettings = simulationSettings, solverType=exu.DynamicSolverType.TrapezoidalIndex2)
def SolveStatic( mbs, simulationSettings=exudyn.SimulationSettings(), updateInitialValues=False, storeSolver=True, showHints=False, showCausingItems=True, ): staticSolver = exudyn.MainSolverStatic() if storeSolver: mbs.sys[ 'staticSolver'] = staticSolver #copy solver structure to sys variable mbs.sys[ 'simulationSettings'] = simulationSettings #link to last simulation settings success = False try: success = staticSolver.SolveSystem(mbs, simulationSettings) except: pass #print error message after except, to catch all errors if not success: # exudyn.Print not shown in Spyder at this time (because of exception?) # exudyn.Print(SolverErrorMessage(staticSolver, mbs, isStatic=True, showCausingObjects=showCausingItems, # showCausingNodes=showCausingItems, showHints=showHints)) print( SolverErrorMessage(staticSolver, mbs, isStatic=True, showCausingObjects=showCausingItems, showCausingNodes=showCausingItems, showHints=showHints)) raise ValueError("SolveStatic terminated due to errors") elif updateInitialValues: currentState = mbs.systemData.GetSystemState() #get current values mbs.systemData.SetSystemState( systemStateList=currentState, configuration=exudyn.ConfigurationType.Initial) return success
def TestExudyn(x): #create an environment for mini example SC = exu.SystemContainer() mbs = SC.AddSystem() oGround = mbs.AddObject(ObjectGround(referencePosition=[0, 0, 0])) nGround = mbs.AddNode(NodePointGround(referenceCoordinates=[0, 0, 0])) testError = 1 #set default error, if failed exu.Print("start mini example for class ObjectMass1D") node = mbs.AddNode( Node1D(referenceCoordinates=[0], initialCoordinates=[0.], initialVelocities=[1 * x])) mass = mbs.AddObject(Mass1D(nodeNumber=node, physicsMass=1)) #assemble and solve system for default parameters mbs.Assemble() #exu.SolveDynamic(mbs, exu.SimulationSettings()) h = 1e-6 tEnd = 10 simulationSettings = exu.SimulationSettings() simulationSettings.timeIntegration.numberOfSteps = int(tEnd / h) simulationSettings.timeIntegration.endTime = tEnd simulationSettings.solutionSettings.coordinatesSolutionFileName = "coordinatesSolution" + str( int(x)) + ".txt" simulationSettings.solutionSettings.writeSolutionToFile = True #no concurrent writing to files ...! #exu.StartRenderer() #don't do this in parallelization: will crash exu.SolveDynamic(mbs, simulationSettings) #exu.StopRenderer() #don't do this in parallelization: will crash #check result, get current mass position at local position [0,0,0] result = mbs.GetObjectOutputBody(mass, exu.OutputVariableType.Position, [0, 0, 0])[0] print("result ", x, "=", result) return result
markerNumbers=[mGlobalGround, mRigidBodyRot], damping=1e6, visualization=VObjectConnectorCoordinateSpringDamper(show=False))) positionOfBody += distanceBetweenBodys #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++# # Assemble multibody system #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++# mbs.Assemble() #exu.Print(mbs) #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++# # Simualtion settings: #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++# simulationSettings = exu.SimulationSettings() #simulationSettings.staticSolver.loadStepGeometric = True #simulationSettings.staticSolver.adaptiveStep = False simulationSettings.staticSolver.numberOfLoadSteps = 10 #simulationSettings.staticSolver.loadStepGeometricRange = 100 simulationSettings.staticSolver.newton.relativeTolerance = 1e-7 #with this error tolerance, the adaptive step selection needs 4 steps #simulationSettings.staticSolver.verboseMode=1 #simulationSettings.staticSolver.verboseModeFile=2 simulationSettings.staticSolver.stabilizerODE2term = 2 SC.visualizationSettings.general.circleTiling = 64 SC.visualizationSettings.nodes.defaultSize = 0.125 SC.visualizationSettings.contour.outputVariable = exu.OutputVariableType.Displacement SC.visualizationSettings.contour.outputVariableComponent = 1 # plot y-component SC.visualizationSettings.connectors.contactPointsDefaultSize = .005
initialCoordinates=[initialLocalMarker, slidingCoordinateInit], numberOfDataCoordinates=2)) #initial index in cable list slidingJoint = mbs.AddObject( ObjectJointSliding2D(name='slider', markerNumbers=[ markerRigidTop, cableMarkerList[initialLocalMarker] ], slidingMarkerNumbers=cableMarkerList, slidingMarkerOffsets=offsetList, nodeNumber=nodeDataSJ)) mbs.Assemble() print(mbs) simulationSettings = exu.SimulationSettings( ) #takes currently set values or default values #simulationSettings.solutionSettings.coordinatesSolutionFileName = 'ANCFCable2Dbending' + str(nElements) + '.txt' h = 5e-4 tEnd = 0.6 simulationSettings.timeIntegration.numberOfSteps = int(tEnd / h) simulationSettings.timeIntegration.endTime = tEnd simulationSettings.solutionSettings.writeSolutionToFile = True simulationSettings.solutionSettings.solutionWritePeriod = h #simulationSettings.solutionSettings.outputPrecision = 4 simulationSettings.displayComputationTime = True simulationSettings.timeIntegration.verboseMode = 1 # simulationSettings.timeIntegration.newton.relativeTolerance = 1e-8*100 #10000 # simulationSettings.timeIntegration.newton.absoluteTolerance = 1e-10*100
def ParameterFunction(parameterSet): SC = exu.SystemContainer() mbs = SC.AddSystem() #default values mass = 1.6 #mass in kg spring = 4000 #stiffness of spring-damper in N/m damper = 8 #damping constant in N/(m/s) u0=-0.08 #initial displacement v0=1 #initial velocity f =80 #force applied to mass #process parameters if 'mass' in parameterSet: mass = parameterSet['mass'] if 'spring' in parameterSet: spring = parameterSet['spring'] iCalc = 'Ref' #needed for parallel computation ==> output files are different for every computation if 'computationIndex' in parameterSet: iCalc = str(parameterSet['computationIndex']) #mass-spring-damper system L=0.5 #spring length (for drawing) x0=f/spring #static displacement # print('resonance frequency = '+str(np.sqrt(spring/mass))) # print('static displacement = '+str(x0)) #node for 3D mass point: n1=mbs.AddNode(Point(referenceCoordinates = [L,0,0], initialCoordinates = [u0,0,0], initialVelocities= [v0,0,0])) #ground node nGround=mbs.AddNode(NodePointGround(referenceCoordinates = [0,0,0])) #add mass point (this is a 3D object with 3 coordinates): massPoint = mbs.AddObject(MassPoint(physicsMass = mass, nodeNumber = n1)) #marker for ground (=fixed): groundMarker=mbs.AddMarker(MarkerNodeCoordinate(nodeNumber= nGround, coordinate = 0)) #marker for springDamper for first (x-)coordinate: nodeMarker =mbs.AddMarker(MarkerNodeCoordinate(nodeNumber= n1, coordinate = 0)) #spring-damper between two marker coordinates nC = mbs.AddObject(CoordinateSpringDamper(markerNumbers = [groundMarker, nodeMarker], stiffness = spring, damping = damper)) #add load: mbs.AddLoad(LoadCoordinate(markerNumber = nodeMarker, load = f)) #add sensor: fileName = 'solution/paramVarDisplacement'+iCalc+'.txt' mbs.AddSensor(SensorObject(objectNumber=nC, fileName=fileName, outputVariableType=exu.OutputVariableType.Force)) #print(mbs) mbs.Assemble() steps = 1000 #number of steps to show solution tEnd = 1 #end time of simulation simulationSettings = exu.SimulationSettings() #simulationSettings.solutionSettings.solutionWritePeriod = 5e-3 #output interval general simulationSettings.solutionSettings.writeSolutionToFile = False simulationSettings.solutionSettings.sensorsWritePeriod = 5e-3 #output interval of sensors simulationSettings.timeIntegration.numberOfSteps = steps simulationSettings.timeIntegration.endTime = tEnd simulationSettings.timeIntegration.generalizedAlpha.spectralRadius = 1 #no damping #exu.StartRenderer() #start graphics visualization #mbs.WaitForUserToContinue() #wait for pressing SPACE bar to continue #start solver: exu.SolveDynamic(mbs, simulationSettings) #SC.WaitForRenderEngineStopFlag()#wait for pressing 'Q' to quit #exu.StopRenderer() #safely close rendering window! # #evaluate final (=current) output values # u = mbs.GetNodeOutput(n1, exu.OutputVariableType.Position) # print('displacement=',u) #+++++++++++++++++++++++++++++++++++++++++++++++++++++ #evaluate difference between reference and optimized solution #reference solution: dataRef = np.loadtxt('solution/paramVarDisplacementRef.txt', comments='#', delimiter=',') data = np.loadtxt(fileName, comments='#', delimiter=',') diff = data[:,1]-dataRef[:,1] errorNorm = np.sqrt(np.dot(diff,diff))/steps*tEnd #+++++++++++++++++++++++++++++++++++++++++++++++++++++ #compute exact solution: if False: from matplotlib import plt plt.close('all') plt.plot(data[:,0], data[:,1], 'b-', label='displacement (m)') ax=plt.gca() # get current axes ax.grid(True, 'major', 'both') ax.xaxis.set_major_locator(ticker.MaxNLocator(10)) ax.yaxis.set_major_locator(ticker.MaxNLocator(10)) plt.legend() #show labels as legend plt.tight_layout() plt.show() import os if iCalc != 'Ref': os.remove(fileName) #remove files in order to clean up del mbs del SC return errorNorm
exu.Print("start mini example for class ObjectANCFCable2D") try: #puts example in safe environment node = mbs.AddNode(NodePoint(referenceCoordinates=[1.05, 0, 0])) oMassPoint = mbs.AddObject(MassPoint(nodeNumber=node, physicsMass=1)) m0 = mbs.AddMarker( MarkerBodyPosition(bodyNumber=oGround, localPosition=[0, 0, 0])) m1 = mbs.AddMarker( MarkerBodyPosition(bodyNumber=oMassPoint, localPosition=[0, 0, 0])) mbs.AddObject( ObjectConnectorSpringDamper( markerNumbers=[m0, m1], referenceLength=1, #shorter than initial distance stiffness=100, damping=1)) #assemble and solve system for default parameters mbs.Assemble() exu.SolveDynamic(mbs, exu.SimulationSettings()) #check result at default integration time testError = mbs.GetNodeOutput( node, exu.OutputVariableType.Position)[0] - 0.9736596225944887 except BaseException as e: exu.Print("An error occured in test example for ObjectANCFCable2D:", e) else: exu.Print("example for ObjectANCFCable2D completed, test error =", testError)
def SolutionViewer(mainSystem, solution=[], rowIncrement=1, timeout=0.04, runOnStart=True, runMode=2): from exudyn.utilities import SetSolutionState, LoadSolutionFile mbs = mainSystem SC = mbs.GetSystemContainer() if solution == []: if not 'simulationSettings' in mbs.sys: raise ValueError( 'SolutionViewer: no solution file found (already simulated?)!') sims = mbs.sys['simulationSettings'] if not sims.solutionSettings.writeSolutionToFile: raise ValueError( 'SolutionViewer: previous simulation has writeSolutionToFile==False; no solution file available!' ) solution = LoadSolutionFile( sims.solutionSettings.coordinatesSolutionFileName ) #load solution file of previous simulation nRows = solution['nRows'] if nRows == 0: print('ERROR in SolutionViewer: solution file is empty') return if (runMode != 0 and runMode != 1 and runMode != 2): print('ERROR in SolutionViewer: illegal run mode:', runMode) return if (rowIncrement < 1) or (rowIncrement > nRows): print( 'ERROR in SolutionViewer: rowIncrement must be at least 1 and must not be larger than the number of rows in the solution file' ) oldUpdateInterval = SC.visualizationSettings.general.graphicsUpdateInterval SC.visualizationSettings.general.graphicsUpdateInterval = 0.5 * min( timeout, 2e-3) #avoid too small values to run multithreading properly mbs.SetRenderEngineStopFlag(False) #not to stop right at the beginning # runLoop = False # while runLoop and not mainSystem.GetRenderEngineStopFlag(): # for i in range(0,nRows,rowIncrement): # if not(mainSystem.GetRenderEngineStopFlag()): # SetSolutionState(mainSystem, solution, i, exudyn.ConfigurationType.Visualization) # exudyn.DoRendererIdleTasks(timeout) SetSolutionState(mainSystem, solution, 0, exudyn.ConfigurationType.Visualization) exudyn.DoRendererIdleTasks(timeout) nSteps = int(nRows) #only make these steps available in slider! maxNSteps = max(500, min( nSteps, 1200)) #do not allow more steps, because dialog may be too large ... resolution = min(1., maxNSteps / nSteps) #do not use values smaller than 1 dialogItems = [ { 'type': 'label', 'text': 'Solution steps:', 'grid': (1, 0) }, { 'type': 'slider', 'range': (0, nSteps - 1), 'value': 0, 'steps': maxNSteps, 'variable': 'solutionViewerStep', 'resolution': resolution, 'grid': (1, 1) }, { 'type': 'label', 'text': 'Increment:', 'grid': (2, 0) }, { 'type': 'slider', 'range': (1, 200), 'value': rowIncrement, 'steps': 200, 'variable': 'solutionViewerRowIncrement', 'grid': (2, 1) }, { 'type': 'label', 'text': 'update period:', 'grid': (3, 0) }, { 'type': 'slider', 'range': (0.005, 1), 'value': timeout, 'steps': 200, 'variable': 'solutionViewerPeriod', 'grid': (3, 1) }, { 'type': 'radio', 'textValueList': [('Continuous run', 0), ('One cycle', 1), ('Static', 2)], 'value': runMode, 'variable': 'solutionViewerRunModus', 'grid': [(4, 0), (4, 1), (4, 2)] }, #{'type':'radio', 'textValueList':[('Mesh+Faces',3), ('Faces only',1), ('Mesh only',2)],'value':3, 'variable':'modeShapeMesh', 'grid': [(8,0),(8,1),(8,2)]}, { 'type': 'radio', 'textValueList': [('Record animation', 0), ('No recording', 1)], 'value': 1, 'variable': 'solutionViewerSaveImages', 'grid': [(5, 0), (5, 1)] }, ] mbs.variables['solutionViewerRowIncrement'] = float(rowIncrement) mbs.variables['solutionViewerNSteps'] = nSteps mbs.variables['solutionViewerSolution'] = solution # mbs.variables['solutionViewerStep'] = 0 # mbs.variables['solutionViewerPeriod'] = timeout def UFviewer(mbs, dialog): i = int(mbs.variables['solutionViewerStep']) # mbs.systemData.SetTime(t, exudyn.ConfigurationType.Visualization) SetSolutionState(mainSystem, mbs.variables['solutionViewerSolution'], i, exudyn.ConfigurationType.Visualization) #exudyn.DoRendererIdleTasks(timeout) # SC.visualizationSettings.contour.reduceRange = False mbs.SendRedrawSignal() exudyn.DoRendererIdleTasks( ) #as there is no simulation, we must do this for graphicsDataUserFunctions # if mbs.variables['modeShapeSaveImages'] == 0: # SC.RedrawAndSaveImage() #create images for animation # else: # SC.visualizationSettings.exportImages.saveImageFileCounter = 0 #for next mode ... dialog.period = mbs.variables['solutionViewerPeriod'] if mbs.variables['solutionViewerRunModus'] < 2: mbs.variables['solutionViewerStep'] += mbs.variables[ 'solutionViewerRowIncrement'] # print("step=", mbs.variables['solutionViewerStep']) #first variable is scale, which contains step dialog.variableList[0][0].set(mbs.variables['solutionViewerStep']) # for var in dialog.variableList: # #self.mbs.variables[var[1]] = var[0].get() # print(var[1],'=', var[0].get()) if mbs.variables['solutionViewerSaveImages'] == 0: SC.RedrawAndSaveImage() #create images for animation # else: #do not reset image counter to allow creating of multi-view images, slow motion, etc. # SC.visualizationSettings.exportImages.saveImageFileCounter = 0 # if mbs.variables['solutionViewerStep'] > mbs.variables[ 'solutionViewerNSteps'] - 1.: #or (mbs.variables['solutionViewerRunModus'] and mbs.variables['solutionViewerStep']==mbs.variables['solutionViewerNSteps']-1.): mbs.variables['solutionViewerStep'] = 0 dialog.variableList[0][0].set(0) SetSolutionState(mainSystem, mbs.variables['solutionViewerSolution'], 0, exudyn.ConfigurationType.Visualization) # mbs.SendRedrawSignal() # exudyn.DoRendererIdleTasks() #as there is no simulation, we must do this for graphicsDataUserFunctions if mbs.variables[ 'solutionViewerRunModus'] == 1: #one cylce ==> stop dialog.StartSimulation() #start/stop simulation exudyn.StartRenderer() if 'renderState' in exudyn.sys: SC.SetRenderState(exudyn.sys['renderState']) #load last model view simulationSettings = exudyn.SimulationSettings( ) #not used, but needed in dialog # self.mbs.sys['solver'].InitializeSolver(self.mbs, self.simulationSettings) simulationSettings.solutionSettings.solutionInformation = '' if not SC.visualizationSettings.general.useMultiThreadedRendering: exudyn.DoRendererIdleTasks() #do an update once dialog = InteractiveDialog(mbs, simulationSettings=simulationSettings, simulationFunction=UFviewer, dialogItems=dialogItems, title='Solution Viewer', doTimeIntegration=False, period=timeout, showTime=True, runOnStart=runOnStart) #SC.WaitForRenderEngineStopFlag() #not needed, Render window closes when dialog is quit exudyn.StopRenderer() #safely close rendering window! SC.visualizationSettings.general.graphicsUpdateInterval = oldUpdateInterval #set values back to original
def AnimateModes(systemContainer, mainSystem, nodeNumber, period=0.04, stepsPerPeriod=30, showTime=True, renderWindowText='', runOnStart=False, runMode=0): SC = systemContainer mbs = mainSystem SC.visualizationSettings.general.graphicsUpdateInterval = 0.25 * min( period, 2e-3) #set according update interval! SC.visualizationSettings.general.showSolverTime = showTime #SC.visualizationSettings.general.showComputationInfo = False SC.visualizationSettings.general.showSolverInformation = False SC.visualizationSettings.general.renderWindowString = renderWindowText + 'mode 0' coordIndex = mbs.GetNodeODE2Index(nodeNumber) nodeCoords = mbs.GetNodeOutput(nodeNumber, exudyn.OutputVariableType.Coordinates, exudyn.ConfigurationType.Reference) numberOfModes = len(nodeCoords) #numberOfModes = mbs.GetNode(nODE2)['numberOfODE2Coordinates'] if (runMode != 0 and runMode != 1 and runMode != 2): print('ERROR in AnimateModes: illegal run mode:', runMode) return #use interactive dialog: dialogItems = [ { 'type': 'label', 'text': 'Mode shape:', 'grid': (1, 0) }, { 'type': 'slider', 'range': (0, numberOfModes - 1), 'value': 0, 'steps': numberOfModes, 'variable': 'modeShapeModeNumber', 'grid': (1, 1) }, { 'type': 'label', 'text': 'Contour plot:', 'grid': (2, 0) }, { 'type': 'radio', 'textValueList': [('None', int(exudyn.OutputVariableType._None)), ('DisplacementLocal', int(exudyn.OutputVariableType.DisplacementLocal)), ('Displacement', int(exudyn.OutputVariableType.Displacement)), ('StressLocal', int(exudyn.OutputVariableType.StressLocal)), ('StrainLocal', int(exudyn.OutputVariableType.StrainLocal))], 'value': int(exudyn.OutputVariableType.DisplacementLocal), 'variable': 'modeShapeOutputVariable', 'grid': [(3, 0), (3, 1), (3, 2), (3, 3), (3, 4)] }, { 'type': 'label', 'text': 'Contour Component (use -1 for norm):', 'grid': (4, 0) }, { 'type': 'slider', 'range': (-1, 5), 'value': 0, 'steps': 7, 'variable': 'modeShapeComponent', 'grid': (4, 1) }, { 'type': 'label', 'text': 'Amplitude:', 'grid': (5, 0) }, { 'type': 'slider', 'range': (0, 0.5), 'value': 0.05, 'steps': 501, 'variable': 'modeShapeAmplitude', 'grid': (5, 1) }, { 'type': 'label', 'text': 'update period:', 'grid': (6, 0) }, { 'type': 'slider', 'range': (0.01, 2), 'value': 0.04, 'steps': 200, 'variable': 'modeShapePeriod', 'grid': (6, 1) }, { 'type': 'radio', 'textValueList': [('Continuous run', 0), ('One cycle', 1), ('Static', 2)], 'value': runMode, 'variable': 'modeShapeRunModus', 'grid': [(7, 0), (7, 1), (7, 2)] }, { 'type': 'radio', 'textValueList': [('Mesh+Faces', 3), ('Faces only', 1), ('Mesh only', 2)], 'value': 3, 'variable': 'modeShapeMesh', 'grid': [(8, 0), (8, 1), (8, 2)] }, { 'type': 'radio', 'textValueList': [('Record animation', 0), ('No recording', 1)], 'value': 1, 'variable': 'modeShapeSaveImages', 'grid': [(9, 0), (9, 1)] }, ] mbs.variables['modeShapePeriod'] = period mbs.variables['modeShapeStepsPerPeriod'] = stepsPerPeriod mbs.variables['modeShapeTimeIndex'] = 0 mbs.variables['modeShapeLastSetting'] = [-1, 0, 0, 0] mbs.variables['modeShapeNodeCoordIndex'] = coordIndex def UFshowModes(mbs, dialog): i = mbs.variables['modeShapeTimeIndex'] mbs.variables['modeShapeTimeIndex'] += 1 stepsPerPeriod = mbs.variables['modeShapeStepsPerPeriod'] amplitude = mbs.variables['modeShapeAmplitude'] if amplitude == 0: SC.visualizationSettings.bodies.deformationScaleFactor = 0 amplitude = 1 else: SC.visualizationSettings.bodies.deformationScaleFactor = 1 if mbs.variables['modeShapeRunModus'] == 2: #no sin(t) in static case stepsPerPeriod = 1 t = 0 else: t = i / stepsPerPeriod * 2 * pi amplitude *= sin(t) mbs.systemData.SetTime(t, exudyn.ConfigurationType.Visualization) ode2Coords = mbs.systemData.GetODE2Coordinates() selectedMode = int(mbs.variables['modeShapeModeNumber']) outputVariable = exudyn.OutputVariableType( int(mbs.variables['modeShapeOutputVariable'])) ode2Coords[mbs.variables['modeShapeNodeCoordIndex'] + selectedMode] = amplitude mbs.systemData.SetODE2Coordinates( ode2Coords, exudyn.ConfigurationType.Visualization) SC.visualizationSettings.contour.reduceRange = False #check, if automatic range of contour colors shall be recomputed: if (mbs.variables['modeShapeLastSetting'][0] != int( mbs.variables['modeShapeModeNumber']) or mbs.variables['modeShapeLastSetting'][1] != int( mbs.variables['modeShapeOutputVariable']) or mbs.variables['modeShapeLastSetting'][2] != mbs.variables['modeShapeAmplitude'] or mbs.variables['modeShapeLastSetting'][3] != int( mbs.variables['modeShapeComponent'])): #print("set=",mbs.variables['modeShapeLastSetting']) SC.visualizationSettings.contour.reduceRange = True SC.visualizationSettings.general.renderWindowString = renderWindowText + 'mode ' + str( int(mbs.variables['modeShapeModeNumber'])) mbs.variables['modeShapeLastSetting'] = [ int(mbs.variables['modeShapeModeNumber']), int(mbs.variables['modeShapeOutputVariable']), mbs.variables['modeShapeAmplitude'], int(mbs.variables['modeShapeComponent']) ] SC.visualizationSettings.contour.outputVariable = outputVariable SC.visualizationSettings.contour.outputVariableComponent = int( mbs.variables['modeShapeComponent']) #component SC.visualizationSettings.openGL.showFaces = ( mbs.variables['modeShapeMesh'] & 1) == 1 SC.visualizationSettings.openGL.showFaceEdges = ( mbs.variables['modeShapeMesh'] & 2) == 2 mbs.SendRedrawSignal() if not SC.visualizationSettings.general.useMultiThreadedRendering: exudyn.DoRendererIdleTasks() if mbs.variables['modeShapeSaveImages'] == 0: SC.RedrawAndSaveImage() #create images for animation else: SC.visualizationSettings.exportImages.saveImageFileCounter = 0 #for next mode ... dialog.period = mbs.variables['modeShapePeriod'] if mbs.variables['modeShapeTimeIndex'] >= stepsPerPeriod: mbs.variables['modeShapeTimeIndex'] = 0 if mbs.variables['modeShapeRunModus'] > 0: #one cylce or static dialog.StartSimulation() exudyn.StartRenderer() if 'renderState' in exudyn.sys: SC.SetRenderState(exudyn.sys['renderState']) #load last model view simulationSettings = exudyn.SimulationSettings( ) #not used, but needed in dialog # self.mbs.sys['solver'].InitializeSolver(self.mbs, self.simulationSettings) simulationSettings.solutionSettings.solutionInformation = 'Mode X' if not SC.visualizationSettings.general.useMultiThreadedRendering: exudyn.DoRendererIdleTasks() #do an update once dialog = InteractiveDialog( mbs, simulationSettings=simulationSettings, simulationFunction=UFshowModes, dialogItems=dialogItems, title='Animate mode shapes', doTimeIntegration=False, period=period, showTime=False, #done in UFshowModes runOnStart=runOnStart) #SC.WaitForRenderEngineStopFlag() #not needed, Render window closes when dialog is quit exudyn.StopRenderer() #safely close rendering window!
oGround = mbs.AddObject(ObjectGround(referencePosition=[0, 0, 0])) nGround = mbs.AddNode(NodePointGround(referenceCoordinates=[0, 0, 0])) testError = 1 #set default error, if failed exu.Print("start mini example for class ObjectRotationalMass1D") try: #puts example in safe environment node = mbs.AddNode( Node1D( referenceCoordinates=[1], #\psi_0ref initialCoordinates=[0.5], #\psi_0ini initialVelocities=[0.5])) #\psi_t0ini rotor = mbs.AddObject(Rotor1D(nodeNumber=node, physicsInertia=1)) #assemble and solve system for default parameters mbs.Assemble() SC.TimeIntegrationSolve(mbs, 'GeneralizedAlpha', exu.SimulationSettings()) #check result #check result, get current rotor z-rotation at local position [0,0,0] testError = mbs.GetObjectOutputBody(rotor, exu.OutputVariableType.Rotation, [0, 0, 0]) - 2 #final z-angle of rotor shall be 2 except BaseException as e: exu.Print("An error occured in test example for ObjectRotationalMass1D:", e) else: exu.Print("example for ObjectRotationalMass1D completed, test error =", testError)
def ParameterFunction(parameterSet): SC = exu.SystemContainer() mbs = SC.AddSystem() #default values mass = 1.6 #mass in kg spring = 4000 #stiffness of spring-damper in N/m damper = 8 #old: 8; damping constant in N/(m/s) u0 = -0.08 #initial displacement v0 = 1 #initial velocity force = 80 #force applied to mass #process parameters if 'mass' in parameterSet: mass = parameterSet['mass'] if 'spring' in parameterSet: spring = parameterSet['spring'] if 'force' in parameterSet: force = parameterSet['force'] iCalc = 'Ref' #needed for parallel computation ==> output files are different for every computation if 'computationIndex' in parameterSet: iCalc = str(parameterSet['computationIndex']) #print("computation index=",iCalc, flush=True) L = 0.5 #spring length (for drawing) n1 = mbs.AddNode( Point(referenceCoordinates=[L, 0, 0], initialCoordinates=[u0, 0, 0], initialVelocities=[v0, 0, 0])) #ground node nGround = mbs.AddNode(NodePointGround(referenceCoordinates=[0, 0, 0])) #add mass point (this is a 3D object with 3 coordinates): massPoint = mbs.AddObject(MassPoint(physicsMass=mass, nodeNumber=n1)) #marker for ground (=fixed): groundMarker = mbs.AddMarker( MarkerNodeCoordinate(nodeNumber=nGround, coordinate=0)) #marker for springDamper for first (x-)coordinate: nodeMarker = mbs.AddMarker( MarkerNodeCoordinate(nodeNumber=n1, coordinate=0)) #spring-damper between two marker coordinates nC = mbs.AddObject( CoordinateSpringDamper(markerNumbers=[groundMarker, nodeMarker], stiffness=spring, damping=damper)) #add load: mbs.AddLoad(LoadCoordinate(markerNumber=nodeMarker, load=force)) #add sensor: sensorFileName = 'solution/paramVarDisplacement' + iCalc + '.txt' mbs.AddSensor( SensorObject(objectNumber=nC, fileName=sensorFileName, outputVariableType=exu.OutputVariableType.Displacement)) #print("sensorFileName",sensorFileName) #print(mbs) mbs.Assemble() steps = 100 #number of steps to show solution tEnd = 1 #end time of simulation simulationSettings = exu.SimulationSettings() #simulationSettings.solutionSettings.solutionWritePeriod = 5e-3 #output interval general simulationSettings.solutionSettings.writeSolutionToFile = False simulationSettings.solutionSettings.sensorsWritePeriod = 2e-3 #output interval of sensors simulationSettings.timeIntegration.numberOfSteps = steps simulationSettings.timeIntegration.endTime = tEnd simulationSettings.timeIntegration.generalizedAlpha.spectralRadius = 1 #no damping exu.SolveDynamic(mbs, simulationSettings) #+++++++++++++++++++++++++++++++++++++++++++++++++++++ #evaluate difference between reference and optimized solution #reference solution: dataRef = np.loadtxt('solution/paramVarDisplacementRef.txt', comments='#', delimiter=',') data = np.loadtxt(sensorFileName, comments='#', delimiter=',') diff = data[:, 1] - dataRef[:, 1] errorNorm = np.sqrt(np.dot(diff, diff)) / steps * tEnd if True: #delete files; does not work for parallel, consecutive operation if iCalc != 'Ref': os.remove(sensorFileName) #remove files in order to clean up while (os.path.exists(sensorFileName) ): #wait until file is really deleted -> usually some delay sleep(0.001) #not nice, but there is no other way than that del mbs del SC return errorNorm
def ComputeODE2Eigenvalues(mbs, simulationSettings=exudyn.SimulationSettings(), useSparseSolver=False, numberOfEigenvalues=0, setInitialValues=True, convert2Frequencies=False): import numpy as np #use static solver, as it does not include factors from time integration (and no velocity derivatives) in the jacobian staticSolver = exudyn.MainSolverStatic() #initialize solver with initial values staticSolver.InitializeSolver(mbs, simulationSettings) staticSolver.ComputeMassMatrix(mbs) M = staticSolver.GetSystemMassMatrix() staticSolver.ComputeJacobianODE2RHS( mbs) #compute ODE2 part of jacobian ==> stored internally in solver staticSolver.ComputeJacobianAE( mbs) #compute algebraic part of jacobian (not needed here...) jacobian = staticSolver.GetSystemJacobian() #read out stored jacobian nODE2 = staticSolver.GetODE2size() #obtain ODE2 part from jacobian == stiffness matrix K = jacobian[0:nODE2, 0:nODE2] if not useSparseSolver: from scipy.linalg import eigh #eigh for symmetric matrices, positive definite; eig for standard eigen value problems [eigenValuesUnsorted, eigenVectors ] = eigh(K, M) #this gives omega^2 ... squared eigen frequencies (rad/s) eigenValues = np.sort( a=abs(eigenValuesUnsorted)) #eigh returns unsorted eigenvalues... if numberOfEigenvalues > 0: eigenValues = eigenValues[0:numberOfEigenvalues] eigenVectors = eigenVectors[0:numberOfEigenvalues] else: if numberOfEigenvalues == 0: #compute all eigenvalues numberOfEigenvalues = nODE2 from scipy.sparse.linalg import eigsh, csr_matrix #eigh for symmetric matrices, positive definite Kcsr = csr_matrix(K) Mcsr = csr_matrix(M) #use "LM" (largest magnitude), but shift-inverted mode with sigma=0, to find the zero-eigenvalues: #see https://docs.scipy.org/doc/scipy/reference/tutorial/arpack.html [eigenValues, eigenVectors] = eigsh(A=Kcsr, k=numberOfEigenvalues, M=Mcsr, which='LM', sigma=0, mode='normal') #sort eigenvalues eigenValues = np.sort(a=abs(eigenValues)) if convert2Frequencies: eigenFrequencies = np.sqrt(eigenValues) / (2 * np.pi) return [eigenFrequencies, eigenVectors] else: return [eigenValues, eigenVectors]
def SolveDynamic( mbs, simulationSettings=exudyn.SimulationSettings(), solverType=exudyn.DynamicSolverType.GeneralizedAlpha, updateInitialValues=False, storeSolver=True, showHints=False, showCausingItems=True, ): success = False if (solverType == exudyn.DynamicSolverType.TrapezoidalIndex2 or solverType == exudyn.DynamicSolverType.GeneralizedAlpha): dynamicSolver = exudyn.MainSolverImplicitSecondOrder() if storeSolver: mbs.sys[ 'dynamicSolver'] = dynamicSolver #copy solver structure to sys variable mbs.sys[ 'simulationSettings'] = simulationSettings #link to last simulation settings #if (experimentalNewSolver or #solver flag # ('experimentalNewSolver' in exudyn.sys)): #flag set in test suite # dynamicSolver.experimentalUseSolverNew = True #must be set at the very beginning when MainSolverImplicitSecondOrder() is initialized #store old settings: newmarkOld = simulationSettings.timeIntegration.generalizedAlpha.useNewmark index2Old = simulationSettings.timeIntegration.generalizedAlpha.useIndex2Constraints if solverType == exudyn.DynamicSolverType.TrapezoidalIndex2: #manually override settings for integrator simulationSettings.timeIntegration.generalizedAlpha.useNewmark = True simulationSettings.timeIntegration.generalizedAlpha.useIndex2Constraints = True stat = exudyn.InfoStat(False) success = False try: success = dynamicSolver.SolveSystem(mbs, simulationSettings) except: pass # print(SolverErrorMessage(dynamicSolver, mbs, isStatic=False, showCausingObjects=showCausingItems, # showCausingNodes=showCausingItems, showHints=showHints)) #print(dynamicSolver.conv) # import sys # sys.exit() #produce no further error messages #raise ValueError("SolveDynamic terminated due to errors, see messages above") if not success: print( SolverErrorMessage(dynamicSolver, mbs, isStatic=False, showCausingObjects=showCausingItems, showCausingNodes=showCausingItems, showHints=showHints)) raise ValueError("SolveDynamic terminated") CheckSolverInfoStatistics(dynamicSolver.GetSolverName(), stat, dynamicSolver.it.newtonStepsCount ) #now check if these statistics are ok #restore old settings: simulationSettings.timeIntegration.generalizedAlpha.useNewmark = newmarkOld simulationSettings.timeIntegration.generalizedAlpha.useIndex2Constraints = index2Old elif (solverType == exudyn.DynamicSolverType.ExplicitEuler or solverType == exudyn.DynamicSolverType.ExplicitMidpoint or solverType == exudyn.DynamicSolverType.RK33 or solverType == exudyn.DynamicSolverType.RK44 or solverType == exudyn.DynamicSolverType.RK67 or solverType == exudyn.DynamicSolverType.ODE23 or solverType == exudyn.DynamicSolverType.DOPRI5): simulationSettings.timeIntegration.explicitIntegration.dynamicSolverType = solverType dynamicSolver = exudyn.MainSolverExplicit() if storeSolver: mbs.sys[ 'dynamicSolver'] = dynamicSolver #copy solver structure to sys variable mbs.sys[ 'simulationSettings'] = simulationSettings #link to last simulation settings stat = exudyn.InfoStat(False) success = dynamicSolver.SolveSystem(mbs, simulationSettings) CheckSolverInfoStatistics(dynamicSolver.GetSolverName(), stat, dynamicSolver.it.currentStepIndex * dynamicSolver.GetNumberOfStages() ) #now check if these statistics are ok else: raise ValueError("SolveDynamic: solver type not implemented: ", solverType) if updateInitialValues: currentState = mbs.systemData.GetSystemState() #get current values mbs.systemData.SetSystemState( systemStateList=currentState, configuration=exudyn.ConfigurationType.Initial) mbs.systemData.SetODE2Coordinates_tt( coordinates=mbs.systemData.GetODE2Coordinates_tt(), configuration=exudyn.ConfigurationType.Initial) return success
def ParameterFunction(parameterSet): SC = exu.SystemContainer() mbs = SC.AddSystem() #default values mass = 1.6 #mass in kg spring = 4000 #stiffness of spring-damper in N/m damper = 8 #old: 8; damping constant in N/(m/s) u0 = -0.08 #initial displacement v0 = 1 #initial velocity force = 80 #force applied to mass #process parameters if 'mass' in parameterSet: mass = parameterSet['mass'] if 'spring' in parameterSet: spring = parameterSet['spring'] if 'force' in parameterSet: force = parameterSet['force'] iCalc = 'Ref' #needed for parallel computation ==> output files are different for every computation if 'computationIndex' in parameterSet: iCalc = str(parameterSet['computationIndex']) #print("computation index=",iCalc, flush=True) # else: # print("***********************\nfailed: computationIndex\n***********************\n") #mass-spring-damper system L = 0.5 #spring length (for drawing) # x0=force/spring #static displacement # print('resonance frequency = '+str(np.sqrt(spring/mass))) # print('static displacement = '+str(x0)) #node for 3D mass point: n1 = mbs.AddNode( Point(referenceCoordinates=[L, 0, 0], initialCoordinates=[u0, 0, 0], initialVelocities=[v0, 0, 0])) #ground node nGround = mbs.AddNode(NodePointGround(referenceCoordinates=[0, 0, 0])) #add mass point (this is a 3D object with 3 coordinates): massPoint = mbs.AddObject(MassPoint(physicsMass=mass, nodeNumber=n1)) #marker for ground (=fixed): groundMarker = mbs.AddMarker( MarkerNodeCoordinate(nodeNumber=nGround, coordinate=0)) #marker for springDamper for first (x-)coordinate: nodeMarker = mbs.AddMarker( MarkerNodeCoordinate(nodeNumber=n1, coordinate=0)) #spring-damper between two marker coordinates nC = mbs.AddObject( CoordinateSpringDamper(markerNumbers=[groundMarker, nodeMarker], stiffness=spring, damping=damper)) #add load: mbs.AddLoad(LoadCoordinate(markerNumber=nodeMarker, load=force)) #add sensor: sensorFileName = 'solution/paramVarDisplacement' + iCalc + '.txt' mbs.AddSensor( SensorObject(objectNumber=nC, fileName=sensorFileName, outputVariableType=exu.OutputVariableType.Displacement)) #print("sensorFileName",sensorFileName) #print(mbs) mbs.Assemble() steps = 1000 #number of steps to show solution tEnd = 1 #end time of simulation simulationSettings = exu.SimulationSettings() #simulationSettings.solutionSettings.solutionWritePeriod = 5e-3 #output interval general simulationSettings.solutionSettings.writeSolutionToFile = False simulationSettings.solutionSettings.sensorsWritePeriod = 2e-3 #output interval of sensors simulationSettings.timeIntegration.numberOfSteps = steps simulationSettings.timeIntegration.endTime = tEnd simulationSettings.timeIntegration.generalizedAlpha.spectralRadius = 1 #no damping #exu.StartRenderer() #start graphics visualization #mbs.WaitForUserToContinue() #wait for pressing SPACE bar to continue #start solver: exu.SolveDynamic(mbs, simulationSettings) #SC.WaitForRenderEngineStopFlag()#wait for pressing 'Q' to quit #exu.StopRenderer() #safely close rendering window! # #evaluate final (=current) output values # u = mbs.GetNodeOutput(n1, exu.OutputVariableType.Position) # print('displacement=',u) #+++++++++++++++++++++++++++++++++++++++++++++++++++++ #evaluate difference between reference and optimized solution #reference solution: dataRef = np.loadtxt('solution/paramVarDisplacementRef.txt', comments='#', delimiter=',') data = np.loadtxt(sensorFileName, comments='#', delimiter=',') # s = 50 #shift, for testing what happens if signal has phase-shift # dataRef[0:-s] = dataRef[s:] if not useFFTfitness: diff = data[:, 1] - dataRef[:, 1] errorNorm = np.sqrt(np.dot(diff, diff)) / steps * tEnd #+++++++++++++++++++++++++++++++++++++++++++++++++++++ #draw solution (not during optimization!): if False: import matplotlib.pyplot as plt from matplotlib import ticker #plt.close('all') plt.plot(data[:, 0], data[:, 1], 'b-', label='displacement (m)') ax = plt.gca() # get current axes ax.grid(True, 'major', 'both') ax.xaxis.set_major_locator(ticker.MaxNLocator(10)) ax.yaxis.set_major_locator(ticker.MaxNLocator(10)) plt.legend() #show labels as legend plt.tight_layout() plt.show() else: from exudyn.signal import ComputeFFT tvec = data[:, 0] uvec = data[:, 1] tvecRef = dataRef[:, 0] uvecRef = dataRef[:, 1] [freq, mag, phase] = ComputeFFT(tvec, uvec) [freqRef, magRef, phaseRef] = ComputeFFT(tvecRef, uvecRef) diff = mag - magRef #diff = np.log(abs(mag)) - np.log(abs(magRef)) #does not improve convergence nMag = len(mag) fRange = freq[-1] - freq[ 0] #use frequency range for better reference value # avrgLength = 51 # def runningMeanFast(x, N): # return np.convolve(x, np.ones((N,))/N)[(N-1):] # mag = runningMeanFast(mag, avrgLength) # magRef = runningMeanFast(magRef, avrgLength) errorNorm = np.sqrt(np.dot(diff, diff)) / nMag * fRange # sumV = 0 # p = 2 #higher coefficient has no effect # for v in diff: # sumV += v**p # errorNorm = (sumV**(1/p))/nMag*fRange #higher weight to peaks # #convolution does not work well: # sumV = 0 # for i in range(20,len(mag)-5): # #sumV += -mag[i]*magRef[i] # sumV += -np.log(abs(mag[i])) * np.log(abs(magRef[i])) # errorNorm = sumV/nMag*fRange #higher weight to peaks #+++++++++++++++++++++++++++++++++++++++++++++++++++++ #draw solution (not during optimization!): if False: from exudyn.plot import PlotFFT PlotFFT(freq, mag, label='freq') #, logScaleY=False) PlotFFT(freqRef, magRef, label='freqRef') #, logScaleY=False) if True: #delete files; does not work for parallel, consecutive operation if iCalc != 'Ref': os.remove(sensorFileName) #remove files in order to clean up while (os.path.exists(sensorFileName) ): #wait until file is really deleted -> usually some delay sleep(0.001) #not nice, but there is no other way than that del mbs del SC return errorNorm
def ParameterFunction(parameterSet): s1=L1*0.5 s2=L2*0.5 if False: s1 = s1opt s2 = s2opt if 's1' in parameterSet: s1 = parameterSet['s1'] h=0.002 if 'h' in parameterSet: h = parameterSet['h'] if 's2' in parameterSet: s2 = parameterSet['s2'] iCalc = 'Ref' #needed for parallel computation ==> output files are different for every computation if 'computationIndex' in parameterSet: iCalc = str(parameterSet['computationIndex']) #print("computation index=",iCalc, flush=True) SC = exu.SystemContainer() mbs = SC.AddSystem() testCases = 1 #floating body nGround = mbs.AddNode(NodePointGround(referenceCoordinates=[0,0,0])) #ground node for coordinate constraint mGround = mbs.AddMarker(MarkerNodeCoordinate(nodeNumber = nGround, coordinate=0)) #Ground node ==> no action #++++++++++++++++++++++++++++++++ #floating body to mount slider-crank mechanism constrainGroundBody = (testCases == 0) #use this flag to fix ground body #graphics for floating frame: gFloating = GraphicsDataOrthoCube(-0.25, -0.25, -0.1, 0.8, 0.25, -0.05, color=[0.3,0.3,0.3,1.]) if constrainGroundBody: floatingRB = mbs.AddObject(ObjectGround(referencePosition=[0,0,0], visualization=VObjectGround(graphicsData=[gFloating]))) mFloatingN = mbs.AddMarker(MarkerBodyPosition(bodyNumber = floatingRB, localPosition=[0,0,0])) else: nFloating = mbs.AddNode(Rigid2D(referenceCoordinates=[0,0,0], initialVelocities=[0,0,0])); mFloatingN = mbs.AddMarker(MarkerNodePosition(nodeNumber=nFloating)) floatingRB = mbs.AddObject(RigidBody2D(physicsMass=2, physicsInertia=1, nodeNumber=nFloating, visualization=VObjectRigidBody2D(graphicsData=[gFloating]))) mRB0 = mbs.AddMarker(MarkerNodeCoordinate(nodeNumber = nFloating, coordinate=0)) mRB1 = mbs.AddMarker(MarkerNodeCoordinate(nodeNumber = nFloating, coordinate=1)) mRB2 = mbs.AddMarker(MarkerNodeCoordinate(nodeNumber = nFloating, coordinate=2)) #add spring dampers for reference frame: k=5000 #stiffness of floating body d=k*0.01 mbs.AddObject(CoordinateSpringDamper(markerNumbers=[mGround,mRB0], stiffness=k, damping=d)) mbs.AddObject(CoordinateSpringDamper(markerNumbers=[mGround,mRB1], stiffness=k, damping=d)) mbs.AddObject(CoordinateSpringDamper(markerNumbers=[mGround,mRB2], stiffness=k, damping=d)) mbs.AddObject(CoordinateConstraint(markerNumbers=[mGround,mRB2])) #++++++++++++++++++++++++++++++++ #nodes and bodies omega=2*pi/60*300 #3000 rpm M=0.1 #torque (default: 0.1) s1L=-s1 s1R=L1-s1 s2L=-s2 s2R=L2-s2 #lambda=L1/L2 J1=(m1/12.)*L1**2 #inertia w.r.t. center of mass J2=(m2/12.)*L2**2 #inertia w.r.t. center of mass ty = 0.05 #thickness tz = 0.05 #thickness graphics1 = GraphicsDataRigidLink(p0=[s1L,0,-0.5*tz],p1=[s1R,0,-0.5*tz], axis0=[0,0,1], axis1=[0,0,1],radius=[0.5*ty,0.5*ty], thickness=0.8*ty, width=[tz,tz], color=color4steelblue,nTiles=16) graphics2 = GraphicsDataRigidLink(p0=[s2L,0,0.5*tz],p1=[s2R,0,0.5*tz], axis0=[0,0,1], axis1=[0,0,1],radius=[0.5*ty,0.5*ty], thickness=0.8*ty, width=[tz,tz], color=color4lightred,nTiles=16) #crank: nRigid1 = mbs.AddNode(Rigid2D(referenceCoordinates=[s1,0,0], initialVelocities=[0,0,0])); oRigid1 = mbs.AddObject(RigidBody2D(physicsMass=m1, physicsInertia=J1, nodeNumber=nRigid1, visualization=VObjectRigidBody2D(graphicsData= [graphics1]))) #connecting rod: nRigid2 = mbs.AddNode(Rigid2D(referenceCoordinates=[L1+s2,0,0], initialVelocities=[0,0,0])); oRigid2 = mbs.AddObject(RigidBody2D(physicsMass=m2, physicsInertia=J2, nodeNumber=nRigid2, visualization=VObjectRigidBody2D(graphicsData= [graphics2]))) #++++++++++++++++++++++++++++++++ #slider: c=0.025 #dimension of mass graphics3 = GraphicsDataOrthoCube(-c,-c,-c*2,c,c,0,color4grey) #nMass = mbs.AddNode(Point2D(referenceCoordinates=[L1+L2,0])) #oMass = mbs.AddObject(MassPoint2D(physicsMass=m3, nodeNumber=nMass,visualization=VObjectMassPoint2D(graphicsData= [graphics3]))) nMass = mbs.AddNode(Rigid2D(referenceCoordinates=[L1+L2,0,0])) oMass = mbs.AddObject(RigidBody2D(physicsMass=m3, physicsInertia=0.001*m3, nodeNumber=nMass,visualization=VObjectRigidBody2D(graphicsData= [graphics3]))) #++++++++++++++++++++++++++++++++ #markers for joints: mR1Left = mbs.AddMarker(MarkerBodyRigid(bodyNumber=oRigid1, localPosition= [s1L,0.,0.])) #support point # MUST be a rigidBodyMarker, because a torque is applied mR1Right = mbs.AddMarker(MarkerBodyPosition(bodyNumber=oRigid1, localPosition=[s1R,0.,0.])) #end point; connection to connecting rod mR2Left = mbs.AddMarker(MarkerBodyPosition(bodyNumber=oRigid2, localPosition= [s2L,0.,0.])) #connection to crank mR2Right = mbs.AddMarker(MarkerBodyPosition(bodyNumber=oRigid2, localPosition=[s2R,0.,0.])) #end point; connection to slider mMass = mbs.AddMarker(MarkerBodyPosition(bodyNumber=oMass, localPosition=[ 0.,0.,0.])) mG0 = mFloatingN #++++++++++++++++++++++++++++++++ #joints: mbs.AddObject(RevoluteJoint2D(markerNumbers=[mG0,mR1Left])) mbs.AddObject(RevoluteJoint2D(markerNumbers=[mR1Right,mR2Left])) mbs.AddObject(RevoluteJoint2D(markerNumbers=[mR2Right,mMass])) #prismatic joint: mRigidGround = mbs.AddMarker(MarkerBodyRigid(bodyNumber = floatingRB, localPosition = [L1+L2,0,0])) mRigidSlider = mbs.AddMarker(MarkerBodyRigid(bodyNumber = oMass, localPosition = [0,0,0])) mbs.AddObject(PrismaticJoint2D(markerNumbers=[mRigidGround,mRigidSlider], constrainRotation=True)) #user function for load; switch off load after 1 second userLoadOn = True def userLoad(mbs, t, load): setLoad = 0 if userLoadOn: setLoad = load omega = mbs.GetNodeOutput(nRigid1,variableType = exu.OutputVariableType.AngularVelocity)[2] if omega > 2*pi*2: #print("t=",t) userLoadOn = False return setLoad #loads and driving forces: mRigid1CoordinateTheta = mbs.AddMarker(MarkerNodeCoordinate(nodeNumber = nRigid1, coordinate=2)) #angle coordinate is constrained #mbs.AddLoad(LoadCoordinate(markerNumber=mRigid1CoordinateTheta, load = M, loadUserFunction=userLoad)) #torque at crank mbs.AddLoad(LoadCoordinate(markerNumber=mRigid1CoordinateTheta, load = M)) #torque at crank #write motion of support frame: sensorFileName = 'solution/floatingPos'+iCalc+'.txt' sFloating = mbs.AddSensor(SensorNode(nodeNumber=nFloating, fileName=sensorFileName, outputVariableType=exu.OutputVariableType.Position)) #++++++++++++++++++++++++++++++++ #assemble, adjust settings and start time integration mbs.Assemble() simulationSettings = exu.SimulationSettings() #takes currently set values or default values tEnd = 3 simulationSettings.timeIntegration.numberOfSteps = int(tEnd/h) simulationSettings.timeIntegration.endTime = tEnd #simulationSettings.timeIntegration.newton.relativeTolerance = 1e-8 #10000 #simulationSettings.timeIntegration.verboseMode = 1 #10000 simulationSettings.solutionSettings.solutionWritePeriod = 2e-3 simulationSettings.solutionSettings.writeSolutionToFile = useGraphics simulationSettings.timeIntegration.newton.useModifiedNewton = True simulationSettings.timeIntegration.newton.relativeTolerance = 1e-8 simulationSettings.timeIntegration.newton.absoluteTolerance = 1e-8 #++++++++++++++++++++++++++++++++++++++++++ #solve index 2 / trapezoidal rule: simulationSettings.timeIntegration.generalizedAlpha.useNewmark = True simulationSettings.timeIntegration.generalizedAlpha.useIndex2Constraints = True dSize = 0.02 SC.visualizationSettings.nodes.defaultSize = dSize SC.visualizationSettings.markers.defaultSize = dSize SC.visualizationSettings.bodies.defaultSize = [dSize, dSize, dSize] SC.visualizationSettings.connectors.defaultSize = dSize #data obtained from SC.GetRenderState(); use np.round(d['modelRotation'],4) SC.visualizationSettings.openGL.initialModelRotation = [[ 0.87758, 0.04786, -0.47703], [ 0. , 0.995 , 0.09983], [ 0.47943, -0.08761, 0.8732]] SC.visualizationSettings.openGL.initialZoom = 0.47 SC.visualizationSettings.openGL.initialCenterPoint = [0.192, -0.0039,-0.075] SC.visualizationSettings.openGL.initialMaxSceneSize = 0.4 SC.visualizationSettings.general.autoFitScene = False #mbs.WaitForUserToContinue() if useGraphics: exu.StartRenderer() exu.SolveDynamic(mbs, simulationSettings) if useGraphics: #+++++++++++++++++++++++++++++++++++++ #animate solution # mbs.WaitForUserToContinue # fileName = 'coordinatesSolution.txt' # solution = LoadSolutionFile('coordinatesSolution.txt') # AnimateSolution(mbs, solution, 10, 0.025, True) #+++++++++++++++++++++++++++++++++++++ SC.WaitForRenderEngineStopFlag() exu.StopRenderer() #safely close rendering window! #++++++++++++++++++++++++++++++++++++++++++ #evaluate error: data = np.loadtxt(sensorFileName, comments='#', delimiter=',') errorNorm = max(abs(data[:,1])) + max(abs(data[:,2])) #max displacement in x and y direction #++++++++++++++++++++++++++++++++++++++++++ #clean up optimization if True: #delete files; does not work for parallel, consecutive operation if iCalc != 'Ref': os.remove(sensorFileName) #remove files in order to clean up while(os.path.exists(sensorFileName)): #wait until file is really deleted -> usually some delay sleep(0.001) #not nice, but there is no other way than that if useGraphics: print("max. oszillation=", errorNorm) from exudyn.plot import PlotSensor PlotSensor(mbs, sensorNumbers=[sFloating,sFloating], components=[0,1]) del mbs del SC return errorNorm