Exemplo n.º 1
0
def create_patch(v, n, t, surf, color, offset = 0, slab = None):

  from _surface import SurfaceModel
  s = SurfaceModel()
  s.name = 'contact patch'
  from chimera import openModels as om
  om.add([s])
  s.openState.xform = surf.openState.xform

  p = s.newPiece()
  p.color = color
  p.save_in_session = True

  if offset:
    vo = v.copy()
    vo += n*offset
    p.geometry = vo,t
    p.normals = n

  if slab:
    from Mask import depthmask
    vs, ns, ts = depthmask.slab_surface(v, t, n, slab, sharp_edges = True)
    p.geometry = vs,ts
    p.normals = ns

  return p
def subdivide_op(surfaces, spacing = None, inPlace = False, modelId = None):

    from Commands import parse_surface_pieces, check_number, parse_model_id
    plist = parse_surface_pieces(surfaces)
    if len(plist) == 0:
        raise CommandError, 'No surfaces specified'
    if spacing is None:
        raise CommandError, 'Must specify mesh spacing'
    check_number(spacing, 'spacing', positive = True)
    model_id = parse_model_id(modelId)
    if inPlace:
        s = None
    else:
        from _surface import SurfaceModel
        s = SurfaceModel()
        s.name = 'finer mesh'
        from chimera import openModels as om
        if model_id:
            id, subid = model_id
        else:
            id, subid = om.Default, om.Default
        om.add([s], baseId = id, subid = subid)
        s.openState.xform = plist[0].model.openState.xform
    from subdivide import subdivide
    for p in plist:
        np = subdivide(p, spacing, s)
        if np != p:
            np.save_in_session = True
Exemplo n.º 3
0
def spine(operation,
          regions,
          spacing=None,
          tipLength=None,
          color=None,
          showDiameter=False):

    sel = parse_object_specifier(regions, 'segmentation region')

    import Surface
    plist = Surface.selected_surface_pieces(sel, include_outline_boxes=False)
    from Segger.regions import Segmentation
    rlist = [
        p.region for p in plist
        if (hasattr(p, 'region') and isinstance(p.model, Segmentation))
    ]
    if len(rlist) == 0:
        raise CommandError('No segmentation regions specified: "%s"' % regions)

    if not (spacing is None or isinstance(spacing,
                                          (int, float)) and spacing > 0):
        raise CommandError('spacing must be positive numeric value')
    if not (tipLength is None or isinstance(tipLength,
                                            (int, float)) and tipLength > 0):
        raise CommandError('tipLength must be positive numeric value')

    if not color is None:
        from Commands import parse_color
        color = parse_color(color)

    if showDiameter:
        from _surface import SurfaceModel
        diam_model = SurfaceModel()
        diam_model.name = 'Diameters'
        from chimera import openModels
        openModels.add([diam_model], sameAs=rlist[0].segmentation)
    else:
        diam_model = None

    import spine
    from chimera import replyobj
    from PathLength import path_length
    for r in rlist:
        mset = spine.trace_spine(r, spacing, tipLength, color)
        slen = path_length([l.bond for l in mset.links()])
        r.set_attribute('spine length', slen)
        msg = 'Spine length for region %d is %.4g' % (r.rid, slen)
        dmax, dmin = spine.measure_diameter(r, mset, diam_model)
        if not dmax is None:
            r.set_attribute('diameter1', dmax)
            r.set_attribute('diameter2', dmin)
            msg += ', diameters %.4g, %.4g' % (dmax, dmin)
        kave, kmin, kmax = spine.measure_curvature(mset)
        if not kmax is None:
            r.set_attribute('curvature average', kave)
            r.set_attribute('curvature minimum', kmin)
            r.set_attribute('curvature maximum', kmax)
            msg += ', curvature %.4g (ave), %.4g (max), %.4g (min)' % (
                kave, kmax, kmin)
        replyobj.info(msg + '\n')
