def xform_points(points, xf, to_xf): txf = to_xf.inverse() txf.multiply(xf) tf = xform_matrix(txf) from _contour import affine_transform_vertices affine_transform_vertices(points, tf)
def bond_points(bonds, xform, bond_point_spacing): if bond_point_spacing == None and use_bond_zone(): bond_point_spacing = bond_zone_point_spacing() if bond_point_spacing == None: return [] xyz_list = [] for b in bonds: c = bond_point_count(b, bond_point_spacing) if c > 0: xyz1, xyz2 = map(lambda a: a.xformCoord().data(), b.atoms) for k in range(c): fb = float(k+1) / (c+1) fa = 1-fb xyz = map(lambda a,b: fa*a + fb*b, xyz1, xyz2) xyz_list.append(xyz) from numpy import array, single as floatc, zeros if len(xyz_list) > 0: points = array(xyz_list, floatc) from Matrix import xform_matrix import _contour _contour.affine_transform_vertices(points, xform_matrix(xform)) else: points = zeros((0,3), floatc) return points
def fit_points_old(fmap, threshold=None): f_m = fmap.data.full_matrix() size = list(f_m.shape) size.reverse() points = VolumeData.grid_indices(size, numpy.single) # i,j,k indices _contour.affine_transform_vertices(points, fmap.data.ijk_to_xyz_transform) weights = numpy.ravel(f_m).astype(numpy.single) threshold = fmap.surface_levels[0] #threshold = .3 * max ( numpy.ravel(f_m).astype(numpy.single) ) ge = numpy.greater_equal(weights, threshold) points = numpy.compress(ge, points, 0) weights = numpy.compress(ge, weights) nz = numpy.nonzero(weights)[0] if len(nz) < len(weights): points = numpy.take(points, nz, axis=0) weights = numpy.take(weights, nz, axis=0) #mass = numpy.sum(weights, dtype=numpy.single) #fmap.rotation_center = numpy.dot(weights,points) / mass if 1: print "FitPoints from %s with threshold %.4f, %d nonzero" % ( fmap.name, threshold, len(nz)) return points, weights
def bond_points(bonds, xform, bond_point_spacing): if bond_point_spacing == None and use_bond_zone(): bond_point_spacing = bond_zone_point_spacing() if bond_point_spacing == None: return [] xyz_list = [] for b in bonds: c = bond_point_count(b, bond_point_spacing) if c > 0: xyz1, xyz2 = map(lambda a: a.xformCoord().data(), b.atoms) for k in range(c): fb = float(k + 1) / (c + 1) fa = 1 - fb xyz = map(lambda a, b: fa * a + fb * b, xyz1, xyz2) xyz_list.append(xyz) from numpy import array, single as floatc, zeros if len(xyz_list) > 0: points = array(xyz_list, floatc) from Matrix import xform_matrix import _contour _contour.affine_transform_vertices(points, xform_matrix(xform)) else: points = zeros((0, 3), floatc) return points
def xform_vectors(vectors, xf, to_xf): txf = to_xf.inverse() txf.multiply(xf) tf = zero_translation(xform_matrix(txf)) from _contour import affine_transform_vertices affine_transform_vertices(vectors, tf)
def bounding_xray_map_symmetry(atoms, pad, volume): # Get atom positions. from _multiscale import get_atom_coordinates xyz = get_atom_coordinates(atoms, transformed = True) # Transform atom coordinates to volume ijk indices. from Matrix import multiply_matrices, xform_matrix tf = multiply_matrices(volume.data.xyz_to_ijk_transform, xform_matrix(volume.model_transform().inverse())) from _contour import affine_transform_vertices affine_transform_vertices(xyz, tf) ijk = xyz # Find integer bounds. from math import floor, ceil ijk_min = [int(floor(i-pad)) for i in ijk.min(axis=0)] ijk_max = [int(ceil(i+pad)) for i in ijk.max(axis=0)] #gather information about unit cell and symmetry ijk_cell_size = getattr(volume.data, 'unit_cell_size', volume.data.size) syms = volume.data.symmetries step = volume.data.step from VolumeFilter import cover cg = cover.map_covering_box(volume, ijk_min, ijk_max, ijk_cell_size, syms, step) from VolumeViewer import volume_from_grid_data v = volume_from_grid_data(cg, show_data = False) v.copy_settings_from(volume, copy_region = False) return v
def transform_vertices_and_normals(v, n, xform): from Matrix import xform_matrix, zero_translation tf = xform_matrix(xform) rot = zero_translation(tf) from _contour import affine_transform_vertices affine_transform_vertices(v, tf) affine_transform_vertices(n, rot)
def show_surface(varray, tarray, edge_mask, color, mesh, linewidth, center, rotation, qrotation, coordinate_system, slab, model_id, shape_name): from Commands import parse_rgba rgba = parse_rgba(color) if coordinate_system: from Commands import openStateFromSpec os = openStateFromSpec(coordinate_system, 'coordinateSystem') cxf = os.xform else: cxf = None s = surface_model(model_id, shape_name, cxf) sxf = s.openState.xform sxfinv = sxf.inverse() if cxf is None: cxf = sxf axis, angle = parse_rotation(rotation, qrotation) if axis: from chimera import Vector csaxis = cxf.apply(Vector(*axis)).data() from Matrix import rotation_transform saxis = sxfinv.apply(Vector(*csaxis)).data() rtf = rotation_transform(saxis, angle) from _contour import affine_transform_vertices affine_transform_vertices(varray, rtf) if center: from Commands import parseCenterArg center, csys = parseCenterArg(center, 'shape') if csys: center = csys.xform.apply(center) else: center = cxf.apply(center) scenter = sxfinv.apply(center) varray += scenter.data() if not slab is None: if isinstance(slab, (float, int)): pad = (-0.5 * slab, 0.5 * slab) else: pad = parse_floats(slab, 'slab', 2) import _surface narray = _surface.calculate_vertex_normals(varray, tarray) from Mask import depthmask varray, tarray = depthmask.slab_surface(varray, tarray, narray, pad) p = s.addPiece(varray, tarray, rgba) if mesh: p.displayStyle = p.Mesh if not edge_mask is None: p.setEdgeMask(edge_mask) # Hide spokes of hexagons. p.lineThickness = linewidth p.save_in_session = True
def show_surface(varray, tarray, edge_mask, color, mesh, linewidth, center, rotation, qrotation, coordinate_system, slab, model_id, shape_name): from Commands import parse_rgba rgba = parse_rgba(color) if coordinate_system: from Commands import openStateFromSpec os = openStateFromSpec(coordinate_system, 'coordinateSystem') cxf = os.xform else: cxf = None s = surface_model(model_id, shape_name, cxf) sxf = s.openState.xform sxfinv = sxf.inverse() if cxf is None: cxf = sxf axis, angle = parse_rotation(rotation, qrotation) if axis: from chimera import Vector csaxis = cxf.apply(Vector(*axis)).data() from Matrix import rotation_transform saxis = sxfinv.apply(Vector(*csaxis)).data() rtf = rotation_transform(saxis, angle) from _contour import affine_transform_vertices affine_transform_vertices(varray, rtf) if center: from Commands import parseCenterArg center, csys = parseCenterArg(center, 'shape') if csys: center = csys.xform.apply(center) else: center = cxf.apply(center) scenter = sxfinv.apply(center) varray += scenter.data() if not slab is None: if isinstance(slab, (float,int)): pad = (-0.5*slab, 0.5*slab) else: pad = parse_floats(slab, 'slab', 2) import _surface narray = _surface.calculate_vertex_normals(varray, tarray) from Mask import depthmask varray, tarray = depthmask.slab_surface(varray, tarray, narray, pad) p = s.addPiece(varray, tarray, rgba) if mesh: p.displayStyle = p.Mesh if not edge_mask is None: p.setEdgeMask(edge_mask) # Hide spokes of hexagons. p.lineThickness = linewidth p.save_in_session = True
def atom_coordinates(atoms, xform): from _multiscale import get_atom_coordinates xyz = get_atom_coordinates(atoms, transformed = True) from Matrix import xform_matrix tf = xform_matrix(xform.inverse()) from _contour import affine_transform_vertices affine_transform_vertices(xyz, tf) return xyz
def move_objects(self, xf): from Matrix import xform_matrix tf = xform_matrix(xf) from _contour import affine_transform_vertices for p in self.pieces: varray, tarray = p.geometry affine_transform_vertices(varray, tf) p.geometry = varray, tarray
def get_atom_coordinates(atoms, xform): from _multiscale import get_atom_coordinates xyz = get_atom_coordinates(atoms, transformed=True) from _contour import affine_transform_vertices from Matrix import xform_matrix affine_transform_vertices(xyz, xform_matrix(xform)) return xyz
def get_atom_coordinates(atoms, xform): from _multiscale import get_atom_coordinates xyz = get_atom_coordinates(atoms, transformed = True) from _contour import affine_transform_vertices from Matrix import xform_matrix affine_transform_vertices(xyz, xform_matrix(xform)) return xyz
def atom_positions(atoms, xform = None): import _multiscale xyz = _multiscale.get_atom_coordinates(atoms, transformed = True) if xform: from Matrix import xform_matrix tf = xform_matrix(xform.inverse()) from _contour import affine_transform_vertices affine_transform_vertices(xyz, tf) return xyz
def transform_atom_positions(atoms, tf, from_atoms = None): if from_atoms is None: from_atoms = atoms import _multiscale xyz = _multiscale.get_atom_coordinates(from_atoms, transformed = False) from _contour import affine_transform_vertices affine_transform_vertices(xyz, tf) from chimera import Point for i,a in enumerate(atoms): a.setCoord(Point(*xyz[i]))
def zone_mask(grid_data, zone_points, zone_radius, invert_mask = False, zone_point_mask_values = None): from numpy import single as floatc, array, ndarray, zeros, int8, intc if not isinstance(zone_points, ndarray): zone_points = array(zone_points, floatc) if (not zone_point_mask_values is None and not isinstance(zone_point_mask_values, ndarray)): zone_point_mask_values = array(zone_point_mask_values, int8) shape = tuple(reversed(grid_data.size)) mask_3d = zeros(shape, int8) mask_1d = mask_3d.ravel() if zone_point_mask_values is None: if invert_mask: mask_value = 0 mask_1d[:] = 1 else: mask_value = 1 from VolumeData import grid_indices from _contour import affine_transform_vertices from _closepoints import find_closest_points, BOXES_METHOD size_limit = 2 ** 22 # 4 Mvoxels if mask_3d.size > size_limit: # Calculate plane by plane to save memory with grid point array xsize, ysize, zsize = grid_data.size grid_points = grid_indices((xsize,ysize,1), floatc) affine_transform_vertices(grid_points, grid_data.ijk_to_xyz_transform) zstep = [grid_data.ijk_to_xyz_transform[a][2] for a in range(3)] for z in range(zsize): i1, i2, n1 = find_closest_points(BOXES_METHOD, grid_points, zone_points, zone_radius) offset = xsize*ysize*z if zone_point_mask_values is None: mask_1d[i1 + offset] = mask_value else: mask_1d[i1 + offset] = zone_point_mask_values[n1] grid_points[:,:] += zstep else: grid_points = grid_indices(grid_data.size, floatc) affine_transform_vertices(grid_points, grid_data.ijk_to_xyz_transform) i1, i2, n1 = find_closest_points(BOXES_METHOD, grid_points, zone_points, zone_radius) if zone_point_mask_values is None: mask_1d[i1] = mask_value else: mask_1d[i1] = zone_point_mask_values[n1] return mask_3d
def AxesModOffset ( COM=[0,0,0], U=None, Extents=[30,30,30], rad=1.0, f=1.0, alignTo = None ) : import _surface mol = _surface.SurfaceModel() chimera.openModels.add([mol], sameAs = alignTo) pos = chimera.Vector(0,0,0) axes = AddArrow2 ( pos, chimera.Vector(0,1,0), lY, (cF,.3,.3,1), rad, mol ) axes.name = "Riboarrow" if U != None : R = numpy.array([ [ U[0,0], U[0,1], U[0,2], 0.0 ], [ U[1,0], U[1,1], U[1,2], 0.0 ], [ U[2,0], U[2,1], U[2,2], 0.0 ] ] ) T = numpy.array([ [ 1.0, 0.0, 0.0, COM[0] ], [ 0.0, 1.0, 0.0, COM[1] ], [ 0.0, 0.0, 1.0, COM[2] ] ] ) Ti = numpy.array([ [ 1.0, 0.0, 0.0, Extents[0]*0.7 ], [ 0.0, 1.0, 0.0, -Extents[1]/2.0 ], [ 0.0, 0.0, 1.0, -Extents[0]*0.7 ] ] ) import Matrix M = Matrix.multiply_matrices ( R, Ti ) M = Matrix.multiply_matrices ( T, M ) ps = [] for p in axes.surfacePieces : v, t = numpy.copy(p.geometry[0]), numpy.copy(p.geometry[1]) ps.append ( [v,t,p.color] ) axes.removePiece ( p ) import _contour for p in ps : _contour.affine_transform_vertices( p[0], M ) axes.addPiece ( p[0], p[1], p[2] ) from random import random as rand clr = ( rand()*.7, rand()*.7, rand()*.7, 1.0 ) # for p in axes.surfacePieces : p.color = clr #for g in axes.surfacePieces : # g.initial_v = numpy.copy ( g.geometry[0] ) return axes
def chain_radial_size(chain): xyz = chain.lan_chain.source_atom_xyz() from numpy import array, multiply, sum xyzc = array(xyz) from Matrix import xform_matrix import _contour _contour.affine_transform_vertices(xyzc, xform_matrix(chain.xform)) multiply(xyzc, xyzc, xyzc) r2 = sum(xyzc, axis=1) r2max = max(r2) import math r = math.sqrt(r2max) return r
def AxesMod1 ( COM=[0,0,0], U=None, length=10.0, exfac=10.0, rad=1.0, alignTo = None, axes=None ) : import _surface toaxes = axes if toaxes == None : toaxes = _surface.SurfaceModel() chimera.openModels.add([toaxes], sameAs = alignTo) toaxes.name = "Axes" #axes = AddAxes ( rad, Extents[0]*f, Extents[1]*f, Extents[2]*f, 1.0, mol ) pos = chimera.Vector(0,0,0) #mol = AddArrow2 ( pos, chimera.Vector(1,0,0), lX, (cF,0,0,1), rad, mol ) #mol = AddArrow2 ( pos, chimera.Vector(0,1,0), lY, (0,cF,0,1), rad, mol ) naxes = AddArrow3 ( pos, chimera.Vector(0,0,1), length, (0,0,1,1), rad, _surface.SurfaceModel() ) if U != None : S = numpy.array([ [ 1.0, 0.0, 0.0, 0 ], [ 0.0, 1.0, 0.0, 0 ], [ 0.0, 0.0, 2.0, 0 ] ] ) P = numpy.array([ [ 1.0, 0.0, 0.0, 0 ], [ 0.0, 1.0, 0.0, 0 ], [ 0.0, 0.0, 1.0, -length ] ] ) R = numpy.array([ [ U[0,0], U[0,1], U[0,2], 0.0 ], [ U[1,0], U[1,1], U[1,2], 0.0 ], [ U[2,0], U[2,1], U[2,2], 0.0 ] ] ) T = numpy.array([ [ 1.0, 0.0, 0.0, COM[0] ], [ 0.0, 1.0, 0.0, COM[1] ], [ 0.0, 0.0, 1.0, COM[2] ] ] ) import Matrix M = Matrix.multiply_matrices ( T, R ) M = Matrix.multiply_matrices ( M, P ) M = Matrix.multiply_matrices ( M, S ) import _contour for p in naxes.surfacePieces : v, t = numpy.copy(p.geometry[0]), numpy.copy(p.geometry[1]) _contour.affine_transform_vertices( v, M ) toaxes.addPiece ( v,t,p.color ) return toaxes
def texture_surface_piece(p, t, txf, border_color, offset = 0): p.textureId = t.texture_id() p.useTextureTransparency = ('a' in t.color_mode) p.textureModulationColor = t.modulation_rgba() p.textureBorderColor = border_color va = offset_vertices(p, offset) s2tc = t.texture_matrix() p2s = p.model.openState.xform p2s.premultiply(txf.inverse()) import Matrix p2tc = Matrix.multiply_matrices(s2tc, Matrix.xform_matrix(p2s)) import _contour _contour.affine_transform_vertices(va, p2tc) p.textureCoordinates = va p.using_surface_coloring = True
def texture_surface_piece(p, t, txf, border_color, offset=0): p.textureId = t.texture_id() p.useTextureTransparency = ('a' in t.color_mode) p.textureModulationColor = t.modulation_rgba() p.textureBorderColor = border_color va = offset_vertices(p, offset) s2tc = t.texture_matrix() p2s = p.model.openState.xform p2s.premultiply(txf.inverse()) import Matrix p2tc = Matrix.multiply_matrices(s2tc, Matrix.xform_matrix(p2s)) import _contour _contour.affine_transform_vertices(va, p2tc) p.textureCoordinates = va p.using_surface_coloring = True
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
def molecule_grid_data(atoms, resolution, step, pad, cutoff_range, sigma_factor): from _multiscale import get_atom_coordinates, bounding_box xyz = get_atom_coordinates(atoms, transformed=True) # Transform coordinates to local coordinates of the molecule containing # the first atom. This handles multiple unaligned molecules. from Matrix import xform_matrix m0 = atoms[0].molecule tf = xform_matrix(m0.openState.xform.inverse()) from _contour import affine_transform_vertices affine_transform_vertices(xyz, tf) xyz_min, xyz_max = bounding_box(xyz) origin = [x - pad for x in xyz_min] ijk = (xyz - origin) / step anum = [a.element.number for a in atoms] sdev = sigma_factor * resolution / step from numpy import zeros, float32 sdevs = zeros((len(atoms), 3), float32) sdevs[:] = sdev from math import pow, pi, ceil normalization = pow(2 * pi, -1.5) * pow(sdev * step, -3) shape = [ int(ceil((xyz_max[a] - xyz_min[a] + 2 * pad) / step)) for a in (2, 1, 0) ] matrix = zeros(shape, float32) from _gaussian import sum_of_gaussians sum_of_gaussians(ijk, anum, sdevs, cutoff_range, matrix) matrix *= normalization molecules = set([a.molecule for a in atoms]) if len(molecules) > 1: name = 'molmap res %.3g' % (resolution, ) else: name = 'molmap %s res %.3g' % (m0.name, resolution) from VolumeData import Array_Grid_Data grid = Array_Grid_Data(matrix, origin, (step, step, step), name=name) return grid, molecules
def contacting_transforms(mol, csys, tflist, cdist): from _multiscale import get_atom_coordinates points = get_atom_coordinates(mol.atoms) pxf = mol.openState.xform pxf.premultiply(csys.openState.xform.inverse()) from Matrix import xform_matrix, identity_matrix from numpy import array, float32 point_tf = xform_matrix(pxf) from _contour import affine_transform_vertices affine_transform_vertices(points, point_tf) # points in reference coords ident = array(identity_matrix(), float32) from _closepoints import find_close_points_sets, BOXES_METHOD ctflist = [ tf for tf in tflist if len( find_close_points_sets(BOXES_METHOD, [(points, ident)], [( points, array(tf, float32))], cdist)[0][0]) > 0 ] return ctflist
def contacting_transforms(mol, csys, tflist, cdist): from _multiscale import get_atom_coordinates points = get_atom_coordinates(mol.atoms) pxf = mol.openState.xform pxf.premultiply(csys.openState.xform.inverse()) from Matrix import xform_matrix, identity_matrix from numpy import array, float32 point_tf = xform_matrix(pxf) from _contour import affine_transform_vertices affine_transform_vertices(points, point_tf) # points in reference coords ident = array(identity_matrix(),float32) from _closepoints import find_close_points_sets, BOXES_METHOD ctflist = [tf for tf in tflist if len(find_close_points_sets(BOXES_METHOD, [(points, ident)], [(points, array(tf,float32))], cdist)[0][0]) > 0] return ctflist
def molecule_grid_data(atoms, resolution, step, pad, cutoff_range, sigma_factor): from _multiscale import get_atom_coordinates, bounding_box xyz = get_atom_coordinates(atoms, transformed = True) # Transform coordinates to local coordinates of the molecule containing # the first atom. This handles multiple unaligned molecules. from Matrix import xform_matrix m0 = atoms[0].molecule tf = xform_matrix(m0.openState.xform.inverse()) from _contour import affine_transform_vertices affine_transform_vertices(xyz, tf) xyz_min, xyz_max = bounding_box(xyz) origin = [x-pad for x in xyz_min] ijk = (xyz - origin) / step anum = [a.element.number for a in atoms] sdev = sigma_factor * resolution / step from numpy import zeros, float32 sdevs = zeros((len(atoms),3), float32) sdevs[:] = sdev from math import pow, pi, ceil normalization = pow(2*pi,-1.5)*pow(sdev*step,-3) shape = [int(ceil((xyz_max[a] - xyz_min[a] + 2*pad) / step)) for a in (2,1,0)] matrix = zeros(shape, float32) from _gaussian import sum_of_gaussians sum_of_gaussians(ijk, anum, sdevs, cutoff_range, matrix) matrix *= normalization molecules = set([a.molecule for a in atoms]) if len(molecules) > 1: name = 'molmap res %.3g' % (resolution,) else: name = 'molmap %s res %.3g' % (m0.name, resolution) from VolumeData import Array_Grid_Data grid = Array_Grid_Data(matrix, origin, (step,step,step), name = name) return grid, molecules
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 map_points_and_weights(v, above_threshold, metric = 'sum product'): from chimera import Xform m, tf_inv = v.matrix_and_transform(Xform(), subregion = None, step = None) from Matrix import invert_matrix tf = invert_matrix(tf_inv) size = list(m.shape) size.reverse() from VolumeData import grid_indices from numpy import single as floatc, ravel, nonzero, take points = grid_indices(size, floatc) # i,j,k indices import _contour _contour.affine_transform_vertices(points, tf) weights = ravel(m).astype(floatc) if above_threshold: # Keep only points where density is above lowest displayed threshold threshold = min(v.surface_levels) from numpy import greater_equal, compress ge = greater_equal(weights, threshold) points = compress(ge, points, 0) weights = compress(ge, weights) if metric == 'correlation about mean': wm = weights.sum() / len(weights) weights -= wm else: # Eliminate points with zero weight. nz = nonzero(weights)[0] if len(nz) < len(weights): points = take(points, nz, axis=0) weights = take(weights, nz, axis=0) return points, weights
def tube_surface_piece(ptlist, pcolors, radius, circle_subdivisions, surface_model=None, model_id=None): nz = len(ptlist) nc = circle_subdivisions height = 0 from Shape.shapecmd import cylinder_geometry varray, tarray = cylinder_geometry(radius, height, nz, nc, caps=True) tflist = extrusion_transforms(ptlist) # Transform circles. from _contour import affine_transform_vertices for i in range(nz): affine_transform_vertices(varray[nc * i:nc * (i + 1), :], tflist[i]) # Transform cap center points affine_transform_vertices(varray[-2:-1, :], tflist[0]) affine_transform_vertices(varray[-1:, :], tflist[-1]) # Vertex colors. from numpy import empty, float32 carray = empty((nz * nc + 2, 4), float32) for i in range(nz): carray[nc * i:nc * (i + 1), :] = pcolors[i] carray[-2, :] = pcolors[0] carray[-1, :] = pcolors[-1] if surface_model is None: import _surface surface_model = _surface.SurfaceModel() from chimera import openModels as om if model_id is None: model_id = (om.Default, om.Default) om.add([surface_model], baseId=model_id[0], subid=model_id[1]) p = surface_model.addPiece(varray, tarray, (1, 1, 1, 1)) p.vertexColors = carray if radius == 0: p.displayStyle = p.Mesh p.useLighting = False return p
def tube_surface_piece(ptlist, pcolors, radius, circle_subdivisions, surface_model = None, model_id = None): nz = len(ptlist) nc = circle_subdivisions height = 0 from Shape.shapecmd import cylinder_geometry varray, tarray = cylinder_geometry(radius, height, nz, nc, caps = True) tflist = extrusion_transforms(ptlist) # Transform circles. from _contour import affine_transform_vertices for i in range(nz): affine_transform_vertices(varray[nc*i:nc*(i+1),:], tflist[i]) # Transform cap center points affine_transform_vertices(varray[-2:-1,:], tflist[0]) affine_transform_vertices(varray[-1:,:], tflist[-1]) # Vertex colors. from numpy import empty, float32 carray = empty((nz*nc+2,4), float32) for i in range(nz): carray[nc*i:nc*(i+1),:] = pcolors[i] carray[-2,:] = pcolors[0] carray[-1,:] = pcolors[-1] if surface_model is None: import _surface surface_model = _surface.SurfaceModel() from chimera import openModels as om if model_id is None: model_id = (om.Default, om.Default) om.add([surface_model], baseId = model_id[0], subid = model_id[1]) p = surface_model.addPiece(varray, tarray, (1,1,1,1)) p.vertexColors = carray if radius == 0: p.displayStyle = p.Mesh p.useLighting = False return p
def apply_transform(tf, v): from _contour import affine_transform_vertices affine_transform_vertices(v, tf)
def computeVolume(self, atoms, frame_ids, volumeName=None, spacing=0.5, radiiTreatment="ignored"): #function taken from Movie/gui.py and tweaked to compute volume based on an array of frame_ids from Matrix import xform_matrix gridData = {} from math import floor from numpy import array, float32, concatenate from _contour import affine_transform_vertices insideDeltas = {} include = {} sp2 = spacing * spacing for fn in frame_ids: cs = self.movie.findCoordSet(fn) if not cs: self.movie.status("Loading frame %d" % fn) self.movie._LoadFrame(int(fn), makeCurrent=False) cs = self.movie.findCoordSet(fn) self.movie.status("Processing frame %d" % fn) pts = array([a.coord(cs) for a in atoms], float32) if self.movie.holdingSteady: if bound is not None: steadyPoints = array([a.coord(cs) for a in steadyAtoms], float32) closeIndices = find_close_points( BOXES_METHOD, steadyPoints, #otherPoints, bound)[1] pts, bound)[1] pts = pts[closeIndices] try: xf, inv = self.movie.transforms[fn] except KeyError: xf, inv = self.movie.steadyXform(cs=cs) self.movie.transforms[fn] = (xf, inv) xf = xform_matrix(xf) affine_transform_vertices(pts, xf) affine_transform_vertices(pts, inverse) if radiiTreatment != "ignored": ptArrays = [pts] for pt, radius in zip(pts, [a.radius for a in atoms]): if radius not in insideDeltas: mul = 1 deltas = [] rad2 = radius * radius while mul * spacing <= radius: for dx in range(-mul, mul+1): for dy in range(-mul, mul+1): for dz in range(-mul, mul+1): if radiiTreatment == "uniform" \ and min(dx, dy, dz) > -mul and max(dx, dy, dz) < mul: continue key = tuple(sorted([abs(dx), abs(dy), abs(dz)])) if key not in include.setdefault(radius, {}): include[radius][key] = (dx*dx + dy*dy + dz*dz ) * sp2 <= rad2 if include[radius][key]: deltas.append([d*spacing for d in (dx,dy,dz)]) mul += 1 insideDeltas[radius] = array(deltas) if len(deltas) < 10: print deltas if insideDeltas[radius].size > 0: ptArrays.append(pt + insideDeltas[radius]) pts = concatenate(ptArrays) # add a half-voxel since volume positions are # considered to be at the center of their voxel from numpy import floor, zeros pts = floor(pts/spacing + 0.5).astype(int) for pt in pts: center = tuple(pt) gridData[center] = gridData.get(center, 0) + 1 # generate volume self.movie.status("Generating volume") axisData = zip(*tuple(gridData.keys())) minXyz = [min(ad) for ad in axisData] maxXyz = [max(ad) for ad in axisData] # allow for zero-padding on both ends dims = [maxXyz[axis] - minXyz[axis] + 3 for axis in range(3)] from numpy import zeros, transpose volume = zeros(dims, int) for index, val in gridData.items(): adjIndex = tuple([index[i] - minXyz[i] + 1 for i in range(3)]) volume[adjIndex] = val from VolumeData import Array_Grid_Data gd = Array_Grid_Data(volume.transpose(), # the "cushion of zeros" means d-1... [(d-1) * spacing for d in minXyz], [spacing] * 3) if volumeName is None: volumeName = self.movie.ensemble.name gd.name = volumeName # show volume self.movie.status("Showing volume") import VolumeViewer dataRegion = VolumeViewer.volume_from_grid_data(gd) vd = VolumeViewer.volumedialog.volume_dialog(create=True) vd.message("Volume can be saved from File menu") self.movie.status("Volume shown")
def computeVolume(self, atoms, startFrame=None, endFrame=None, bound=None, volumeName=None, step=1, spacing=0.5): # load and process frames if startFrame is None: startFrame = self.startFrame if endFrame is None: endFrame = self.endFrame if bound is not None: from _closepoints import find_close_points, BOXES_METHOD from Matrix import xform_matrix if self.holdingSteady: steadyAtoms, steadySel, steadyCS, inverse = \ self.holdingSteady # all the above used later... inverse = xform_matrix(inverse) gridData = {} from math import floor from numpy import array, float32 from _contour import affine_transform_vertices for fn in range(startFrame, endFrame + 1, step): cs = self.findCoordSet(fn) if not cs: self.status("Loading frame %d" % fn) self._LoadFrame(fn, makeCurrent=False) cs = self.findCoordSet(fn) self.status("Processing frame %d" % fn) pts = array([a.coord(cs) for a in atoms], float32) if self.holdingSteady: if bound is not None: steadyPoints = array([a.coord(cs) for a in steadyAtoms], float32) closeIndices = find_close_points( BOXES_METHOD, steadyPoints, #otherPoints, bound)[1] pts, bound)[1] pts = pts[closeIndices] try: xf, inv = self.transforms[fn] except KeyError: xf, inv = self.steadyXform(cs=cs) self.transforms[fn] = (xf, inv) xf = xform_matrix(xf) affine_transform_vertices(pts, xf) affine_transform_vertices(pts, inverse) # add a half-voxel since volume positions are # considered to be at the center of their voxel from numpy import floor, zeros pts = floor(pts / spacing + 0.5).astype(int) for pt in pts: center = tuple(pt) gridData[center] = gridData.get(center, 0) + 1 # generate volume self.status("Generating volume") axisData = zip(*tuple(gridData.keys())) minXyz = [min(ad) for ad in axisData] maxXyz = [max(ad) for ad in axisData] # allow for zero-padding on both ends dims = [maxXyz[axis] - minXyz[axis] + 3 for axis in range(3)] from numpy import zeros, transpose volume = zeros(dims, int) for index, val in gridData.items(): adjIndex = tuple([index[i] - minXyz[i] + 1 for i in range(3)]) volume[adjIndex] = val from VolumeData import Array_Grid_Data gd = Array_Grid_Data( volume.transpose(), # the "cushion of zeros" means d-1... [(d - 1) * spacing for d in minXyz], [spacing] * 3) if volumeName is None: volumeName = self.ensemble.name gd.name = volumeName # show volume self.status("Showing volume") import VolumeViewer dataRegion = VolumeViewer.volume_from_grid_data(gd) vd = VolumeViewer.volumedialog.volume_dialog(create=True) vd.message("Volume can be saved from File menu") self.status("Volume shown")
def computeVolume(self, atoms, startFrame=None, endFrame=None, bound=None, volumeName=None, step=1, spacing=0.5): # load and process frames if startFrame is None: startFrame = self.startFrame if endFrame is None: endFrame = self.endFrame if bound is not None: from _closepoints import find_close_points, BOXES_METHOD from Matrix import xform_matrix if self.holdingSteady: steadyAtoms, steadySel, steadyCS, inverse = \ self.holdingSteady # all the above used later... inverse = xform_matrix(inverse) gridData = {} from math import floor from numpy import array, float32 from _contour import affine_transform_vertices for fn in range(startFrame, endFrame+1, step): cs = self.findCoordSet(fn) if not cs: self.status("Loading frame %d" % fn) self._LoadFrame(fn, makeCurrent=False) cs = self.findCoordSet(fn) self.status("Processing frame %d" % fn) pts = array([a.coord(cs) for a in atoms], float32) if self.holdingSteady: if bound is not None: steadyPoints = array([a.coord(cs) for a in steadyAtoms], float32) closeIndices = find_close_points( BOXES_METHOD, steadyPoints, #otherPoints, bound)[1] pts, bound)[1] pts = pts[closeIndices] try: xf, inv = self.transforms[fn] except KeyError: xf, inv = self.steadyXform(cs=cs) self.transforms[fn] = (xf, inv) xf = xform_matrix(xf) affine_transform_vertices(pts, xf) affine_transform_vertices(pts, inverse) # add a half-voxel since volume positions are # considered to be at the center of their voxel from numpy import floor, zeros pts = floor(pts/spacing + 0.5).astype(int) for pt in pts: center = tuple(pt) gridData[center] = gridData.get(center, 0) + 1 # generate volume self.status("Generating volume") axisData = zip(*tuple(gridData.keys())) minXyz = [min(ad) for ad in axisData] maxXyz = [max(ad) for ad in axisData] # allow for zero-padding on both ends dims = [maxXyz[axis] - minXyz[axis] + 3 for axis in range(3)] from numpy import zeros, transpose volume = zeros(dims, int) for index, val in gridData.items(): adjIndex = tuple([index[i] - minXyz[i] + 1 for i in range(3)]) volume[adjIndex] = val from VolumeData import Array_Grid_Data gd = Array_Grid_Data(volume.transpose(), # the "cushion of zeros" means d-1... [(d-1) * spacing for d in minXyz], [spacing] * 3) if volumeName is None: volumeName = self.ensemble.name gd.name = volumeName # show volume self.status("Showing volume") import VolumeViewer dataRegion = VolumeViewer.volume_from_grid_data(gd) vd = VolumeViewer.volumedialog.volume_dialog(create=True) vd.message("Volume can be saved from File menu") self.status("Volume shown")