Initialise from matrix representation

        Create a Quaternion by specifying the 3x3 rotation or 4x4 transformation matrix
        (as a numpy array) from which the quaternion's rotation should be created.
426708
def _from_matrix(cls, matrix):
        
        try:
            shape = matrix.shape
        except AttributeError:
            raise TypeError("Invalid matrix type: Input must be a 3x3 or 4x4 numpy array or matrix")

        if shape == (3, 3):
            R = matrix
        elif shape == (4,4):
            R = matrix[:-1][:,:-1] # Upper left 3x3 sub-matrix
        else:
            raise ValueError("Invalid matrix shape: Input must be a 3x3 or 4x4 numpy array or matrix")

        # Check matrix properties
        if not np.allclose(np.dot(R, R.conj().transpose()), np.eye(3)):
            raise ValueError("Matrix must be orthogonal, i.e. its transpose should be its inverse")
        if not np.isclose(np.linalg.det(R), 1.0):
            raise ValueError("Matrix must be special orthogonal i.e. its determinant must be +1.0")

        def decomposition_method(matrix):
            """ Method supposedly able to deal with non-orthogonal matrices - NON-FUNCTIONAL!
            Based on this method: http://arc.aiaa.org/doi/abs/10.2514/2.4654
            """
            x, y, z = 0, 1, 2 # indices
            K = np.array([
                [R[x, x]-R[y, y]-R[z, z],  R[y, x]+R[x, y],           R[z, x]+R[x, z],           R[y, z]-R[z, y]],
                [R[y, x]+R[x, y],          R[y, y]-R[x, x]-R[z, z],   R[z, y]+R[y, z],           R[z, x]-R[x, z]],
                [R[z, x]+R[x, z],          R[z, y]+R[y, z],           R[z, z]-R[x, x]-R[y, y],   R[x, y]-R[y, x]],
                [R[y, z]-R[z, y],          R[z, x]-R[x, z],           R[x, y]-R[y, x],           R[x, x]+R[y, y]+R[z, z]]
            ])
            K = K / 3.0

            e_vals, e_vecs = np.linalg.eig(K)
            print('Eigenvalues:', e_vals)
            print('Eigenvectors:', e_vecs)
            max_index = np.argmax(e_vals)
            principal_component = e_vecs[max_index]
            return principal_component

        def trace_method(matrix):
            """
            This code uses a modification of the algorithm described in:
            https://d3cw3dd2w32x2b.cloudfront.net/wp-content/uploads/2015/01/matrix-to-quat.pdf
            which is itself based on the method described here:
            http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/

            Altered to work with the column vector convention instead of row vectors
            """
            m = matrix.conj().transpose() # This method assumes row-vector and postmultiplication of that vector
            if m[2, 2] < 0:
                if m[0, 0] > m[1, 1]:
                    t = 1 + m[0, 0] - m[1, 1] - m[2, 2]
                    q = [m[1, 2]-m[2, 1],  t,  m[0, 1]+m[1, 0],  m[2, 0]+m[0, 2]]
                else:
                    t = 1 - m[0, 0] + m[1, 1] - m[2, 2]
                    q = [m[2, 0]-m[0, 2],  m[0, 1]+m[1, 0],  t,  m[1, 2]+m[2, 1]]
            else:
                if m[0, 0] < -m[1, 1]:
                    t = 1 - m[0, 0] - m[1, 1] + m[2, 2]
                    q = [m[0, 1]-m[1, 0],  m[2, 0]+m[0, 2],  m[1, 2]+m[2, 1],  t]
                else:
                    t = 1 + m[0, 0] + m[1, 1] + m[2, 2]
                    q = [t,  m[1, 2]-m[2, 1],  m[2, 0]-m[0, 2],  m[0, 1]-m[1, 0]]

            q = np.array(q)
            q *= 0.5 / sqrt(t);
            return q

        return cls(array=trace_method(R))
