def volume_linearBarycenterSave(session, volumes, folder, frames = 25, niter = 20, reg = None, rate = 'Linear', interpolate_colors = True, subregion = 'all', step = 1, maxsize = None, model_id = None): '''OT interpolate between maps.''' if len(volumes) < 2: raise CommandError('volume morph requires 2 or more volumes, got %d' % len(volumes)) vs = [tuple(v.matrix_size(step = step, subregion = subregion)) for v in volumes] if len(set(vs)) > 1: sizes = ' and '.join([str(s) for s in vs]) raise CommandError("Volume grid sizes don't match: %s" % sizes) if frames > 0 : play_step = 1./frames if not (maxsize == None): if np.product(vs[0]) > maxsize**3 : print('Your structure is bigger than maxsize, resizing for better tractability') print('resizing volumes to maxsize') print('You can change maxsize option to prevent resizing') downscale_ratio = round(max(list(set(vs))[0])/maxsize) step = downscale_ratio if reg == None : reg = max(volumes[0].matrix(step = step, subregion = subregion).shape)/60. from .mergedmorph import linear_save linear_save(volumes, folder, frames, niter, reg, rate, subregion, step, model_id)
def volume_morphOT(session, volumes, frames = 25, start = 0, play_step = .04, play_direction = 1, niter = 20, reg = None, rate = 'linear', play_range = None, constant_volume = False, scale_factors = None, hide_original_maps = True, interpolate_colors = True, maxsize = 60, subregion = 'all', step = 1, model_id = None): '''OT interpolate between maps.''' if len(volumes) < 2: raise CommandError('volume morph requires 2 or more volumes, got %d' % len(volumes)) if play_range is None: prange = (0.0,1.0) else: prange = play_range if not scale_factors is None and len(volumes) != len(scale_factors): raise CommandError('Number of scale factors (%d) does not match number of volumes (%d)' % (len(scale_factors), len(volumes))) vs = [tuple(v.matrix_size(step = step, subregion = subregion)) for v in volumes] if len(set(vs)) > 1: sizes = ' and '.join([str(s) for s in vs]) raise CommandError("Volume grid sizes don't match: %s" % sizes) """if play_step == None : #Not putting those line allows bouncing back if frames > 0 : play_step = 1./frames #bounces back #play_step = (prange[-1] - prange[0]) / float(frames) #doesnt bounce back""" if np.product(vs[0]) > maxsize**3 : print('Your structure is bigger than maxsize, you might consider using barycenterSave for efficiency issue') print('resizing volumes to maxsize') downscale_ratio = round(max(list(set(vs))[0])/maxsize) step = downscale_ratio if reg == None : reg = max(volumes[0].matrix(step = step, subregion = subregion).shape) / 60. from .mergedmorph import morph_maps_ot im = morph_maps_ot(volumes, frames, start, play_step, play_direction, prange, constant_volume, scale_factors, hide_original_maps, interpolate_colors, subregion, step, model_id, niter, reg, rate) return im
def shape_box_path(session, atoms, width = 1.0, twist = 0.0, color = (190,190,190,255), center = None, rotation = None, qrotation = None, coordinate_system = None, mesh = False, slab = None, report_cuts = False, cut_scale = 1.0, name = 'box path', model_id = None): if len(atoms) < 2: raise CommandError('Must specify at least 2 atoms, got %d' % len(atoms)) points = atoms.scene_coords from .boxpath import box_path varray, tarray = box_path(points, width, twist) if report_cuts: from .boxpath import cut_distances cuts = cut_distances(varray) lines = '\n'.join(['\t'.join(['%6.2f'%(d*cut_scale,) for d in cut]) for cut in cuts]) session.logger.info('Box cuts for %d segments\n' % len(cuts) + lines + '\n') p = _show_surface(session, varray, tarray, color, mesh, center, rotation, qrotation, coordinate_system, slab, model_id, name) return p
def shape_sphere(session, radius = 1.0, center = None, rotation = None, qrotation = None, coordinate_system = None, divisions = 72, color = (190,190,190,255), mesh = False, slab = None, name = None, model_id = None): ntri = _sphere_triangles(divisions) from chimerax.geometry.sphere import sphere_triangulation varray, tarray = sphere_triangulation(ntri) if isinstance(radius, (float, int)): varray *= radius sphere = True elif isinstance(radius, (list, tuple)): for a in range(3): varray[:,a] *= radius[a] sphere = (radius[1] == radius[0] and radius[2] == radius[0]) else: # TODO: Need to handle numpy arrays. raise CommandError('shape sphere: radius is not a float, int, list or tuple, got "%s" type %s' % (radius, repr(radius))) from chimerax.core.commands import Center if isinstance(center, Center): center = center.scene_coordinates() if name is None: name = 'sphere' if sphere else 'ellipsoid' s = _show_surface(session, varray, tarray, color, mesh, center, rotation, qrotation, coordinate_system, slab, model_id, name) return s
def shape_ribbon(session, atoms, follow_bonds = False, width = 1.0, height = 0.1, yaxis = None, twist = 0, divisions = 15, segment_subdivisions = 10, color = None, band_length = 0.0, mesh = None, name = 'ribbon', model_id = None): if len(atoms) == 0: raise CommandError('No atoms specified') from chimerax.surface.tube import ribbon_through_atoms va,na,ta,ca = ribbon_through_atoms(atoms, width, yaxis, twist, band_length, segment_subdivisions, divisions, follow_bonds, color) if va is None: return None if height != 0: from chimerax.mask.depthmask import slab_surface va, na, ta = slab_surface(va, ta, na, (-0.5*height, 0.5*height), sharp_edges = True) from numpy import concatenate ca = concatenate((ca,ca,ca,ca)) s = _surface_model(session, model_id, name) s.set_geometry(va, na, ta) s.vertex_colors = ca if mesh or (mesh is None and width == 0): s.display_style = s.Mesh _add_surface(s) return s
def shape_icosahedron(session, radius = 1.0, center = None, rotation = None, qrotation = None, coordinate_system = None, divisions = 72, color = (190,190,190,255), mesh = None, sphere_factor = 0.0, orientation = '222', lattice = None, slab = None, name = 'icosahedron', model_id = None): from chimerax.geometry.icosahedron import coordinate_system_names as csnames if orientation not in csnames: raise CommandError('Unknown orientation "%s", use %s' % (orientation, ', '.join(csnames))) if lattice is not None and mesh is None: mesh = True if lattice is None: varray, tarray = icosahedral_geometry(radius, divisions, sphere_factor, orientation) edge_mask = None else: hk = lattice varray, tarray, edge_mask = hk_icosahedral_geometry(radius, hk, sphere_factor, orientation) s = _show_surface(session, varray, tarray, color, mesh, center, rotation, qrotation, coordinate_system, slab, model_id, name, edge_mask = edge_mask) return s
def volume_barycenterOT(session, volumes, weights, niter=20, reg=None, interpolate_colors=True, subregion='all', step=1, model_id=None, maxsize=60): '''computes one weighted barycenter between two or more maps.''' if len(volumes) < 2: raise CommandError('volume morph requires 2 or more volumes, got %d' % len(volumes)) vs = [ tuple(v.matrix_size(step=step, subregion=subregion)) for v in volumes ] if len(set(vs)) > 1: sizes = ' and '.join([str(s) for s in vs]) raise CommandError("Volume grid sizes don't match: %s" % sizes) if np.product(vs[0]) > maxsize**3: print( 'Your structure is bigger than maxsize, resizing for better tractability' ) print('resizing volumes to maxsize') print('You can change maxsize option to prevent resizing') downscale_ratio = round(max(list(set(vs))[0]) / maxsize) step = downscale_ratio if reg == None: reg = max(volumes[0].matrix(step=step, subregion=subregion).shape) / 60. from .mergedmorph import ot_barycenter im = ot_barycenter(volumes, weights, niter, reg, subregion, step, model_id) return im
def shape_triangle(session, atoms = None, point = None, color = (190,190,190,255), mesh = False, center = None, rotation = None, qrotation = None, coordinate_system = None, divisions = 1, slab = None, name = 'triangle', model_id = None): points = point # List of points. Name is point so user command repeated option name is "point" if atoms is not None: if len(atoms) != 3: raise CommandError('shape triangle: Must specify 3 atoms, got %d' % len(atoms)) if (center is not None or rotation is not None or qrotation is not None or coordinate_system is not None): raise CommandError('shape triangle: Cannot use center, rotation, qrotation, ' 'or coordinateSystem options if atom positions are used.') vertices = atoms.scene_coords elif points is not None: if len(points) != 3: raise CommandError('shape triangle: Must specify 3 points, got %d' % len(points)) from chimerax.core.commands import Center vertices = [(p.scene_coordinates() if isinstance(p,Center) else p) for p in points] else: # Equilateral triangle centered at origin, edge length 1. from math import sqrt vertices = ((-0.5,-sqrt(3)/6,0),(0.5,-sqrt(3)/6,0),(0,sqrt(3)/3,0)) from numpy import array, float32, int32 varray = array(vertices, float32) tarray = array(((0,1,2),), int32) div = 1 while divisions > div: from chimerax.surface import subdivide_triangles varray, tarray = subdivide_triangles(varray, tarray) div *= 2 s = _show_surface(session, varray, tarray, color, mesh, center, rotation, qrotation, coordinate_system, slab, model_id, name, sharp_slab = True) return s
def shape_tube(session, atoms, radius = 1.0, band_length = 0.0, follow_bonds = False, divisions = 15, segment_subdivisions = 10, color = None, mesh = None, name = 'tube', model_id = None): if len(atoms) == 0: raise CommandError('No atoms specified') from chimerax.surface.tube import tube_through_atoms va,na,ta,ca = tube_through_atoms(atoms, radius, band_length, segment_subdivisions, divisions, follow_bonds, color) if va is None: return None s = _surface_model(session, model_id, name) s.set_geometry(va, na, ta) s.vertex_colors = ca if mesh or (mesh is None and radius == 0): s.display_style = s.Mesh _add_surface(s) return s
def movie_record(session, directory=None, pattern=None, format=None, size=None, supersample=1, limit=90000): '''Start recording a movie. Parameters ---------- directory : string A temporary directory for saving image files before the movie is encoded. If a directory is specified, it must already exist -- it will not be created. If no directory is specified a temporary system directory is created. pattern : string File name including a "*" character that is substituted with the frame number when saving images. format : string Image file format (default ppm) for saving frames. Possible values ppm, png, jpeg. ppm is fastest but takes the most disk space because it is not compressed. size : 2 int Width and height in pixels of movie. supersample : int Amount of supersampling when saving individual image frames. limit : int Maximum number of frames to save. This is a safe guard so that the entire computer disk storage is not filled with images if a movie recording is never stopped. ''' if ignore_movie_commands(session): return from . import formats if format is None: format = formats.default_image_format else: fmts = formats.image_formats format = format.upper() if not format in fmts: raise CommandError('Unsupported image file format %s, use %s' % (format, ', '.join(fmts))) from os.path import isdir, expanduser if directory and not isdir(expanduser(directory)): raise CommandError('Directory %s does not exist' % (directory, )) if pattern and pattern.count('*') != 1: raise CommandError('Pattern must contain exactly one "*"') if not size is None and len(size) != 2: raise CommandError('Size must be two comma-separated integers') if not supersample is None and supersample < 0: raise CommandError('Supersample must be a positive integer') movie = getattr(session, 'movie', None) if movie is None: from .movie import Movie movie = Movie(format, directory, pattern, size, supersample, limit, False, session) session.movie = movie elif movie.is_recording(): raise CommandError("Already recording a movie") else: movie.supersample = supersample movie.limit = limit movie.start_recording()
def encode_op(session, output=None, format=None, quality=None, qscale=None, bitrate=None, framerate=25, round_trip=False, reset_mode=RESET_CLEAR, wait=False, verbose=False): from . import formats output_size = None bit_rate = None qual = None if output: from os import path output = path.expanduser(output) if format is None: if output: format = format_from_file_suffix(output) if format is None: suffixes = set(fmt['suffix'] for fmt in formats.formats.values()) sufs = ', '.join('*.%s' % s for s in suffixes) from os.path import basename raise CommandError( 'Unrecognized movie file suffix %s, use %s' % (basename(output), sufs)) if format is None: fmt_name = formats.default_video_format elif format.lower() in formats.formats: fmt_name = format.lower() else: raise CommandError('Unrecognized movie format %s' % format) f = formats.formats[fmt_name] if bitrate is None and qscale is None and quality is None: quality = formats.default_quality if quality: qopt = f['ffmpeg_quality'] qual = (qopt['option_name'], qopt[quality]) elif qscale: qual = ('-qscale:v', qscale) elif bitrate: bit_rate = bitrate if output is None: import os.path ext = f['suffix'] from .movie import DEFAULT_OUTFILE output = '%s.%s' % (os.path.splitext(DEFAULT_OUTFILE)[0], ext) movie = getattr(session, 'movie', None) if movie is None: raise CommandError('No frames have been recorded') if movie.is_recording(): movie.stop_recording() movie.verbose = verbose movie.start_encoding(output, f['ffmpeg_name'], output_size, f['ffmpeg_codec'], "yuv420p", f['size_restriction'], framerate, bit_rate, qual, round_trip, reset_mode)