示例#1
0
def inv(q):
    """
    inverse 

    If you're dealing with unit quaternions, use conj instead.
    """
    return Vec.scal(1 / Vec.norm2(q), conj(q))
示例#2
0
def inv(q):
    """
    inverse 

    If you're dealing with unit quaternions, use conj instead.
    """
    return Vec.scal(1 / Vec.norm2(q), conj(q) )
示例#3
0
def spring(v1, v2):
    
    force_vec = (v1-v2)
    #dist = force_vec.mag()
    force_vec = Vec (force_vec.x, force_vec.y) 
    #node has mass
    #eval
    if (force_vec.mag()>=100) :
        return(Vec(-force_vec.x, -force_vec.y))
    else : return(force_vec)
示例#4
0
	def checkLine2(self, point, direction):
		# calculate distance between point and plane
		length = direction.length()
		dire = Vec.Vec3( direction.x/length, direction.y/length, direction.z/length )
		
		bot = Vec.op3(self.n, dire, operator.mul)
		if bot.x == 0 and bot.y == 0 and bot.z == 0: return False

		subd = Vec.op3(self.n, point, operator.mul)
		top  = Vec.op3(self.d, subd, operator.sub)
		dist = Vec.op3(top, bot, collision._my_div)

		# check direction
		if (dist.x < 0 or dist.y < 0 or dist.z < 0):
			return False
		
		# calculate intersection point
		dist = Vec.op3(dist, dire, operator.mul)
		inter = Vec.op3(point, dist, operator.add)

		# calculate radii
		rc = Vec.op3(self.c, inter, operator.sub).length()
		rw = Vec.op3(self.pw, inter, operator.sub).length()
		rh = Vec.op3(self.ph, inter, operator.sub).length()

		# calc 2d coords		
		x = collision._circ_calc(self.w, rc, rw)
		y = collision._circ_calc(self.h, rc, rh)

		# check bounds
		if (x < 0 or x > self.w): return False
		if (y < 0 or y > self.h): return False
		
		return True
示例#5
0
def axisToQuat(axis, phi):
    """ return the quaternion corresponding to rotation around vector axis with angle phi
    """
    axis_norm = Vec.norm(axis)
    if axis_norm < sys.float_info.epsilon:
        return id()
    axis = Vec.scal(1./axis_norm, axis)
    return [ axis[0]*math.sin(phi/2),
             axis[1]*math.sin(phi/2),
             axis[2]*math.sin(phi/2),
             math.cos(phi/2) ]
示例#6
0
def axisToQuat(axis, phi):
    """ return the quaternion corresponding to rotation around vector axis with angle phi
    """
    axis_norm = Vec.norm(axis)
    if axis_norm < sys.float_info.epsilon:
        return id()
    axis = Vec.scal(1. / axis_norm, axis)
    return [
        axis[0] * math.sin(phi / 2), axis[1] * math.sin(phi / 2),
        axis[2] * math.sin(phi / 2),
        math.cos(phi / 2)
    ]
示例#7
0
def flip(q):
    """Flip a quaternion to the real positive hemisphere if needed."""
    
    if re(q) < 0:
        return Vec.minus(q)
    else :
        return q
示例#8
0
def flip(q):
    """Flip a quaternion to the real positive hemisphere if needed."""

    if re(q) < 0:
        return Vec.minus(q)
    else:
        return q
示例#9
0
 def __init__(self,
              node,
              name,
              node1,
              node2,
              stiffnesses=[0, 0, 0, 0, 0, 0],
              index1=0,
              index2=0):
     self.node = node.createChild(name)
     self.dofs = self.node.createObject('MechanicalObject',
                                        template='Vec6d',
                                        name='dofs',
                                        position='0 0 0 0 0 0')
     input = []  # @internal
     input.append('@' + Tools.node_path_rel(self.node, node1) + '/dofs')
     input.append('@' + Tools.node_path_rel(self.node, node2) + '/dofs')
     self.mapping = self.node.createObject('RigidJointMultiMapping',
                                           template='Rigid,Vec6d',
                                           name='mapping',
                                           input=concat(input),
                                           output='@dofs',
                                           pairs=str(index1) + " " +
                                           str(index2))
     compliances = vec.inv(stiffnesses)
     self.compliance = self.node.createObject(
         'DiagonalCompliance',
         template="Vec6d",
         name='compliance',
         compliance=concat(compliances),
         isCompliance=0)
