def show_axis(tf, color, os):

    import Matrix
    axis, axis_point, angle, axis_shift = Matrix.axis_center_angle_shift(tf)
    if angle < 0.1:
        raise CommandError, 'Rotation angle is near zero (%g degrees)' % angle

    have_box, box = os.bbox()
    if not have_box:
        # TODO: Chimera does not provide bounding box of full model.
        raise CommandError, 'First model must be visible to show axis'

    axis_center = Matrix.project_to_axis(box.center().data(), axis, axis_point)
    axis_length = max((box.urb - box.llf).data())
    hl = 0.5 * axis_length
    ap1 = map(lambda a, b: a - hl * b, axis_center, axis)
    ap2 = map(lambda a, b: a + hl * b, axis_center, axis)
    from VolumePath import Marker_Set, Link
    from VolumePath.markerset import chimera_color
    m = Marker_Set('rotation axis')
    mm = m.marker_model()
    mm.openState.xform = os.xform
    if color:
        mm.color = chimera_color(color)
    radius = 0.025 * axis_length
    m1 = m.place_marker(ap1, None, radius)
    m2 = m.place_marker(ap2, None, radius)
    Link(m1, m2, None, radius)
Beispiel #2
0
def show_axis(tf, color, os):

    import Matrix
    axis, axis_point, angle, axis_shift = Matrix.axis_center_angle_shift(tf)
    if angle < 0.1:
        raise CommandError, 'Rotation angle is near zero (%g degrees)' % angle

    have_box, box = os.bbox()
    if not have_box:
        # TODO: Chimera does not provide bounding box of full model.
        raise CommandError, 'First model must be visible to show axis'

    axis_center = Matrix.project_to_axis(box.center().data(), axis, axis_point)
    axis_length = max((box.urb - box.llf).data())
    hl = 0.5*axis_length
    ap1 = map(lambda a,b: a-hl*b, axis_center, axis)
    ap2 = map(lambda a,b: a+hl*b, axis_center, axis)
    from VolumePath import Marker_Set, Link
    from VolumePath.markerset import chimera_color
    m = Marker_Set('rotation axis')
    mm = m.marker_model()
    mm.openState.xform = os.xform
    if color:
        mm.color = chimera_color(color)
    radius = 0.025 * axis_length
    m1 = m.place_marker(ap1, None, radius)
    m2 = m.place_marker(ap2, None, radius)
    Link(m1, m2, None, radius)
Beispiel #3
0
def molecule_from_mesh(s, stick_radius):

  from VolumePath import Marker_Set, Link
  m = Marker_Set('Mesh ' + s.name)
  radius = stick_radius
  markers = []
  for p in s.surfacePieces:
    varray, earray = p.maskedGeometry(p.Mesh)
    color = p.color
    vcolors = p.vertexColors
    used_vertex = {}
    for v1,v2 in earray:
      used_vertex[v1] = True
      used_vertex[v2] = True
    for v in range(len(varray)):
      if v in used_vertex:
        xyz = varray[v]
        if not vcolors is None:
          color = vcolors[v]
        vm = m.place_marker(xyz, color, radius)
      else:
        vm = None
      markers.append(vm)
    for v1,v2 in earray:
      m1 = markers[v1]
      m2 = markers[v2]
      color = map(lambda a,b: .5*(a+b), m1.rgba(), m2.rgba())
      Link(m1, m2, color, radius)
Beispiel #4
0
def spine_path(region, points, marker_radius, link_radius, rgba):

    from VolumePath import Marker_Set, Marker, Link
    mset = Marker_Set('Region %d spine' % region.rid)
    mset.set_transform(region.segmentation.openState.xform)
    last_marker = None
    for b, xyz in enumerate(points):
        m = Marker(mset, b + 1, xyz, rgba, marker_radius)
        if last_marker:
            Link(last_marker, m, rgba, link_radius)
        last_marker = m
    return mset
