Transform actor position and orientation wrt to its polygonal mesh,
        which remains unmodified.
335448
def setTransform(self, T):
        
        if isinstance(T, vtk.vtkMatrix4x4):
            self.SetUserMatrix(T)
        else:
            try:
                self.SetUserTransform(T)
            except TypeError:
                colors.printc('~time Error in setTransform(): consider transformPolydata() instead.', c=1)
        return self
396549
def normalize_mesh(mesh):
  ''''''
  mesh = dict(mesh)
  pos = mesh['position'][:,:3].copy()
  pos -= (pos.max(0)+pos.min(0)) / 2.0
  pos /= np.abs(pos).max()
  mesh['position'] = pos
  return mesh
518083
def Torus(pos=(0, 0, 0), r=1, thickness=0.1, axis=(0, 0, 1), c="khaki", alpha=1, res=30):
    
    rs = vtk.vtkParametricTorus()
    rs.SetRingRadius(r)
    rs.SetCrossSectionRadius(thickness)
    pfs = vtk.vtkParametricFunctionSource()
    pfs.SetParametricFunction(rs)
    pfs.SetUResolution(res * 3)
    pfs.SetVResolution(res)
    pfs.Update()

    nax = np.linalg.norm(axis)
    if nax:
        axis = np.array(axis) / nax
    theta = np.arccos(axis[2])
    phi = np.arctan2(axis[1], axis[0])
    t = vtk.vtkTransform()
    t.PostMultiply()
    t.RotateY(theta * 57.3)
    t.RotateZ(phi * 57.3)
    tf = vtk.vtkTransformPolyDataFilter()
    tf.SetInputData(pfs.GetOutput())
    tf.SetTransform(t)
    tf.Update()
    pd = tf.GetOutput()

    actor = Actor(pd, c, alpha)
    actor.GetProperty().SetInterpolationToPhong()
    actor.SetPosition(pos)
    settings.collectable_actors.append(actor)
    return actor
1166827
def polyfit2dGrid(arr, mask=None, order=3, replace_all=False,
                  copy=True, outgrid=None):
    '''
    
    '''
    s0,s1 = arr.shape
    if mask is None:
        if outgrid is None:
            y,x = np.mgrid[:float(s0),:float(s1)]
            p = polyfit2d(x.flatten(),y.flatten(),arr.flatten(),order)
            return polyval2d(x,y, p, dtype=arr.dtype)
        mask = np.zeros_like(arr, dtype=bool)
    elif mask.sum() == 0 and not replace_all and outgrid is None:

        return arr
    valid = ~mask
    y,x = np.where(valid)
    z = arr[valid]
    p = polyfit2d(x,y,z,order)
    if outgrid is not None:
        yy,xx = outgrid
    else:
        if replace_all:
            yy,xx = np.mgrid[:float(s0),:float(s1)]
        else:
            yy,xx = np.where(mask)
    new = polyval2d(xx,yy, p, dtype=arr.dtype)
    
    if outgrid is not None or replace_all:
        return new
    
    if copy:
        arr = arr.copy()
    arr[mask] = new
    return arr
465687
def rebuild( self ):
        
        scene      = self.scene()
        if ( not scene ):
            return
        
        sourcePos  = self.sourceItem().viewItem().pos()
        sourceRect = self.sourceItem().viewItem().rect()
        
        targetPos  = self.targetItem().viewItem().pos()
        targetRect = self.targetItem().viewItem().rect()
        
        cellWidth  = scene.ganttWidget().cellWidth()
        
        startX = sourcePos.x() + sourceRect.width() - (cellWidth / 2.0)
        startY = sourcePos.y() + (sourceRect.height() / 2.0)
        
        endX   = targetPos.x() - 2
        endY   = targetPos.y() + (targetRect.height() / 2.0)
        
        path = QPainterPath()
        path.moveTo(startX, startY)
        path.lineTo(startX, endY)
        path.lineTo(endX, endY)
        
        a = QPointF(endX - 10, endY - 3)
        b = QPointF(endX, endY)
        c = QPointF(endX - 10, endY + 3)
        
        self._polygon = QPolygonF([a, b, c, a])
        
        path.addPolygon(self._polygon)
        
        self.setPath(path)