示例#10
0
 def addSpring(self, stiffness):
     mask = [(1 - d) for d in self.mask]
     mask = vec.scal(1.0 / stiffness, mask)
     return self.node.createObject('DiagonalCompliance',
                                   template="Rigid",
                                   isCompliance="0",
                                   compliance=concat(mask))
示例#11
0
	def __mul__(self, other):
		res = Frame()
		res.translation = vec.sum(self.translation,
					  quat.rotate(self.rotation,
						      other.translation))
		res.rotation = quat.prod( self.rotation,
					  other.rotation)

		return res
示例#12
0
 def __init__(self, node, name, node1, node2, stiffnesses=[0,0,0,0,0,0], index1=0, index2=0):
         self.node = node.createChild( name )
         self.dofs = self.node.createObject('MechanicalObject', template = 'Vec6d', name = 'dofs', position = '0 0 0 0 0 0' )
         input = [] # @internal
         input.append( '@' + Tools.node_path_rel(self.node,node1) + '/dofs' )
         input.append( '@' + Tools.node_path_rel(self.node,node2) + '/dofs' )
         self.mapping = self.node.createObject('RigidJointMultiMapping', template = 'Rigid,Vec6d', name = 'mapping', input = concat(input), output = '@dofs', pairs = str(index1)+" "+str(index2))
         compliances = vec.inv(stiffnesses);
         self.compliance = self.node.createObject('DiagonalCompliance', template="Vec6d", name='compliance', compliance=concat(compliances), isCompliance=0)
示例#13
0
	def __mul__(self, other):
		res = Frame()
		res.translation = vec.sum(self.translation,
					  quat.rotate(self.rotation,
						      other.translation))
		res.rotation = quat.prod( self.rotation,
					  other.rotation)

		return res
示例#14
0
def exp(v):
    """exponential"""
    theta = Vec.norm(v)

    if math.fabs(theta) < sys.float_info.epsilon:
        return id()

    s = math.sin(theta / 2)
    c = math.cos(theta / 2)

    return [v[0] / theta * s, v[1] / theta * s, v[2] / theta * s, c]
示例#15
0
	def __init__(self, c, pw, ph):
		self.c = c
		self.pw = pw
		self.ph = ph
		
		ow = Vec.op3(pw, c, operator.sub)
		oh = Vec.op3(ph, c, operator.sub)
		self.n = Vec.Vec3( \
			oh.y*ow.z - oh.z*ow.y, \
			oh.z*ow.x - oh.x*ow.z, \
			oh.x*ow.y - oh.y*ow.x)
		
		length = self.n.length()
		self.n.x /= length
		self.n.y /= length
		self.n.z /= length

		self.d = Vec.op3(self.n, c, operator.mul)
		self.w = ow.length()
		self.h = oh.length()
示例#16
0
    def apply(self, tau):

        current = self.dofs.externalForce
        value = [tau * ei for ei in self.basis]

        # TODO optimize ? setting the list directly does not work
        # across time steps :-/
        if len(current) == 0:
            self.dofs.externalForce = Tools.cat(value)
        else:
            self.dofs.externalForce = Tools.cat(Vec.sum(current[0], value))
示例#17
0
def quatToAxis(q):
    """ Return rotation vector corresponding to unit quaternion q in the form of [axis, angle]
    """
    sine = math.sin(math.acos(q[3]))

    if (math.fabs(sine) < sys.float_info.epsilon):
        axis = [0.0, 1.0, 0.0]
    else:
        axis = Vec.scal(1 / sine, q[0:3])
    phi = math.acos(q[3]) * 2.0
    return [axis, phi]
示例#18
0
def quatToAxis(q):
    """ Return rotation vector corresponding to unit quaternion q in the form of [axis, angle]
    """
    sine  = math.sin( math.acos(q[3]) );

    if (math.fabs(sine) < sys.float_info.epsilon) :
        axis = [0.0,1.0,0.0]
    else :
        axis = Vec.scal(1/sine, q[0:3])
    phi =  math.acos(q[3]) * 2.0
    return [axis, phi]