68572
public Quaternion fromAxes (IVector3 nx, IVector3 ny, IVector3 nz) {
        double nxx = nx.x(), nyy = ny.y(), nzz = nz.z();
        double x2 = (1f + nxx - nyy - nzz)/4f;
        double y2 = (1f - nxx + nyy - nzz)/4f;
        double z2 = (1f - nxx - nyy + nzz)/4f;
        double w2 = (1f - x2 - y2 - z2);
        return set(Math.sqrt(x2) * (ny.z() >= nz.y() ? +1f : -1f),
                   Math.sqrt(y2) * (nz.x() >= nx.z() ? +1f : -1f),
                   Math.sqrt(z2) * (nx.y() >= ny.x() ? +1f : -1f),
                   Math.sqrt(w2));
    }
490346
function() {

      // Q* := Q / |Q|

      // unrolled Q.scale(1 / Q.norm())

      var w = this['w'];
      var x = this['x'];
      var y = this['y'];
      var z = this['z'];

      var norm = Math.sqrt(w * w + x * x + y * y + z * z);

      if (norm < Quaternion['EPSILON']) {
        return Quaternion['ZERO'];
      }

      norm = 1 / norm;

      return new Quaternion(w * norm, x * norm, y * norm, z * norm);
    }
1143223
def make_pose(translation, rotation):
    
    pose = np.zeros((4, 4))
    pose[:3, :3] = rotation
    pose[:3, 3] = translation
    pose[3, 3] = 1.0
    return pose
496565
function(w, x, y, z) {

      parse(P, w, x, y, z);

      // Q1 * Q2 = [w1 * w2 - dot(v1, v2), w1 * v2 + w2 * v1 + cross(v1, v2)]

      // Not commutative because cross(v1, v2) != cross(v2, v1)!

      var w1 = this['w'];
      var x1 = this['x'];
      var y1 = this['y'];
      var z1 = this['z'];

      var w2 = P['w'];
      var x2 = P['x'];
      var y2 = P['y'];
      var z2 = P['z'];

      return new Quaternion(
              w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
              w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
              w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2,
              w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2);
    }
1371016
def qrot(vector, quaternion):
    
    t = 2 * np.cross(quaternion[1:], vector)
    v_rot = vector + quaternion[0] * t + np.cross(quaternion[1:], t)
    return v_rot
825631
def rotation_matrix_from_axis_and_angle(u, theta):
    ''''''
    
    x = u[0]
    y = u[1]
    z = u[2]
    s = np.sin(theta)
    c = np.cos(theta)
    
    return np.array([[c + x**2 * (1 - c), x * y * (1 - c) - z * s, x * z * (1 - c) + y * s],
                     [y * x * (1 - c) + z * s, c + y**2 * (1 - c), y * z * (1 - c) - x * s ],
                     [z * x * (1 - c) - y * s, z * y * (1 - c) + x * s, c + z**2 * (1 - c) ]])
900667
function getter_THREE_Quaternion(inst) {
	return [
		inst._x,
		inst._y,
		inst._z,
		inst._w];
}
838699
def quaternion_imag(quaternion):
    
    return numpy.array(quaternion[1:4], dtype=numpy.float64, copy=True)
1119280
def rotate(quat)
      rot_matrix = Matrix.from_quat(quat)
      verts = self.vertices
      inv_mat = rot_matrix.inv
      verts = verts.collect {|item| inv_mat*item}
      return Box.from_points(verts)
    end
1239711
def rotate(self, azimuth, axis=None):
        
        target = self._target

        y_axis = self._n_pose[:3, 1].flatten()
        if axis is not None:
            y_axis = axis
        x_rot_mat = transformations.rotation_matrix(azimuth, y_axis, target)
        self._n_pose = x_rot_mat.dot(self._n_pose)

        y_axis = self._pose[:3, 1].flatten()
        if axis is not None:
            y_axis = axis
        x_rot_mat = transformations.rotation_matrix(azimuth, y_axis, target)
        self._pose = x_rot_mat.dot(self._pose)