192998
def encode_to_shape(inputs, shape, scope):
  """"""
  with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
    w, h = shape[1], shape[2]
    x = inputs
    x = tfl.flatten(x)
    x = tfl.dense(x, w * h, activation=None, name="enc_dense")
    x = tf.reshape(x, (-1, w, h, 1))
    return x
278933
def grid_from_coordinate_transform(numPix, Mpix2coord, ra_at_xy_0, dec_at_xy_0):
    
    a = np.arange(numPix)
    matrix = np.dstack(np.meshgrid(a, a)).reshape(-1, 2)
    x_grid = matrix[:, 0]
    y_grid = matrix[:, 1]
    ra_grid = x_grid * Mpix2coord[0, 0] + y_grid * Mpix2coord[0, 1] + ra_at_xy_0
    dec_grid = x_grid * Mpix2coord[1, 0] + y_grid * Mpix2coord[1, 1] + dec_at_xy_0
    return ra_grid, dec_grid
855957
def Disc(
    pos=(0, 0, 0),
    normal=(0, 0, 1),
    r1=0.5,
    r2=1,
    c="coral",
    bc="darkgreen",
    lw=1,
    alpha=1,
    res=12,
    resphi=None,
):
    
    ps = vtk.vtkDiskSource()
    ps.SetInnerRadius(r1)
    ps.SetOuterRadius(r2)
    ps.SetRadialResolution(res)
    if not resphi:
        resphi = 6 * res
    ps.SetCircumferentialResolution(resphi)
    ps.Update()

    axis = np.array(normal) / np.linalg.norm(normal)
    theta = np.arccos(axis[2])
    phi = np.arctan2(axis[1], axis[0])
    t = vtk.vtkTransform()
    t.PostMultiply()
    t.RotateY(theta * 57.3)
    t.RotateZ(phi * 57.3)
    tf = vtk.vtkTransformPolyDataFilter()
    tf.SetInputData(ps.GetOutput())
    tf.SetTransform(t)
    tf.Update()

    pd = tf.GetOutput()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(pd)

    actor = Actor()  # vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.getColor(c))
    actor.GetProperty().SetOpacity(alpha)
    actor.GetProperty().SetLineWidth(lw)
    actor.GetProperty().SetInterpolationToFlat()
    if bc:  # defines a specific color for the backface
        backProp = vtk.vtkProperty()
        backProp.SetDiffuseColor(colors.getColor(bc))
        backProp.SetOpacity(alpha)
        actor.SetBackfaceProperty(backProp)
    actor.SetPosition(pos)
    settings.collectable_actors.append(actor)
    return actor
1135283
def delaunay2D(plist, mode='xy', tol=None):
    
    pd = vtk.vtkPolyData()
    vpts = vtk.vtkPoints()
    vpts.SetData(numpy_to_vtk(plist, deep=True))
    pd.SetPoints(vpts)
    delny = vtk.vtkDelaunay2D()
    delny.SetInputData(pd)
    if tol:
        delny.SetTolerance(tol)
    if mode=='fit':
        delny.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE)
    delny.Update()
    return Actor(delny.GetOutput())
94313
def apply_transform(self, transform):
        
        dimension = self.vertices.shape[1]
        transform = np.asanyarray(transform, dtype=np.float64)

        if transform.shape != (dimension + 1, dimension + 1):
            raise ValueError('transform is incorrect shape!')
        elif np.abs(transform - np.eye(dimension + 1)).max() < 1e-8:
            # if we've been passed an identity matrix do nothing
            return

        # make sure cache is up to date
        self._cache.verify()
        # new cache to transfer items
        cache = {}
        # apply transform to discretized paths
        if 'discrete' in self._cache.cache:
            cache['discrete'] = np.array([
                transformations.transform_points(
                    d, matrix=transform)
                for d in self.discrete])

        # things we can just straight up copy
        # as they are topological not geometric
        for key in ['root',
                    'paths',
                    'path_valid',
                    'dangling',
                    'vertex_graph',
                    'enclosure',
                    'enclosure_shell',
                    'enclosure_directed']:
            # if they're in cache save them from the purge
            if key in self._cache.cache:
                cache[key] = self._cache.cache[key]

        # transform vertices in place
        self.vertices = transformations.transform_points(
            self.vertices,
            matrix=transform)
        # explicitly clear the cache
        self._cache.clear()
        self._cache.id_set()

        # populate the things we wangled
        self._cache.cache.update(cache)