Beispiel #5
0
def contact_marker_model(molecule, crystal, clist, asu_list):

    # Set marker and link colors and radii for clash depiction.
    xyz = atom_coordinates(molecule.atoms)
    asu_center = average_xyz(xyz)
    bbox = bounding_box(xyz)
    radius_ncs = .25 * min(map(lambda a, b: a - b, bbox[1], bbox[0]))
    radius_copies = .8 * radius_ncs
    rgba_ncs = (.5, 1, .5, 1)  # NCS asym unit, light green
    rgba_uc = (.5, .8, .9, 1)  # Unit cell, light blue
    rgba_ouc = (.9, .9, .5, 1)  # Other unit cells, light yellow
    rgba_overlap = rgba_ncs[:3] + (.5, )
    link_rgba = (1, .5, .5, 1)
    link_radius = radius_copies
    uc_thickness = .4 * radius_ncs

    # Create markers and links depicting asym units and clashes.
    from VolumePath import Marker_Set
    marker_set = Marker_Set(molecule.name + ' crystal contacts')
    markers = create_asymmetric_unit_markers(marker_set, asu_list, asu_center,
                                             crystal.identity_smtry_index,
                                             rgba_ncs, rgba_uc, rgba_ouc,
                                             radius_ncs, radius_copies)
    n = len(molecule.atoms)
    links = create_clash_links(clist, n, link_radius, link_rgba, markers)

    # Make marker transparent when clashing asym unit are close.
    for l in links:
        if distance(l.marker1.xyz(), l.marker2.xyz()) < .5 * radius_ncs:
            l.marker1.set_rgba(rgba_overlap)

    create_unit_cell(marker_set, crystal.axes, rgba_uc, uc_thickness)

    return marker_set
Beispiel #6
0
def make_polygon_mesh(plist, color, edge_thickness):

    # Find sets of joined vertices.
    mt = {}
    for p in plist:
        for e in p.edges:
            m0, m1 = ordered_link_markers(e)
            for m in (m0, m1):
                if not m in mt:
                    mt[m] = set([m])
            je = joined_edge(e)
            if je:
                jm1, jm0 = ordered_link_markers(je)
                mt[m0].add(jm0)
                mt[m1].add(jm1)

    # Create markers at average postions of joined markers.
    from VolumePath import Marker_Set, Link
    mset = Marker_Set('Mesh')
    mm = {}
    r = 0.5 * edge_thickness
    from numpy import mean
    for m, mg in mt.items():
        if not m in mm:
            xyz = mean([me.polygon.vertex_xyz(me) for me in mg], axis=0)
            mc = mset.place_marker(xyz, color, r)
            for me in mg:
                mm[me] = mc

    # Create links between markers.
    et = {}
    for p in plist:
        for e in p.edges:
            em1, em2 = e.atoms
            m1, m2 = mm[em1], mm[em2]
            if not (m1, m2) in et:
                et[(m1, m2)] = et[(m2, m1)] = Link(m1, m2, color, r)

    return mset
Beispiel #7
0
def draw_marker_lines(lines,
                      v,
                      color=(.7, .7, .7, 1),
                      radius=None,
                      model_id=None):

    from VolumePath import Marker_Set, Link
    mset = Marker_Set('%s field lines' % v.name)
    mset.marker_molecule(model_id).openState.xform = v.openState.xform
    if radius is None:
        radius = 0.5 * max(v.data.step)
    for i, line in enumerate(lines):
        if i % 100 == 0:
            from chimera.replyobj import status
            status('Drawing line %d of %d' % (i, len(lines)))
        mprev = None
        for xyz in line:
            m = mset.place_marker(xyz, color, radius)
            if mprev:
                l = Link(m, mprev, color, radius)
                l.bond.halfbond = True
            mprev = m
    return mset
Beispiel #8
0
def imod_models(chunk_list, name, mesh, contours):

    mlist = []

    surf_model = None
    for c in chunk_list:
        if c['id'] == 'IMOD':
            xyz_scale = c['xscale'], c['yscale'], c['zscale']
            pixel_size = c['pixsize']
            print 'IMOD pixel size =', pixel_size, ' scale', xyz_scale
        elif c['id'] == 'OBJT':
            alpha = 1.0 - 0.01 * c['trans']
            object_rgba = (c['red'], c['green'], c['blue'], alpha)
            obj_name = c['name']
            radius = c['pdrawsize'] * pixel_size
            fill = c['flags'] & (1 << 8)
            lines = not (c['flags'] & (1 << 11))
            only_points = (not lines and not fill)
            link = not only_points
            open_contours = c['flags'] & (1 << 3)
            mset = None
        elif c['id'] == 'MESH':
            if mesh:
                if surf_model == None:
                    import _surface
                    surf_model = _surface.SurfaceModel()
                    surf_model.name = name + ' mesh'
                    mlist.append(surf_model)
                create_mesh(c, pixel_size, xyz_scale, object_rgba, surf_model,
                            obj_name)
        elif c['id'] == 'CONT':
            if contours:
                if mset == None:
                    from VolumePath import Marker_Set
                    mname = '%s %s contours' % (name, obj_name)
                    mset = Marker_Set(mname)
                    # Marker set already added to openModels so don't return
                    # it in mlist.
                create_contour(c, pixel_size, xyz_scale, radius, object_rgba,
                               link, open_contours, mset)

    return mlist