Exemplo n.º 4
0
    def __setattr__(self, attrname, value):

        if attrname in ('drawMode', 'lineWidth', 'pointSize', 'useLighting',
                        'twoSidedLighting', 'smoothLines',
                        'transparencyBlendMode'):
            # SurfacePiece attributes
            if value == getattr(self, attrname):
                return
        elif attrname in ('colorMode', 'visibilityMode',
                          'density', 'probeRadius',
                          'category', 'allComponents'):
            if value == getattr(self, attrname):
                return
            self.__dict__[attrname] = value
        elif attrname not in ('customColors', 'customRGBA'):
            SurfaceModel.__setattr__(self, attrname, value)
            return

        if attrname in ('density', 'probeRadius', 'category', 'allComponents'):
            self.update_surface()
        else:
            p = self.surface_piece
            if p is None or p.__destroyed__:
                return
            if attrname == 'drawMode':
                style = {self.Filled: p.Solid,
                         self.Mesh: p.Mesh,
                         self.Dot:  p.Dot,
                         }[value]
                p.displayStyle = style
            elif attrname == 'lineWidth':
                p.lineThickness = value
            elif attrname == 'pointSize':
                p.dotSize = value
            elif attrname in ('useLighting', 'twoSidedLighting', 'smoothLines',
                              'transparencyBlendMode'):
                setattr(p, attrname, value)
            elif attrname == 'colorMode':
                if value != self.Custom:
                    import Surface
                    Surface.set_coloring_method('msms', self,
                                                self.custom_coloring)
                    self.update_coloring()
            elif attrname == 'visibilityMode':
                if value == self.ByAtom:
                    import Surface
                    Surface.set_visibility_method('msms', self,
                                                  self.custom_visibility)
                    self.update_visibility()
            elif attrname == 'customColors':
                self.set_custom_colors(value)
            elif attrname == 'customRGBA':
                self.set_custom_rgba(value)

        self.report_change(self.change_reason[attrname])
Exemplo n.º 5
0
    def __setattr__(self, attrname, value):

        if attrname in ('drawMode', 'lineWidth', 'pointSize', 'useLighting',
                        'twoSidedLighting', 'smoothLines',
                        'transparencyBlendMode'):
            # SurfacePiece attributes
            if value == getattr(self, attrname):
                return
        elif attrname in ('colorMode', 'visibilityMode', 'density',
                          'probeRadius', 'category', 'allComponents'):
            if value == getattr(self, attrname):
                return
            self.__dict__[attrname] = value
        elif attrname not in ('customColors', 'customRGBA'):
            SurfaceModel.__setattr__(self, attrname, value)
            return

        if attrname in ('density', 'probeRadius', 'category', 'allComponents'):
            self.update_surface()
        else:
            p = self.surface_piece
            if p is None or p.__destroyed__:
                return
            if attrname == 'drawMode':
                style = {
                    self.Filled: p.Solid,
                    self.Mesh: p.Mesh,
                    self.Dot: p.Dot,
                }[value]
                p.displayStyle = style
            elif attrname == 'lineWidth':
                p.lineThickness = value
            elif attrname == 'pointSize':
                p.dotSize = value
            elif attrname in ('useLighting', 'twoSidedLighting', 'smoothLines',
                              'transparencyBlendMode'):
                setattr(p, attrname, value)
            elif attrname == 'colorMode':
                if value != self.Custom:
                    import Surface
                    Surface.set_coloring_method('msms', self,
                                                self.custom_coloring)
                    self.update_coloring()
            elif attrname == 'visibilityMode':
                if value == self.ByAtom:
                    import Surface
                    Surface.set_visibility_method('msms', self,
                                                  self.custom_visibility)
                    self.update_visibility()
            elif attrname == 'customColors':
                self.set_custom_colors(value)
            elif attrname == 'customRGBA':
                self.set_custom_rgba(value)

        self.report_change(self.change_reason[attrname])
Exemplo n.º 6
0
def read_grasp_surface(path):

  sg = GRASP_Surface_Geometry(path)
  from _surface import SurfaceModel
  sm = SurfaceModel()
  import os.path
  sm.name = os.path.basename(path)
  rgba = (1, 1, 1, 1)
  p = sm.addPiece(sg.vertices, sg.triangles, rgba)
  p.normals = sg.normals
  return sm
Exemplo n.º 7
0
def new_surface(name, align_to, model_id):
    from _surface import SurfaceModel
    s = SurfaceModel()
    s.name = name
    from chimera import openModels as om
    if model_id:
        id, subid = model_id
    else:
        id, subid = om.Default, om.Default
    om.add([s], baseId=id, subid=subid)
    s.openState.xform = align_to.openState.xform
    return s