671366
def MeshArrows(*inputobj, **options):
    
    s = options.pop("s", None)
    scale = options.pop("scale", 1)
    c = options.pop("c", "gray")
    alpha = options.pop("alpha", 1)
    res = options.pop("res", 12)

    mesh, u = _inputsort(inputobj)
    startPoints = mesh.coordinates()
    u_values = np.array([u(p) for p in mesh.coordinates()])
    if not utils.isSequence(u_values[0]):
        printc("~times Error: cannot show Arrows for 1D scalar values!", c=1)
        exit()
    endPoints = mesh.coordinates() + u_values
    if u_values.shape[1] == 2:  # u_values is 2D
        u_values = np.insert(u_values, 2, 0, axis=1)  # make it 3d
        startPoints = np.insert(startPoints, 2, 0, axis=1)  # make it 3d
        endPoints = np.insert(endPoints, 2, 0, axis=1)  # make it 3d

    actor = shapes.Arrows(
        startPoints, endPoints, s=s, scale=scale, c=c, alpha=alpha, res=res
    )
    actor.mesh = mesh
    actor.u = u
    actor.u_values = u_values
    return actor
111299
def mesh(self):
        """"""
        triangles = np.empty((self.f.shape[0], 4))
        triangles[:, -3:] = self.f
        triangles[:, 0] = 3
        return vtki.PolyData(self.v, triangles, deep=False)
333866
def _get_affine_transform(self):
        """"""
        # How big is the projected globe?
        # In the case of a stereonet, it's actually constant.
        xscale = yscale = self._scale
        # Create an affine transform to stretch the projection from 0-1
        return Affine2D() \
            .rotate(np.radians(self.rotation)) \
            .scale(0.5 / xscale, 0.5 / yscale) \
            .translate(0.5, 0.5)
65870
def Cone(pos=(0, 0, 0), r=1, height=3, axis=(0, 0, 1), c="dg", alpha=1, res=48):
    
    con = vtk.vtkConeSource()
    con.SetResolution(res)
    con.SetRadius(r)
    con.SetHeight(height)
    con.SetDirection(axis)
    con.Update()
    actor = Actor(con.GetOutput(), c, alpha)
    actor.GetProperty().SetInterpolationToPhong()
    actor.SetPosition(pos)
    v = utils.versor(axis) * height / 2
    actor.base = pos - v
    actor.top = pos + v
    settings.collectable_actors.append(actor)
    return actor
770231
def _transform_to_2d(t):
    """"""
    t = np.asarray(t)

    dim = len(t.shape)
    assert dim <= 2

    if dim < 2:
        t = np.atleast_2d(t).T

    return t
969270
def Plane(pos=(0, 0, 0), normal=(0, 0, 1), sx=1, sy=None, c="g", bc="darkgreen",
          alpha=1, texture=None):
    
    if sy is None:
        sy = sx
    ps = vtk.vtkPlaneSource()
    ps.SetResolution(1, 1)
    tri = vtk.vtkTriangleFilter()
    tri.SetInputConnection(ps.GetOutputPort())
    tri.Update()
    poly = tri.GetOutput()
    axis = np.array(normal) / np.linalg.norm(normal)
    theta = np.arccos(axis[2])
    phi = np.arctan2(axis[1], axis[0])
    t = vtk.vtkTransform()
    t.PostMultiply()
    t.Scale(sx, sy, 1)
    t.RotateY(theta * 57.3)
    t.RotateZ(phi * 57.3)
    tf = vtk.vtkTransformPolyDataFilter()
    tf.SetInputData(poly)
    tf.SetTransform(t)
    tf.Update()
    pd = tf.GetOutput()
    actor = Actor(pd, c=c, bc=bc, alpha=alpha, texture=texture)
    actor.SetPosition(pos)
    settings.collectable_actors.append(actor)
    return actor
521770
def to_mesh(self):
        
        result = Trimesh(vertices=self.vertices.copy(),
                         faces=self.faces.copy(),
                         face_normals=self.face_normals.copy(),
                         process=False)
        return result