示例#19
0
def log(q):
    """(principal) logarithm. 

    You might want to flip q first to ensure theta is in the [-0, pi]
    range, yielding the equivalent rotation (principal) logarithm.

    """

    half_theta = math.acos(sign * re(q))

    if math.fabs(half_theta) < sys.float_info.epsilon:
        return [0, 0, 0]

    return Vec.scal(2 * half_theta / math.sin(half_theta), im(q))
示例#20
0
def exp(v):
    """exponential"""
    theta = Vec.norm(v)

    if math.fabs(theta) < sys.float_info.epsilon:
        return id()

    s = math.sin(theta / 2)
    c = math.cos(theta / 2)

    return [ v[0] / theta * s,
             v[1] / theta * s,
             v[2] / theta * s,
             c ]
示例#21
0
def force_layout(nodes):
    forces = {}
    for n in nodes:
        forces[n] = Vec(0, 0)
        for t in n.targets:
            forces[n] += spring(n.vec,t[1].vec)
        for nod in nodes:

            #if nod is not n.targets[1]:
                if nod is not n:
                    forces[n] += ball(n.vec,nod.vec)
                    
    for n in nodes:
        #if (forces[n])
        n.vec += forces[n] * C4
示例#22
0
def log(q):

    """(principal) logarithm. 

    You might want to flip q first to ensure theta is in the [-0, pi]
    range, yielding the equivalent rotation (principal) logarithm.

    """

    half_theta = math.acos( sign * re(q) )

    if math.fabs( half_theta ) < sys.float_info.epsilon:
        return [0, 0, 0]

    return Vec.scal(2 * half_theta / math.sin(half_theta),
                    im(q))
示例#23
0
    def insert(self, parent):
        res = Joint.insert(self, parent)

        if self.lower_limit == None and self.upper_limit == None:
            return res

        limit = res.createChild('limit')

        dofs = limit.createObject('MechanicalObject', template='Vec1')
        map = limit.createObject('ProjectionMapping', template='Vec6,Vec1')

        limit.createObject('UniformCompliance',
                           template='Vec1',
                           compliance='0')
        limit.createObject('UnilateralConstraint')

        # don't stabilize as we need to detect violated
        # constraints first
        # limit.createObject('Stabilization');

        set = []
        position = []
        offset = []

        if self.lower_limit != None:
            set = set + [0] + self.dofs
            position.append(0)
            offset.append(self.lower_limit)

        if self.upper_limit != None:
            set = set + [0] + vec.minus(self.dofs)
            position.append(0)
            offset.append(-self.upper_limit)

        map.set = concat(set)
        map.offset = concat(offset)
        dofs.position = concat(position)

        return res
示例#24
0
文件: Rigid.py 项目: 151706061/sofa
        def insert(self, parent):
                res = Joint.insert(self, parent)

                if self.lower_limit == None and self.upper_limit == None:
                        return res
                
                limit = res.createChild('limit')

                dofs = limit.createObject('MechanicalObject', template = 'Vec1')
                map = limit.createObject('ProjectionMapping', template = 'Vec6,Vec1' )

                limit.createObject('UniformCompliance', template = 'Vec1', compliance = '0' )
                limit.createObject('UnilateralConstraint');

                # don't stabilize as we need to detect violated
                # constraints first
                # limit.createObject('Stabilization');

                set = []
                position = []
                offset = []

                if self.lower_limit != None:
                        set = set + [0] + self.dofs
                        position.append(0)
                        offset.append(self.lower_limit)

                if self.upper_limit != None:
                        set = set + [0] + vec.minus(self.dofs)
                        position.append(0)
                        offset.append(- self.upper_limit)
                
                map.set = concat(set)
                map.offset = concat(offset)
                dofs.position = concat(position)

                return res
示例#25
0
import sys

import CNN_fine_turn
import CNN_GAP_MAM
from utils import str2bool, evaluate, inference_and_generation
import Vec