Beispiel #9
0
def place_coordinate_frames(coords, radius):
    '''
    TODO: This Chimera code has not been ported to ChimeraX.
    '''
    r = radius
    t = .2 * r
    from VolumePath import Marker_Set, Marker, Link
    mset = Marker_Set('nucleotide orientations')
    for b, tf in coords.items():
        p0 = (tf[0][3], tf[1][3], tf[2][3])
        m0 = Marker(mset, 4 * b, p0, (.5, .5, .5, 1), t)
        p1 = (tf[0][3] + r * tf[0][0], tf[1][3] + r * tf[1][0],
              tf[2][3] + r * tf[2][0])
        m1 = Marker(mset, 4 * b + 1, p1, (1, .5, .5, 1), t)
        Link(m0, m1, (1, .5, .5, 1), t)
        p2 = (tf[0][3] + r * tf[0][1], tf[1][3] + r * tf[1][1],
              tf[2][3] + r * tf[2][1])
        m2 = Marker(mset, 4 * b + 2, p2, (.5, 1, .5, 1), t)
        Link(m0, m2, (.5, 1, .5, 1), t)
        p3 = (tf[0][3] + r * tf[0][2], tf[1][3] + r * tf[1][2],
              tf[2][3] + r * tf[2][2])
        m3 = Marker(mset, 4 * b + 3, p3, (.5, .5, 1, 1), t)
        Link(m0, m3, (.5, .5, 1, 1), t)
    return mset
from math import sqrt
plane_spacing = sqrt(3)/2 * lattice_spacing

radius = 30		# Radius of cylinder depicting actin filament, Angstroms.

# Colors
color1 = (1,1,.5,1)	# Light yellow. (red, green, blue, opacity) 0-1 scale
color2 = (.5,.5,1,1)	# Light blue.
color3 = (1,0,0,1)	#Red
color4 = (0,1,0,1)	#Green
color5 = (1,0,1,1)	#Purple
color6 = (1,1,0,1)	
color7 = (0.5,0.5,0.5,1)	

from VolumePath import Marker_Set, Marker, Link   #this is to import the module for Chimera
mset = Marker_Set('Actin Filament 01')  #defining the name of the marker set


# Marker(marker_set_name, id_number, (y_coordinate, x_coorinate, Z_coordinate), color, radius)


# m1_(filament_number)

# One actin filament with two colors.

# This is first segment in YELLOW. This is the origin.
m1_0 = Marker(mset, 0, (0,0,0), color2, radius)
m2_0 = Marker(mset, 1, (0,0,actin_length), color2, radius)
Link(m1_0, m2_0, color1, radius)    #link the first segment

Beispiel #11
0
def create_graph ( smod, links ) :

    print "\nCreating graph for %s - %s" % (smod.name, links)

    if hasattr(smod, 'adj_graph') and smod.adj_graph :
        smod.adj_graph.close()
        smod.adj_graph = None

    from VolumePath import Marker_Set, Marker, Link

    gname = smod.name + " graph(%s)" % links
    g = Marker_Set ( gname )
    smod.adj_graph = g
    smod.graph_links = links
    aMap = dict()

    regions = smod.regions
    marker_radius = 0.1 * sum([r.enclosed_volume() ** (1./3) for r in regions]) / len(regions)
#    ijk_to_xyz_transform = smod.point_transform()
    from Matrix import apply_matrix
    for reg in regions :