def surface_model(model_id, shape_name, coord_xform=None):

    s = find_surface_model(model_id)
    if s is None:
        from _surface import SurfaceModel
        s = SurfaceModel()
        s.name = shape_name
        from chimera import openModels as om
        if model_id is None:
            model_id = (om.Default, om.Default)
        om.add([s], baseId=model_id[0], subid=model_id[1])
        if coord_xform:
            s.openState.xform = coord_xform
    return s
Exemplo n.º 9
0
def surface_model(model_id, shape_name, coord_xform = None):

    s = find_surface_model(model_id)
    if s is None:
        from _surface import SurfaceModel
        s = SurfaceModel()
        s.name = shape_name
        from chimera import openModels as om
        if model_id is None:
            model_id = (om.Default, om.Default)
        om.add([s], baseId = model_id[0], subid = model_id[1])
        if coord_xform:
            s.openState.xform = coord_xform
    return s
Exemplo n.º 10
0
    def __init__(self,
                 molecule,
                 category,
                 probeRadius=1.4,
                 allComponents=True,
                 vertexDensity=2.0):

        SurfaceModel.__init__(self)

        name = 'MSMS %s surface of %s' % (category, molecule.name)
        SurfaceModel.__setattr__(self, 'name', name)
        SurfaceModel.__setattr__(self, 'piecesAreSelectable', True)
        SurfaceModel.__setattr__(self, 'oneTransparentLayer', True)

        init = {
            'molecule': molecule,
            'colorMode': self.ByAtom,
            'visibilityMode': self.ByAtom,
            'density': vertexDensity,
            'probeRadius': probeRadius,
            'category': category,
            'allComponents': allComponents,
            'atomMap': None,  # vertex number to Atom
            'surface_piece': None,
            'srf': None,  # MSMS surface object
            'triData': None,  # MSMS triangle data
            'areaSES': 0.0,
            'areaSAS': 0.0,
            'calculationFailed': False,
        }
        self.__dict__.update(init)

        from _surface import SurfacePiece
        self.surface_piece_defaults = {
            'drawMode': self.Filled,
            'lineWidth': 1.0,
            'pointSize': 1.0,
            'useLighting': True,
            'twoSidedLighting': True,
            'smoothLines': False,
            'transparencyBlendMode': SurfacePiece.SRC_ALPHA_DST_1_MINUS_ALPHA,
        }

        self.update_surface()

        # Detect changes in atom color, atom surfaceColor, atom surfaceOpacity,
        #   molecule color, atom surfaceDisplay.
        from chimera import triggers as t
        self.molecule_handler = t.addHandler('Molecule', self.molecule_cb,
                                             None)

        # Detect when surface or molecule deleted.
        from chimera import addModelClosedCallback
        addModelClosedCallback(self, self.surface_closed_cb)
        addModelClosedCallback(self.molecule, self.molecule_closed_cb)

        import Surface
        Surface.set_coloring_method('msms', self, self.custom_coloring)
        Surface.set_visibility_method('msms', self, self.custom_visibility)
Exemplo n.º 11
0
def distance(operation,
             object1,
             object2,
             multiple=False,
             show=False,
             color=(0, 1, 1, 1)):

    a1 = object1.atoms()
    import Surface as s
    s1 = s.selected_surface_pieces(object1, include_outline_boxes=False)

    if len(a1) == 0 and len(s1) == 0:
        raise CommandError('No atoms or surfaces specified')

    a2 = object2.atoms()
    s2 = s.selected_surface_pieces(object2, include_outline_boxes=False)

    if len(a2) == 0 and len(s2) == 0:
        raise CommandError('No target atoms or surfaces')

    # Remove near stuff.
    if a1:
        a2 = list(set(a2).difference(a1))
    if s1:
        s2 = list(set(s2).difference(s1))

    name2 = object_name(a2, s2)
    xyz2 = point_array(a2, s2)

    if show:
        from Commands import parse_color
        color = parse_color(color)
        from _surface import SurfaceModel
        surf = SurfaceModel()
        surf.name = 'Distance measurement'
        from chimera import openModels
        openModels.add([surf])
    else:
        surf = None

    if multiple:
        pairs = [([a], []) for a in a1] + [([], [s]) for s in s1]
    else:
        pairs = [(a1, s1)]

    for a, s in pairs:
        name = object_name(a, s)
        xyz = point_array(a, s)
        report_distance(xyz, xyz2, name, name2, surf, color)
