def createScene(rootNode): from splib.animation import animate from stlib.scene import Scene import math scene = Scene(rootNode) scene.VisualStyle.displayFlags = "showBehavior" rootNode.dt = 0.003 rootNode.gravity = [0., -9810., 0.] simulation = rootNode.createChild("Simulation") simulation.createObject("EulerImplicitSolver", rayleighStiffness=0.1, rayleighMass=0.1) simulation.createObject("CGLinearSolver", name="precond") arm = ActuatedArm(simulation, name="ActuatedArm", translation=[0.0, 0.0, 0.0]) def myanimate(target, factor): target.angle = math.cos(factor * 2 * math.pi) target.setX(math.cos(factor * 2 * math.pi)) animate(myanimate, {"target": arm.servomotor}, duration=5, mode="loop")
def createScene(rootNode): import math def animation(target, factor): target.angleIn = math.cos(factor * 2 * math.pi) Scene(rootNode) rootNode.dt = 0.003 rootNode.gravity = [0., -9810., 0.] rootNode.createObject("VisualStyle", displayFlags="showBehaviorModels") # Use these components on top of the scene to solve the constraint "StopperConstraint". rootNode.createObject("FreeMotionAnimationLoop") rootNode.createObject("GenericConstraintSolver", maxIterations=1e3, tolerance=1e-5) simulation = rootNode.createChild("Simulation") simulation.createObject("EulerImplicitSolver", rayleighStiffness=0.1, rayleighMass=0.1) simulation.createObject("CGLinearSolver", name="precond") ServoMotor(simulation, showWheel=True) animate(animation, {"target": simulation.ServoMotor}, duration=5., mode="loop") return rootNode
def createScene(rootNode): from splib.animation import animate from fixingbox import FixingBox import math scene = Scene(rootNode) scene.VisualStyle.displayFlags = "showBehavior" tripod = Tripod(scene.Modelling) FixingBox(tripod, tripod.ElasticBody.ElasticMaterialObject, scale=[10, 10, 10], translation=[0., 25, 0.]) tripod.FixingBox.BoxROI.drawBoxes = True scene.Simulation.addChild(tripod.RigidifiedStructure) scene.Simulation.addChild(tripod.ActuatedArm0) scene.Simulation.addChild(tripod.ActuatedArm1) scene.Simulation.addChild(tripod.ActuatedArm2) def myanimate(targets, factor): for arm in targets: arm.ServoMotor.angleIn = -factor * math.pi / 4. animate(myanimate, { "targets": [tripod.ActuatedArm0, tripod.ActuatedArm1, tripod.ActuatedArm2] }, duration=1)
def createScene(rootNode): import math def animation(target, factor): target.angle = math.cos(factor * 2 * math.pi) target.setX(math.cos(factor * 2 * math.pi)) Scene(rootNode) rootNode.dt = 0.003 rootNode.gravity = [0., -9810., 0.] rootNode.createObject("VisualStyle", displayFlags="showBehaviorModels") # Use these components on top of the scene to solve the constraint "StopperConstraint". rootNode.createObject("FreeMotionAnimationLoop") rootNode.createObject("GenericConstraintSolver", maxIterations=1e3, tolerance=1e-5) simulation = rootNode.createChild("Simulation") simulation.createObject("EulerImplicitSolver", rayleighStiffness=0.1, rayleighMass=0.1) simulation.createObject("CGLinearSolver", name="precond") servomotor = ServoMotor(simulation, showWheel=True) animate(animation, {"target": servomotor}, duration=5., mode="loop") return rootNode
def initTripod(self, key): if key == Key.A: animate(setupanimation, { "actuators": self.actuators, "step": 35.0, "angularstep": -1.4965 }, duration=0.2)
def saveElements(node,dt,forcefield): ''' **Depending on the forcefield will go search for the right kind of elements (tetrahedron/triangles...) to save** +------------+-----------+-------------------------------------------------------------------------+ | argument | type | definition | +============+===========+=========================================================================+ | node | Sofa.node | from which node will search to save elements | +------------+-----------+-------------------------------------------------------------------------+ | dt | sc | time step of our SOFA scene | +------------+-----------+-------------------------------------------------------------------------+ | forcefield | list(str) || list of path to the forcefield working on the elements we want to save | | | || see :py:obj:`.forcefield` | +------------+-----------+-------------------------------------------------------------------------+ After determining what to save we will add an animation with a *duration* of 0 that will be executed only once when the scene is launched saving the elements. To do that we use :py:func:`splib.animation.animate` **of the** `STLIB <https://github.com/SofaDefrost/STLIB>`_ **SOFA plugin** ''' import numpy as np # print('---------------------> Gonna Try to Save the Elements') def save(node,container,valueType, **param): global tmp elements = container.findData(valueType).value np.savetxt('reducedFF_'+ node.name + '_' + str(tmp)+'_'+valueType+'_elmts.txt', elements,fmt='%i') tmp += 1 print('save : '+'elmts_'+node.name+' from '+container.name+' with value Type '+valueType) # print('---------------------> ',forcefield) for objPath in forcefield: nodePath = '/'.join(objPath.split('/')[:-1]) # print(nodePath,objPath) obj = get(node,objPath[1:]) currentNode = get(node,nodePath[1:]) if obj.getClassName() == 'HyperReducedRestShapeSpringsForceField': container = obj elif obj.getClassName() == 'HyperReducedHexahedronFEMForceField': container = searchObjectClassInGraphScene(currentNode,'RegularGridTopology')[0] else: container = getContainer(currentNode) # print(container) if obj.getClassName() in forceFieldImplemented and container: valueType = forceFieldImplemented[obj.getClassName()] # print('---------------------> ',valueType) if valueType: animate(save, {"node" : currentNode ,'container' : container, 'valueType' : valueType, 'startTime' : 0}, 0)
def onKeyPressed(self, key): if key == Key.A and self.serialportctrl.state == "init": self.serialportctrl.state = "no-comm" animate(setupanimation, { "actuators": self.actuators, "step": 3.0, "angularstep": -0.14 }, duration=0.2) # Inclusion of the keystroke to start data sending = establishing communication ('comm') if key == Key.B and self.serialportctrl.state == "no-comm": self.serialportctrl.state = "comm"
def createScene(rootNode): from splib.animation import animate from splib.animation.easing import LinearRamp from splib.scenegraph import get from stlib.scene import MainHeader scene = Scene(rootNode) s = DefaultSolver(rootNode) # Test a assembly that also implements a KinematicMotorController # The angle of the KinematicMotorController is dynamically changed using a # animation function servomotor = ServoMotor(rootNode, translation=[2, 0, 0]) def myAnimation(motorctrl, factor): motorctrl.angle = LinearRamp(-3.14/2, 3.14/2, factor) animate(myAnimation, {"motorctrl" : servomotor.node }, duration=1.0, mode="pingpong")
def createScene(rootNode): from splib.animation import animate from stlib.scene import Scene scene = Scene(rootNode) scene.createObject("EulerImplicitSolver") scene.createObject("SparseLDLSolver") scene.VisualStyle.displayFlags = "showBehavior" arm1 = ActuatedArm(scene, name="arm1", translation=[-2.0, 0.0, 0.0]) arm1.createObject("FixedConstraint") def myanimate(target, factor): target.angle = factor animate(myanimate, {"target": arm1.ServoMotor}, duration=0.5, mode="pingpong")
def saveElements(rootNode, dt, forcefield): import numpy as np def save(node, container, valueType, **param): global tmp elements = container.findData(valueType).value np.savetxt('reducedFF_' + node.name + '_' + str(tmp) + '_' + valueType + '_elmts.txt', elements, fmt='%i') tmp += 1 print('save : ' + 'elmts_' + node.name + ' from ' + container.name + ' with value Type ' + valueType) # print('---------------------> ',forcefield) for objPath in forcefield: nodePath = '/'.join(objPath.split('/')[:-1]) # print(nodePath,objPath) obj = get(rootNode, objPath[1:]) node = get(rootNode, nodePath[1:]) if obj.getClassName() == 'HyperReducedRestShapeSpringsForceField': container = obj else: container = getContainer(node) if obj.getClassName() in forceFieldImplemented and container: valueType = forceFieldImplemented[obj.getClassName()] # print('---------------------> ',valueType) if valueType: animate( save, { "node": node, 'container': container, 'valueType': valueType, 'startTime': 0 }, 0)
def createScene(rootNode): def animation(target, factor): #target.angleIn = math.cos(factor * 2 * math.pi) x = factor + 1 #print(factor) #if factor == 0: # keyboard.press_and_release("v") #sys.exit(0) def ExitFunc(target, factor): import sys sys.exit(0) import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.show() #Scene(rootNode) #rootNode.dt = 0.003 #rootNode.gravity = [0., -9810., 0.] #rootNode.createObject("VisualStyle", displayFlags="showBehaviorModels") # Use these components on top of the scene to solve the constraint "StopperConstraint". #rootNode.createObject("FreeMotionAnimationLoop") #rootNode.createObject("GenericConstraintSolver", maxIterations=1e3, tolerance=1e-5) #simulation = rootNode.createChild("Simulation") #simulation.createObject("EulerImplicitSolver", rayleighStiffness=0.1, rayleighMass=0.1) #simulation.createObject("CGLinearSolver", name="precond") createSceneReal(rootNode) #ServoMotor(simulation, showWheel=True) animate(animation, {"target": None}, duration=10, mode="once", onDone=ExitFunc) return rootNode
def createScene(rootNode): dt = 0.001 length_scale = '0.500' disk_msh = 'disk_' + length_scale + '.msh' def animation(target, factor): #This is a dummy animation function #I would like to use Model Order Reducation on a model that I #animate, but I want to figure out how to do it with the default one first print "Factor ", factor createSceneReal(rootNode, dt) animate(animation, {"target": rootNode}, duration=2, mode="once") return rootNode
def addAnimation(rootNode, phase, timeExe, dt, listObjToAnimate): ''' FOR all node find to animate animate only the one moving -> phase 1/0 If DEFAULT : - SEARCH here for the obj to animate & its valueToIncrement Else : - GIVE obj name to work with & its valueToIncrement give to animate : - the obj to work with & its valueToIncrement if DEFAULT : - the animation function will be defaultShaking - the general param lis(range,period,increment) else : - give the new animation function - param lis(...) ''' # Search node to animate toAnimate = [] for obj in listObjToAnimate: node = get(rootNode, obj.location) print(node.name) toAnimate.append(node) if len(toAnimate) != len(listObjToAnimate): raise Exception("All Obj/Node to animate haven't benn found") tmp = 0 for objToAnimate in listObjToAnimate: if phase[tmp]: if type(toAnimate[tmp]).__name__ == "Node": objToAnimate.item = toAnimate[tmp] for obj in objToAnimate.item.getObjects(): # print(obj.getClassName()) if obj.getClassName( ) == 'CableConstraint' or obj.getClassName( ) == 'SurfacePressureConstraint': objToAnimate.item = obj objToAnimate.params["dataToWorkOn"] = 'value' else: objToAnimate.item = toAnimate[tmp] if objToAnimate.item and objToAnimate.params["dataToWorkOn"]: objToAnimate.duration = timeExe animate(objToAnimate.animFct, { 'objToAnimate': objToAnimate, 'dt': dt }, objToAnimate.duration) print("Animate " + objToAnimate.location + " of type " + objToAnimate.item.getClassName() + "\nwith parameters :\n" + str(objToAnimate.params)) else: print("Found Nothing to animate in " + str(objToAnimate.location)) tmp += 1
def initTripod(self, key): if key == Key.A: animate(setupanimation, {"actuators": self.actuators, "step": 35.0, "angularstep": -1.4965}, duration=0.2)
def addAnimation(node, phase, timeExe, dt, listObjToAnimate): ''' **Add/or not animations defined by** :py:class:`.ObjToAnimate` **to the** :py:obj:`splib.animation.AnimationManagerController` **thanks to** :py:func:`splib.animation.animate` **of the** `STLIB <https://github.com/SofaDefrost/STLIB>`_ **SOFA plugin** +------------------+---------------------------------+----------------------------------------------------------------------------+ | argument | type | definition | +==================+=================================+============================================================================+ | node | Sofa.node | from which node will search & add animation | +------------------+---------------------------------+----------------------------------------------------------------------------+ | phase | list(int) || list of 0/1 that according to its index will activate/desactivate | | | || a :py:class:`.ObjToAnimate` contained in *listObjToAnimate* | +------------------+---------------------------------+----------------------------------------------------------------------------+ | timeExe | sc || correspond to the total SOFA execution duration the animation will occure,| | | || determined with *nbIterations* (of :py:class:`.ReductionAnimations`) | | | || multiply by the *dt* of the current scene | +------------------+---------------------------------+----------------------------------------------------------------------------+ | dt | sc | time step of our SOFA scene | +------------------+---------------------------------+----------------------------------------------------------------------------+ | listObjToAnimate | list(:py:class:`.ObjToAnimate`) | list conaining all the ObjToAnimate that will be use to shake our model | +------------------+---------------------------------+----------------------------------------------------------------------------+ Thanks to the location parameters of an :py:class:`.ObjToAnimate`, we find the component or Sofa.node it will animate. *If its a Sofa.node we search something to animate by default CableConstraint/SurfacePressureConstraint.* ''' toAnimate = [] for obj in listObjToAnimate: nodeFound = get(node, obj.location) # print(nodeFound.name) toAnimate.append(nodeFound) if len(toAnimate) != len(listObjToAnimate): raise Exception("All Obj/Node to animate haven't been found") tmp = 0 for objToAnimate in listObjToAnimate: if phase[tmp]: if type(toAnimate[tmp]).__name__ == "Node": objToAnimate.item = toAnimate[tmp] for obj in objToAnimate.item.getObjects(): # print(obj.getClassName()) if obj.getClassName( ) == 'CableConstraint' or obj.getClassName( ) == 'SurfacePressureConstraint': objToAnimate.item = obj objToAnimate.params["dataToWorkOn"] = 'value' else: objToAnimate.item = toAnimate[tmp] if objToAnimate.item: objToAnimate.duration = timeExe animate(objToAnimate.animFct, { 'objToAnimate': objToAnimate, 'dt': dt }, objToAnimate.duration) print("Animate " + objToAnimate.location + " of type " + objToAnimate.item.getClassName() + "\nwith parameters :\n" + str(objToAnimate.params)) else: print("Found Nothing to animate in " + str(objToAnimate.location)) tmp += 1
def createScene(rootNode): dt = 0.001 length_scale = sys.argv[1] block_msh = 'block_' + length_scale + '.msh' # find point closest to zero (with positive z valu) vector, mid_ind = point_finder.nth_smallest_point(block_msh, 0) fixed_const_lst = point_finder.edge_nodes(block_msh, 1) moving_const_lst = point_finder.edge_nodes(block_msh, -1) middle_nodes_lst = point_finder.nodes_near_10(block_msh, float(length_scale)) i = 0 while vector[-1] < 1.0: i += 1 vector, mid_ind = point_finder.nth_smallest_point(block_msh, i) list_of_vectors_static = [] list_of_vectors_middle = [] list_of_vectors_mid_piont = [] mid_point = point_finder.center_point(block_msh) num_nodes = point_finder.number_of_nodes(block_msh) info_arr = np.array([float(length_scale), 0, dt, num_nodes]) print "info arra ", info_arr print "number of nodes", num_nodes, " num end nodes ", len( fixed_const_lst), " num mid nodes ", len(middle_nodes_lst) import timeit start = timeit.default_timer() def animation(target, factor): x = 1 forces = np.array(target.block.dofs.force)[fixed_const_lst] vels = np.array(target.block.dofs.velocity)[fixed_const_lst] mid_forces = np.array(target.block.dofs.force)[middle_nodes_lst] mid_vels = np.array(target.block.dofs.velocity)[middle_nodes_lst] mid_f = np.array(target.block.dofs.force)[mid_point] mid_v = np.array(target.block.dofs.velocity)[mid_point] list_of_vectors_static.append(np.array([forces, vels])) list_of_vectors_middle.append(np.array([mid_forces, mid_vels])) list_of_vectors_mid_piont.append(np.array([mid_f, mid_v])) def ExitFunc(target, factor): runtime = timeit.default_timer() - start info_arr[1] = runtime print "runtime", runtime, "number of nodes ", num_nodes np.save('output' + str(length_scale) + '.npy', np.array(list_of_vectors_static)) np.save('output' + str(length_scale) + '_middle.npy', np.array(list_of_vectors_static)) np.save('output' + str(length_scale) + '_middle.npy', np.array(list_of_vectors_static)) np.save('output' + str(length_scale) + '_mid_point.npy', np.array(list_of_vectors_mid_piont)) np.save('output' + str(length_scale) + '_info.npy', info_arr) sys.exit(0) createSceneReal(rootNode, dt, fixed_const_lst, moving_const_lst) animate(animation, {"target": rootNode}, duration=2.0, mode="once", onDone=ExitFunc) return rootNode