#        xyz = apply_matrix(ijk_to_xyz_transform, reg.max_point)
        c = reg.center_of_points()
        m = Marker(g, reg.rid, c, reg.color, marker_radius)
        aMap[reg] = m
        m.region = reg
        m.extra_attributes = { 'region_id' : str(reg.rid),
                               'region_size': str(reg.point_count()) }

    link_color = ( .5, .5, .5, 1 )
    link_radius = 0.5 * marker_radius

    from regions import group_contacts
    cons = group_contacts(smod.region_contacts())

    Ns, min_N, max_N = [], None, None
    avgds, min_avgd, max_avgd = [], None, None
    maxds, min_maxd, max_maxd = [], None, None

    # first run through contacts to list contacts and properties
    if links == "avgd" or links == "maxd" or links == "N" :
        for r1 in cons.keys() :
            for r2 in cons[r1].keys() :
                if r2 > r1 :

                    con = cons[r1][r2]

                    #print "link %d -> %d -- N:%.1f, " % (r1.rid, r2.rid, con.N),

                    if con.N < 0.1 :
                        #print "*hmm*"
                        continue
                    else :
                        Ns.append ( con.N )

                    if con.D :
                        #print "D:%.3f, " % con.D,
                        avgd = float(con.D) / (2.0 * float(con.N))
                        avgds.append ( avgd )
                    #else : print "D:*",

                    if con.maximum_density :
                        #print "MaxD:%.3f, " % con.maximum_density
                        maxds.append ( con.maximum_density )
                    #else : print "MaxD:*"


        min_N, max_N = min(Ns), max(Ns)
        #min_maxd, max_maxd = min(maxds), max(maxds)
        #min_avgd, max_avgd = min(avgds), max(avgds)

        #print "Avg densities: %.5f -> %.5f" % (min_avgd, max_avgd)
        print "N: %.1f -> %.1f" % (min_N, max_N)
        #print "Maximum densities %.5f -> %.5f" % (min_maxd, max_maxd)


    min_rad = marker_radius * 0.1
    max_rad = marker_radius * 0.75 - min_rad

    for r1 in cons.keys() :
        for r2 in cons[r1].keys() :
            if r2 > r1 :

                con = cons[r1][r2]

                if links == "maxd" and con.maximum_density :
                    # radius proportional to max density at boundary
                    if con.N > 0.1 :
                        maxd = con.maximum_density
                        link_radius_var = min_rad + max_rad * (maxd - min_maxd)/(max_maxd-min_maxd)
                        Link ( aMap[r1], aMap[r2], link_color, link_radius_var )

                elif links == "N" and con.N:
                    # radius of link proportional to area of contact
                    #  - where area of contact ~ #voxels between regions
                    con = cons[r1][r2]
                    link_radius_var = min_rad + max_rad * (con.N - min_N)/(max_N-min_N)
                    Link ( aMap[r1], aMap[r2], link_color, link_radius_var )

                elif links == "avgd" and con.D:
                    # radius of link proportional to average density
                    #  - at boundary
                    if con.N > 0.1 :
                        avgd = float(con.D) / (2.0 * float(con.N))
                        link_radius_var = min_rad + max_rad * (avgd - min_avgd)/(max_avgd-min_avgd)
                        Link ( aMap[r1], aMap[r2], link_color, link_radius_var )
                else :
                    # same link radius for all links
                    Link ( aMap[r1], aMap[r2], link_color, link_radius )


    g.show_model ( True )
    smod.display = True
    smod.regions_scale = 0.5
    smod.display_regions ('Voxel_Surfaces', None, None, True)