if __name__ == '__main__':

    config = configparser.ConfigParser()
    config.read(sys.argv[1])

    if str2bool(config['Pipeline']['Vec']):
        print(
            "Starting to learn a distributed representation of amino acids...")
        Vec.run(config['Vec'], config['FilesDirectories'])

    if str2bool(config['Pipeline']['train']):
        print("Start training")
        CNN_GAP_MAM.train(config['Hyper-Parameter for MAM'],
                          config['FilesDirectories'])
    if str2bool(config['Pipeline']['evaluate']):
        print("Performing prediction on the test set...")
        # CNN_GAP_MAM.evaluate(config['FilesDirectories'])
        evaluate(dir_names=config['FilesDirectories'], mode='normal')

    if str2bool(config['Pipeline']['inference']):
        print("Performing inference on the test set...")
        # CNN_GAP_MAM.inference_and_generation(config['FilesDirectories'])
        inference_and_generation(dir_names=config['FilesDirectories'],
                                 mode='normal')
示例#26
0
	def inv(self):
		res = Frame()
		res.rotation = quat.conj( self.rotation )
		res.translation = vec.minus( quat.rotate(res.rotation,
							 self.translation) )
		return res
示例#27
0
 def __init__(self, label):
     self.label = label
     self.targets = []
     self.vec = Vec(0, 0)
示例#28
0
    if isVector(x):
        return x
    else:
        return Vec.Vec(x, y, z, w)


# TODO: add to test_helpers.py with isMatrix and ensureMatrix


# Ensure testMat is a Mat44 matrix (4 row Vec4s)
def isMatrix(testMat):
    return isinstance(testMat, Mat44.Mat44)


# Ensure matrix, either a Mat44 object, 4 row Vec4s, 16 matrix values
zero = Vec.Vec(0, 0, 0, 0)


def ensureMatrix(row0x,
                 row0y=zero,
                 row0z=zero,
                 row0w=zero,
                 row1x=zero,
                 row1y=zero,
                 row1z=zero,
                 row1w=zero,
                 row2x=zero,
                 row2y=zero,
                 row2z=zero,
                 row2w=zero,
                 row3x=zero,
示例#29
0
def ensureVector(x, y=0, z=0, w=0):
    if isVector(x):
        return x
    else:
        return Vec.Vec(x, y, z, w)
示例#30
0
    def pid(self, dt):
        p = Vec.dot(self.basis, self.dofs.position[0]) - self.ref_pos
        d = Vec.dot(self.basis, self.dofs.velocity[0]) - self.ref_vel
        i = self.integral + dt * p

        return p, i, d
示例#31
0
 def addLimits( self, lower, upper, compliance=0 ):
     mask = [ (1 - d) for d in self.mask ]
     return GenericRigidJoint.Limits( self.node, [mask,vec.minus(mask)], [lower,-upper], compliance )
示例#32
0
 def addSpring( self, stiffness ):
     mask = [ (1 - d) for d in self.mask ]
     mask = vec.scal(1.0/stiffness,mask)
     return self.node.createObject('DiagonalCompliance', template = "Rigid", isCompliance="0", compliance=concat(mask))
示例#33
0
	def inv(self):
		res = Frame()
		res.rotation = quat.conj( self.rotation )
		res.translation = vec.minus( quat.rotate(res.rotation,
							 self.translation) )
		return res
示例#34
0
def prod(a, b):
    """product"""
    return Vec.sum( Vec.sum( Vec.scal( re(a), im(b) ),
                             Vec.scal( re(b), im(a) )),
                    Vec.cross( im(a), im(b) ) ) + [ re(a) * re(b) - Vec.dot( im(a), im(b) ) ]
示例#35
0
def inv(q):
    return Vec.scal(1 / Vec.norm2(q), conj(q) )
示例#36
0
 def addLimits(self, lower, upper, compliance=0):
     mask = [(1 - d) for d in self.mask]
     return GenericRigidJoint.Limits(self.node,
                                     [mask, vec.minus(mask)],
                                     [lower, -upper], compliance)
示例#37
0
def prod(a, b):
    """product"""
    return Vec.sum(Vec.sum(Vec.scal(re(a), im(b)), Vec.scal(re(b), im(a))),
                   Vec.cross(im(a),
                             im(b))) + [re(a) * re(b) - Vec.dot(im(a), im(b))]