Exemplo n.º 12
0
def create_surface(matrix, height, transform, color, interpolate, mesh,
                   smoothing_factor, smoothing_iterations):

    if interpolate == 'cubic':
        matrix = cubic_interpolated_2d_array(matrix)
        from Matrix import multiply_matrices
        transform = multiply_matrices(transform,
                                      ((.5,0,0,0),(0,.5,0,0),(0,0,.5,0)))

    if mesh == 'isotropic':
        vertices, triangles = isotropic_surface_geometry(matrix)
    else:
        cell_diagonal_direction = mesh
        vertices, triangles = surface_geometry(matrix, cell_diagonal_direction)

    # Adjust vertex z range.
    x, z = vertices[:,0], vertices[:,2]
    zmin = z.min()
    xsize, zextent = x.max() - x.min(), z.max() - zmin
    z += -zmin
    if zextent > 0:
        if height is None:
            # Use 1/10 of grid voxels in x dimension.
            zscale = 0.1 * xsize / zextent
        else:
            # Convert zscale physical units to volume index z size.
            from Matrix import apply_matrix_without_translation, length
            zstep = length(apply_matrix_without_translation(transform, (0,0,1)))
            zscale = (height/zstep) / zextent
        z *= zscale

    # Transform vertices from index units to physical units.
    from _contour import affine_transform_vertices
    affine_transform_vertices(vertices, transform)

    if smoothing_factor != 0 and smoothing_iterations > 0:
        from _surface import smooth_vertex_positions
        smooth_vertex_positions(vertices, triangles,
                                smoothing_factor, smoothing_iterations)

    from _surface import SurfaceModel
    sm = SurfaceModel()
    p = sm.addPiece(vertices, triangles, color)
        
    return sm
Exemplo n.º 13
0
    def __init__(self, molecule, category, probeRadius = 1.4,
                 allComponents = True, vertexDensity = 2.0):

        SurfaceModel.__init__(self)

        name = 'MSMS %s surface of %s' % (category, molecule.name)
        SurfaceModel.__setattr__(self, 'name', name)
        SurfaceModel.__setattr__(self, 'piecesAreSelectable', True)
        SurfaceModel.__setattr__(self, 'oneTransparentLayer', True)

        init = {
            'molecule': molecule,
            'colorMode': self.ByAtom,
            'visibilityMode': self.ByAtom,
            'density': vertexDensity,
            'probeRadius': probeRadius,
            'category': category,
            'allComponents': allComponents,
            'atomMap': None,            # vertex number to Atom
            'surface_piece': None,
            'srf': None,                # MSMS surface object
            'triData': None,            # MSMS triangle data
            'areaSES': 0.0,
            'areaSAS': 0.0,
	    'calculationFailed': False,
            }
        self.__dict__.update(init)

        from _surface import SurfacePiece
        self.surface_piece_defaults = {
            'drawMode': self.Filled,
            'lineWidth': 1.0,
            'pointSize': 1.0,
            'useLighting': True,
            'twoSidedLighting': True,
            'smoothLines': False,
            'transparencyBlendMode': SurfacePiece.SRC_ALPHA_DST_1_MINUS_ALPHA,
            }

        self.update_surface()

        # Detect changes in atom color, atom surfaceColor, atom surfaceOpacity,
        #   molecule color, atom surfaceDisplay.
        from chimera import triggers as t
        self.molecule_handler = t.addHandler('Molecule', self.molecule_cb, None)

        # Detect when surface or molecule deleted.
        from chimera import addModelClosedCallback
        addModelClosedCallback(self, self.surface_closed_cb)
        addModelClosedCallback(self.molecule, self.molecule_closed_cb)

        import Surface
        Surface.set_coloring_method('msms', self, self.custom_coloring)
        Surface.set_visibility_method('msms', self, self.custom_visibility)
