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 RunSimulationPeriod(self): cnt = self.counter deltaT = self.period h = self.stepSize mbs = self.mbs #+++++++++++++++++++++++++++++++++++++++++ #this is the USER PART self.simulationFunction(self.mbs, self) #+++++++++++++++++++++++++++++++++++++++++ if self.doTimeIntegration and False: #slow way, always start/stop simulation: self.simulationSettings.timeIntegration.numberOfSteps = int( deltaT / h) self.simulationSettings.timeIntegration.endTime = self.simulationSettings.timeIntegration.startTime + deltaT exudyn.SolveDynamic(mbs, self.simulationSettings, updateInitialValues=True) self.simulationSettings.timeIntegration.startTime += deltaT #+++++++++++++++++++++++++++++++++++++++++ #PLOT PART, done every time before simulation starts self.UpdatePlots() #+++++++++++++++++++++++++++++++++++++++++ #TIME STEPPING PART if self.doTimeIntegration and True: self.simulationSettings.timeIntegration.numberOfSteps = int( deltaT / h) self.simulationSettings.timeIntegration.endTime = self.simulationSettings.timeIntegration.startTime + deltaT mbs.sys['solver'].InitializeSolverInitialConditions( mbs, self.simulationSettings ) #needed to update simulationSettings in solver mbs.sys['solver'].SolveSteps(mbs, self.simulationSettings) #get current values and update initial conditions for next step: currentState = mbs.systemData.GetSystemState() mbs.systemData.SetSystemState( systemStateList=currentState, configuration=exudyn.ConfigurationType.Initial) self.simulationSettings.timeIntegration.startTime += deltaT return self.simulationSettings.timeIntegration.endTime #return current time for dialog
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
simulationSettings.timeIntegration.newton.useModifiedNewton = True simulationSettings.timeIntegration.generalizedAlpha.useIndex2Constraints = False simulationSettings.timeIntegration.generalizedAlpha.useNewmark = False simulationSettings.timeIntegration.generalizedAlpha.spectralRadius = 0.6 #0.6 works well simulationSettings.solutionSettings.solutionInformation = "rigid body tests" SC.visualizationSettings.nodes.defaultSize = 0.05 simulationSettings.displayComputationTime = False #simulationSettings.displayStatistics = True if exudynTestGlobals.useGraphics: exu.StartRenderer() mbs.WaitForUserToContinue() exu.SolveDynamic(mbs, simulationSettings) #, experimentalNewSolver=True) #+++++++++++++++++++++++++++++++++++++++++++++ #compute TestModel error for EulerParameters and index2 solver pos = mbs.GetObjectOutputBody(oRB, exu.OutputVariableType.Position, localPosition=[0, 0, 0]) exu.Print('pos=', pos) u = 0 for i in range(3): #take sum of all coordinates u += abs(pos[i]) exu.Print('solution of GenericJointTest=', u) exudynTestGlobals.testError = u - (1.1878327690760586 ) #2020-04-22: 1.1878327690760586
groundMarker = mbs.AddMarker( MarkerNodeCoordinate(nodeNumber=nGround, coordinate=0)) nodeMarker = mbs.AddMarker( MarkerNodeCoordinate(nodeNumber=nMass, coordinate=0)) #Spring-Damper between two marker coordinates mbs.AddObject( CoordinateSpringDamper(markerNumbers=[groundMarker, nodeMarker], stiffness=5000, damping=80, springForceUserFunction=springForce)) loadCoord = mbs.AddLoad(LoadCoordinate( markerNumber=nodeMarker, load=1)) #static linear solution:0.002 #assemble and solve system for default parameters mbs.Assemble() exu.SolveDynamic(mbs) #check result at default integration time exudynTestGlobals.testResult = mbs.GetNodeOutput( nMass, exu.OutputVariableType.Displacement)[0] except BaseException as e: exu.Print( "An error occured in test example for ObjectConnectorCoordinateSpringDamper:", e) else: exu.Print( "example for ObjectConnectorCoordinateSpringDamper 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 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
simulationSettings = exu.SimulationSettings() #takes currently set values or default values tEnd = 4 #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.window.renderWindowSize=[1600,1200] SC.visualizationSettings.openGL.multiSampling = 4 SC.visualizationSettings.general.autoFitScene = False 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) SC.WaitForRenderEngineStopFlag() #stop before closing exu.StopRenderer() #safely close rendering window! if True: from exudyn.plot import PlotSensor PlotSensor(mbs, [sens1],[1])
M = np.block([[mass, 0. * np.eye(3)], [0. * np.eye(3), mass]]) K = np.block([[2 * stif, -stif], [-stif, stif]]) D = np.block([[2 * damp, -damp], [-damp, damp]]) oGenericODE2 = mbs.AddObject( ObjectGenericODE2(nodeNumbers=[nMass0, nMass1], massMatrix=M, stiffnessMatrix=K, dampingMatrix=D)) mNode1 = mbs.AddMarker(MarkerNodePosition(nodeNumber=nMass1)) mbs.AddLoad(Force( markerNumber=mNode1, loadVector=[10, 0, 0])) #static solution=10*(1/5000+1/5000)=0.0004 #assemble and solve system for default parameters mbs.Assemble() exu.SolveDynamic(mbs, solverType=exudyn.DynamicSolverType.TrapezoidalIndex2) #check result at default integration time exudynTestGlobals.testResult = mbs.GetNodeOutput( nMass1, exu.OutputVariableType.Position)[0] except BaseException as e: exu.Print("An error occured in test example for ObjectGenericODE2:", e) else: exu.Print("example for ObjectGenericODE2 completed, test error =", testError)
simulationSettings.displayStatistics = True simulationSettings.linearSolverType = exu.LinearSolverType.EigenSparse #simulationSettings.linearSolverType = exu.LinearSolverType.EXUdense #simulationSettings.numberOfThreads = 1 #not available for eigen LU sparse matrix solver SC.visualizationSettings.nodes.show = True SC.visualizationSettings.bodies.show = False SC.visualizationSettings.loads.show = False SC.visualizationSettings.markers.show = False SC.visualizationSettings.nodes.defaultSize = 0.2 * 2 SC.visualizationSettings.contour.outputVariable = exu.OutputVariableType.Displacement SC.visualizationSettings.contour.outputVariableComponent = 0 #y-component exu.SolveDynamic(mbs, simulationSettings, solverType=exudyn.DynamicSolverType.ExplicitMidpoint) #u = mbs.GetNodeOutput(nBodies-2, exu.OutputVariableType.Position) #tip node #print('dynamic tip displacement (y)=', u[1]) #dense: -11.085967426937412, sparse:-11.085967426937431 simulationSettings.staticSolver.newton.numericalDifferentiation.relativeEpsilon = 1e-7 simulationSettings.staticSolver.newton.relativeTolerance = 1e-6 * 1e5 # make this large for linear computation simulationSettings.staticSolver.newton.absoluteTolerance = 1e-1 simulationSettings.staticSolver.verboseMode = 1 exu.SolveStatic(mbs, simulationSettings) u = mbs.GetNodeOutput(nBodies - 2, exu.OutputVariableType.Position) #tip node print('static tip displacement (y)=', u[1]) staticError = u[1] - (-0.44056224799446486)
# SC.visualizationSettings.general.drawCoordinateSystem=False SC.visualizationSettings.general.autoFitScene = False #use loaded render state useGraphics = True if useGraphics: simulationSettings.displayComputationTime = True simulationSettings.displayStatistics = True exu.StartRenderer() if 'renderState' in exu.sys: SC.SetRenderState(exu.sys['renderState']) #mbs.WaitForUserToContinue() else: simulationSettings.solutionSettings.writeSolutionToFile = False #exu.SolveDynamic(mbs, simulationSettings, solverType=exu.DynamicSolverType.TrapezoidalIndex2) exu.SolveDynamic(mbs, simulationSettings, showHints=True) if True: #use this to reload the solution and use SolutionViewer from exudyn.interactive import SolutionViewer SolutionViewer(mbs, runMode=2, runOnStart=True) u0 = mbs.GetNodeOutput(nRB, exu.OutputVariableType.Displacement) rot0 = mbs.GetNodeOutput(nRB, exu.OutputVariableType.Rotation) exu.Print('u0=', u0, ', rot0=', rot0) result = (abs(u0) + abs(rot0)).sum() exu.Print('solution of addRevoluteJoint=', result) # exudynTestGlobals.testError = result - (1.2538806799246283) #2020-07-01: 1.2538806799246283 # exudynTestGlobals.testResult = result
if False: #record animation frames: SC.visualizationSettings.exportImages.saveImageFileName = "animation/frame" SC.visualizationSettings.window.renderWindowSize=[1600,1024] SC.visualizationSettings.openGL.multiSampling = 4 simulationSettings.solutionSettings.recordImagesInterval = 0.02 SC.visualizationSettings.general.autoFitScene = False #use loaded render state useGraphics = True if useGraphics: exu.StartRenderer() if 'renderState' in exu.sys: SC.SetRenderState(exu.sys[ 'renderState' ]) mbs.WaitForUserToContinue() exu.SolveDynamic(mbs, simulationSettings, solverType=exu.DynamicSolverType.TrapezoidalIndex2) exu.SolveDynamic(mbs, simulationSettings, showHints=True) #%%+++++++++++++++++++++++++++++ if useGraphics: SC.WaitForRenderEngineStopFlag() exu.StopRenderer() #safely close rendering window! #%%++++++++++++++++++++++++++++++++++++++++++++++q+++++++ if addSensors: #plot results from exudyn.plot import PlotSensor import matplotlib.pyplot as plt
if True: #check automatic step size control #sims.timeIntegration.verboseMode = 1 for i in range(6 - 2 * offset): #sims.solutionSettings.writeSolutionToFile = True #sims.solutionSettings.solutionWritePeriod = 0 tEnd = 2 h = 1 sims.timeIntegration.numberOfSteps = int(tEnd / h) sims.timeIntegration.endTime = tEnd #sims.timeIntegration.initialStepSize = 1e-5 sims.timeIntegration.absoluteTolerance = 10**(-2 * i) sims.timeIntegration.relativeTolerance = 1e-4 solverType = exu.DynamicSolverType.DOPRI5 exu.SolveDynamic(mbs, solverType=solverType, simulationSettings=sims) if printResults: exu.Print( str(solverType) + ", h=" + str(h) + ", tol=" + str(sims.timeIntegration.absoluteTolerance), ", val=", mbs.GetSensorValues(sCoords1)[0] - ref) #exu.Print(mbs.GetSensorValues(sCoords1),mbs.GetSensorValues(sCoords2)) err += abs(mbs.GetSensorValues(sCoords1)[0] - ref) + abs(mbs.GetSensorValues(sCoords2)[0] - ref) if True: #check orders: if printResults: exu.Print("RK67:") for i in range(3 - offset): h = 1e-1 * 10**-i sims.timeIntegration.numberOfSteps = int(tEnd / h)
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)
try: #puts example in safe environment #example with 1m pendulum, 50kg under gravity nMass = mbs.AddNode(NodePoint2D(referenceCoordinates=[1, 0])) oMass = mbs.AddObject(MassPoint2D(physicsMass=50, nodeNumber=nMass)) mMass = mbs.AddMarker(MarkerNodePosition(nodeNumber=nMass)) mGround = mbs.AddMarker( MarkerBodyPosition(bodyNumber=oGround, localPosition=[0, 0, 0])) oDistance = mbs.AddObject( DistanceConstraint(markerNumbers=[mGround, mMass], distance=1)) mbs.AddLoad(Force(markerNumber=mMass, loadVector=[0, -50 * 9.81, 0])) #assemble and solve system for default parameters mbs.Assemble() sims = exu.SimulationSettings() sims.timeIntegration.generalizedAlpha.spectralRadius = 0.7 exu.SolveDynamic(mbs, sims) #check result at default integration time exudynTestGlobals.testResult = mbs.GetNodeOutput( nMass, exu.OutputVariableType.Position)[0] except BaseException as e: exu.Print("An error occured in test example for ObjectConnectorDistance:", e) else: exu.Print("example for ObjectConnectorDistance completed, test error =", testError)
#set up a 2-DOF system nODE1 = mbs.AddNode( NodeGenericODE1(referenceCoordinates=[0, 0], initialCoordinates=[1, 0], numberOfODE1Coordinates=2)) #build system matrix and force vector #undamped mechanical system with m=1, K=100, f=1 A = np.array([[0, 1], [-100, 0]]) b = np.array([0, 1]) oGenericODE1 = mbs.AddObject( ObjectGenericODE1(nodeNumbers=[nODE1], systemMatrix=A, rhsVector=b)) #assemble and solve system for default parameters mbs.Assemble() sims = exu.SimulationSettings() solverType = exu.DynamicSolverType.RK44 exu.SolveDynamic(mbs, solverType=solverType, simulationSettings=sims) #check result at default integration time exudynTestGlobals.testResult = mbs.GetNodeOutput( nODE1, exu.OutputVariableType.Coordinates)[0] except BaseException as e: exu.Print("An error occured in test example for ObjectGenericODE1:", e) else: exu.Print("example for ObjectGenericODE1 completed, test error =", testError)
objectDict = {"objectType": "ConnectorSpringDamper", "markerNumbers": [markerNumberOfPositionMarkerL, markerNumberOfPositionMarkerR], "stiffness": elementStiffness, "damping": elementDamping, "force": 0, "referenceLength": springDamperDiagnoalElementLength, "activeConnector": activateElement, "name": springDamperElementName, "VdrawSize": 0.0} mbs.AddObject(objectDict) elementCtr = elementCtr + 1 ctr1 = ctr1 + 1 ####################### assemble and solve mbs ############################### mbs.Assemble() #print(mbs) exu.StartRenderer() exu.SolveDynamic(mbs, simulationSettings, solverType = exudyn.DynamicSolverType.ODE23) SC.WaitForRenderEngineStopFlag() exu.StopRenderer() #safely close rendering window!
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
success = exu.SolveStatic(mbs, simulationSettings, updateInitialValues=True) #turn on moving beam: mbs.SetObjectParameter(oCCvALE, 'activeConnector', True) mbs.SetObjectParameter(oCCvALE, 'velocityLevel', True) mbs.SetObjectParameter(oCCvALE, 'offset', vALE0) #%%+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #turn on vALE velocity (could also be done in modifying coordinates): #rope decelerates due to gravity and then runs backwards simulationSettings.timeIntegration.numberOfSteps = int(1/h) simulationSettings.timeIntegration.endTime = 1 success = exu.SolveDynamic(mbs, simulationSettings, exudyn.DynamicSolverType.TrapezoidalIndex2, updateInitialValues=True) mbs.systemData.SetODE2Coordinates_tt(coordinates = mbs.systemData.GetODE2Coordinates_tt(), configuration = exudyn.ConfigurationType.Initial) if useGraphics: mbs.WaitForUserToContinue() #%%+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #finally: solve dynamic problem under self weight mbs.SetObjectParameter(oCCvALE, 'activeConnector', False) #rope under self-weight mbs.SetObjectParameter(oCCvALE, 'velocityLevel', False) mbs.SetObjectParameter(oCCvALE, 'offset', 0) simulationSettings.timeIntegration.numberOfSteps = int(tEnd/h) simulationSettings.timeIntegration.startTime = 1
solveDynamic = True if solveDynamic: # time related settings: steps = 400 tend = 0.8 h = tend / steps SC.visualizationSettings.openGL.lineWidth = 2 simulationSettings.timeIntegration.numberOfSteps = steps simulationSettings.timeIntegration.endTime = tend simulationSettings.timeIntegration.generalizedAlpha.useIndex2Constraints = True simulationSettings.timeIntegration.generalizedAlpha.useNewmark = simulationSettings.timeIntegration.generalizedAlpha.useIndex2Constraints simulationSettings.timeIntegration.generalizedAlpha.spectralRadius = 0.3 simulationSettings.timeIntegration.verboseMode = 1 simulationSettings.displayStatistics = True exu.SolveDynamic(mbs, simulationSettings) if exudynTestGlobals.useGraphics: #SC.WaitForRenderEngineStopFlag() exu.StopRenderer() #safely close rendering window! sol = mbs.systemData.GetODE2Coordinates() uDynamic = sol[nc] #y-displacement of first node of four bar mechanism exu.Print('dynamic solution of cable1 =', uDynamic) exudynTestGlobals.testError += uDynamic - ( -2.2290811574753953 ) #2020-03-05(corrected Cable2DshapeMarker): -2.2290811574753953 #2019-12-26: -2.2290811558815617; 2019-12-18: -2.229126333291627 exudynTestGlobals.testResult += uDynamic
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