Beispiel #12
0
    def connect_attached_rings(self, ring):
        """
        Build a cylinder that connects `ring` with its adjacent one,
        given by `ring.a1`
        """
        geom_center = ring.center
        bild = ""
        # Connections (cylinders) depend on linkage type
        O_att, N_att, C_att = None, None, None
        for neighbor in ring.a1.neighbors:
            if (neighbor.element.name == 'O'
                    and neighbor.residue != ring.residue
                    and neighbor.name != 'O{}'.format(ring.shifted + 5)):
                O_att = neighbor
                break
            elif neighbor.element.name == 'N':
                N_att = neighbor
                break
        if O_att is not None:
            # Check if the oxygen is then attached to a carbon
            for neighbor in O_att.neighbors:
                if neighbor.element.name == 'C' and neighbor.residue != ring.a1.residue:
                    C_att = neighbor
                    break
            # If the oxygen is attached to a carbon
            # Then the attached residue is a carbohydrate or this is an O-linked glycan
            # Check for ring atoms of the attached carbohydrate residue
            if C_att is not None:
                attached_ring = self.saccharydes.get(C_att.residue)
                # If the attached residue contains ring atoms
                # Then the attached residue is a carbohydrate
                # Set position of attachment as geometric center of ring atoms
                # of attached carbohydrate residue
                if attached_ring is not None and attached_ring is not ring:
                    # TODO: Check name of C and color accordingly
                    bild_attrs = dict(start=geom_center,
                                      end=attached_ring.center,
                                      sphere_radius=self.cylinder_radius,
                                      cylinder_radius=self.cylinder_radius,
                                      kind='saccharyde ' + C_att.name,
                                      label=C_att.name)
                # Otherwise this is an O-linked glycan or GLYCAM OME or TBT
                else:
                    # Check for alpha carbon of attached protein residue
                    att_CA = C_att.residue.atomsMap.get('CA')
                    if att_CA is not None:
                        # Then it is attached to a protein via CA and is an O-linked glycan
                        bild_attrs = dict(start=geom_center,
                                          end=att_CA[0].coord(),
                                          sphere_radius=self.cylinder_radius,
                                          cylinder_radius=self.cylinder_radius,
                                          kind='O-linked glycan')
                    else:
                        # Then GLYCAM OME or TBT
                        bild_attrs = dict(
                            start=geom_center,
                            end=O_att.coord(),
                            sphere_radius=self.size * SCALES['sphere'] *
                            self.sphere_redfac,
                            cylinder_radius=self.cylinder_radius *
                            self.cylinder_redfac,
                            kind='GLYCAM OME or TBT')
            # If the oxygen is not attached to a carbon
            else:
                # Then it is a terminal oxygen and marks the reducing end
                bild_attrs = dict(start=geom_center,
                                  end=O_att.coord(),
                                  sphere_radius=self.size * SCALES['sphere'] *
                                  self.sphere_redfac,
                                  cylinder_radius=self.cylinder_radius *
                                  self.cylinder_redfac,
                                  kind='reducing end')
                # If the residue has an attached nitrogen
        elif N_att is not None:
            # Then we assume this is an N-linked glycan
            # Set position of attachment as the linked CA
            att_CA = N_att.residue.atomsMap['CA']
            bild_attrs = dict(start=geom_center,
                              end=att_CA[0].coord(),
                              sphere_radius=self.cylinder_radius,
                              cylinder_radius=self.cylinder_radius,
                              kind='N-linked glycan')
        # If there is no oxygen or nitrogen attached
        else:
            # Generate a point to denote terminal
            vec = ring.p1 - chimera.Point(*geom_center)
            vecadj = (1.43 / vec.length) * vec
            geom_center_att = ring.p1 + vecadj
            bild_attrs = dict(start=geom_center,
                              end=geom_center_att,
                              sphere_radius=self.cylinder_radius,
                              cylinder_radius=self.cylinder_radius,
                              kind='terminal')

        geom_center_att = bild_attrs['end']
        bild = """
        .color gray
        .sphere {end[0]} {end[1]} {end[2]} {sphere_radius}
        .cylinder {start[0]} {start[1]} {start[2]} {end[0]} {end[1]} {end[2]} {cylinder_radius}
        """.format(**bild_attrs)

        ring.vrml._vrml_connector = ring.vrml._build_vrml(
            bild, name='SNFG connector {}'.format(bild_attrs['kind']))
        ring.vrml._vrml_connector[0].attrs = bild_attrs

        if self.bondtypes and 'label' in bild_attrs:
            ms = MarkerSet('SNFG label {}'.format(bild_attrs['kind']))
            ms.marker_model((ring.vrml._vrml_connector[0].id,
                             ring.vrml._vrml_connector[0].subid + 1))
            ring.vrml._vrml_connector[0].markerset = ms
            ms.place_marker(bild_attrs['start'], None, 0.1)
            ms.place_marker(bild_attrs['end'], None, 0.1)
            link = ms.molecule.newBond(*ms.molecule.atoms[:2])
            link.label = bild_attrs['label']
            link.labelColor = chimera.colorTable.getColorByName('black')
        return ring.vrml._vrml_connector
Beispiel #13
0
def test(n=1000, color=(.7, .7, .7, 1), radius=1):
    from VolumePath import Marker_Set
    m = Marker_Set('sphere points')
    p = sphere_points(n)
    for xyz in p:
        m.place_marker(20 * xyz, color, radius)