Exemplo n.º 14
0
  def create_object(self):

    from _surface import SurfaceModel
    sm = SurfaceModel()

    sm.piecesAreSelectable = self.pieces_are_selectable
    if self.version >= 2:
      sm.oneTransparentLayer = self.one_transparent_layer

    for ps in self.surface_piece_states:
      ps.create_object(sm)

    sms = self.surface_model
    from SimpleSession import modelOffset
    from chimera import openModels as om
    om.add([sm], baseId = sms.id + modelOffset, subid = sms.subid)
    sms.restore_state(sm)

    return sm
Exemplo n.º 15
0
    def create_object(self):

        from _surface import SurfaceModel
        sm = SurfaceModel()

        sm.piecesAreSelectable = self.pieces_are_selectable
        if self.version >= 2:
            sm.oneTransparentLayer = self.one_transparent_layer

        for ps in self.surface_piece_states:
            ps.create_object(sm)

        sms = self.surface_model
        from SimpleSession import modelOffset
        from chimera import openModels as om
        om.add([sm], baseId=sms.id + modelOffset, subid=sms.subid)
        sms.restore_state(sm)

        return sm
Exemplo n.º 16
0
def show_surfnet(surfmol, useMesh, interval, density, color, sameAs=None):

    # Create volume
    q = density == 'Quadratic'
    grid, origin = _surfnet.compute_volume(surfmol, interval, False, q)

    # Contour volume
    from _contour import surface, affine_transform_vertices
    varray, tarray, narray = surface(grid,
                                     100,
                                     cap_faces=True,
                                     calculate_normals=True)

    # Hide triangle edges to show square mesh
    from _surface import principle_plane_edges
    hidden_edges = principle_plane_edges(varray, tarray)

    # Scale and shift vertices
    tf = ((interval, 0, 0, origin[0]), (0, interval, 0, origin[1]),
          (0, 0, interval, origin[2]))
    affine_transform_vertices(varray, tf)

    # Create surface/mesh model.
    from _surface import SurfaceModel
    sm = SurfaceModel()

    if color is None:
        rgba = (1, 1, 1, 1)
    else:
        rgba = color.rgba()
    p = sm.addPiece(varray, tarray, rgba)
    p.normals = narray
    if useMesh:
        p.displayStyle = p.Mesh
    p.smoothLines = True
    p.setEdgeMask(hidden_edges)

    chimera.openModels.add([sm], shareXform=False, sameAs=sameAs)
    return [sm]
def show_line_segments(v1, v2, color = (1,1,1,1), surface_model = None):

    n = len(v1)
    from numpy import empty, single as floatc, intc, arange
    varray = empty((2*n,3), floatc)
    tarray = empty((n,3), intc)
    varray[:n,:] = v1
    varray[n:,:] = v2
    tarray[:,0] = tarray[:,2] = arange(n)
    tarray[:,1] = tarray[:,0] + n

    create_model = (surface_model is None)
    if create_model:
        from _surface import SurfaceModel
        surface_model = SurfaceModel()

    p = surface_model.addPiece(varray, tarray, color)
    p.displayStyle = p.Mesh

    if create_model:
        from chimera import openModels as om
        om.add([surface_model])

    return p
Exemplo n.º 18
0
def show_hk_lattice(h, k, radius, orientation = '222',
                    color_rgba = (1,1,1,1), mesh_line_thickness = 1,
                    sphere_factor = 0, replace = True):

    varray, tarray, hex_edges = hk_icosahedron_lattice(h,k,radius,orientation)
    interpolate_with_sphere(varray, radius, sphere_factor)

    # Make new surface model or find an existing one.
    sm = None
    open = False
    from chimera import openModels
    from _surface import SurfaceModel
    if replace:
        mlist = openModels.list(modelTypes = [SurfaceModel])
        mlist = [m for m in mlist if hasattr(m, 'hkcage')]
        if mlist:
            sm = mlist[0]
            for p in sm.surfacePieces:
                if hasattr(p, 'hkcage'):
                    sm.removePiece(p)
            open = True
    if sm is None:
        sm = SurfaceModel()
        sm.name = 'h = %d, k = %d lattice' % (h,k)
        sm.hkcage = True

    p = sm.addPiece(varray, tarray, color_rgba)
    p.hkcage = True
    p.lineThickness = mesh_line_thickness
    p.displayStyle = p.Mesh
    p.setEdgeMask(hex_edges)    # Hide spokes of hexagons.

    if not open:
        openModels.add([sm])

    return sm