1027708
public Quaterniond rotateTo(double fromDirX, double fromDirY, double fromDirZ,
                                double toDirX, double toDirY, double toDirZ, Quaterniond dest) {
        double x = fromDirY * toDirZ - fromDirZ * toDirY;
        double y = fromDirZ * toDirX - fromDirX * toDirZ;
        double z = fromDirX * toDirY - fromDirY * toDirX;
        double w = Math.sqrt((fromDirX * fromDirX + fromDirY * fromDirY + fromDirZ * fromDirZ) *
                                    (toDirX * toDirX + toDirY * toDirY + toDirZ * toDirZ)) +
                  (fromDirX * toDirX + fromDirY * toDirY + fromDirZ * toDirZ);
        double invNorm = 1.0 / Math.sqrt(x * x + y * y + z * z + w * w);
        if (Double.isInfinite(invNorm)) {
            // Rotation is ambiguous: Find appropriate rotation axis (1. try toDir x +Z)
            x = toDirY; y = -toDirX; z = 0.0; w = 0.0;
            invNorm = (float) (1.0 / Math.sqrt(x * x + y * y));
            if (Double.isInfinite(invNorm)) {
                // 2. try toDir x +X
                x = 0.0; y = toDirZ; z = -toDirY; w = 0.0;
                invNorm = (float) (1.0 / Math.sqrt(y * y + z * z));
            }
        }
        x *= invNorm;
        y *= invNorm;
        z *= invNorm;
        w *= invNorm;
        /* Multiply */
        dest.set(this.w * x + this.x * w + this.y * z - this.z * y,
                 this.w * y - this.x * z + this.y * w + this.z * x,
                 this.w * z + this.x * y - this.y * x + this.z * w,
                 this.w * w - this.x * x - this.y * y - this.z * z);
        return dest;
    }
1341267
def rotate(self, vec):
    

    qvec = self * Quaternion(vec.x, vec.y, vec.z, 0) * ~self
    return type(vec)(qvec.x, qvec.y, qvec.z)
1006392
@Override
    public Quaternionf wrapQuaternion(ByteBuffer buffer, int offset) {
    	float w = buffer.getFloat(offset);
    	float x = buffer.getFloat(offset + 4);
    	float y = buffer.getFloat(offset + 8);
    	float z = buffer.getFloat(offset + 12);
        return new Quaternionf(x, y, z, w);
    }
1240826
public void rotate(Quaternion rotation) {
		Transform3D m = new Transform3D();
		m.setRotation(rotation);
		m.transform(this.getSegmentVector());
		this.getSegmentVector().normalize();
	}
304976
def quaternion(self):
        
        q_xyzw = transformations.quaternion_from_matrix(self.matrix)
        q_wxyz = np.roll(q_xyzw, 1)
        return q_wxyz
11323
public void rotate(Quaternion rotation, Point3D pivot) {
		Point3D currentPivot = getPivot();
    	// Update the plane equation according
    	// to the desired normal (computed from
    	// the identity vector and the rotations).
    	Transform3D m = new Transform3D();
    	m.setRotation(rotation);
    	Vector3f v = new Vector3f(this.getEquationComponentA(),this.getEquationComponentB(),this.getEquationComponentC());
    	m.transform(v);
    	this.setEquationComponentA(v.getX());
    	this.setEquationComponentB(v.getY());
    	this.setEquationComponentC(v.getZ());
    	
    	if (pivot==null) {
	    	// a.x + b.y + c.z + d = 0
	    	// where (x,y,z) is the translation point
	    	this.setEquationComponentD( - (this.getEquationComponentA()*currentPivot.getX() +
	    				this.getEquationComponentB()*currentPivot.getY() +
	    				this.getEquationComponentC()*currentPivot.getZ()));
    	}
    	else {
    		// Compute the new point
    		Point3f nP = new Point3f(
    				currentPivot.getX() - pivot.getX(),
    				currentPivot.getY() - pivot.getY(),
    				currentPivot.getZ() - pivot.getZ());
    		m.transform(nP);
    		nP.setX(nP.getX() + pivot.getX());
    		nP.setY(nP.getY() + pivot.getY());
    		nP.setZ(nP.getZ() + pivot.getZ());
    		
	    	// a.x + b.y + c.z + d = 0
	    	// where (x,y,z) is the translation point
	    	this.setEquationComponentD( - (this.getEquationComponentA()*nP.getX() +
	    				this.getEquationComponentB()*nP.getY() +
	    				this.getEquationComponentC()*nP.getZ()));
    	}
    	
		clearBufferedValues();
	}