def Apply(self):
        val = self.seqMenu1.get()
        if val == self.ALL:
            seqs1 = self.mav.seqs
        else:
            seqs1 = [s for s in self.mav.seqs if s.name == val]
        val = self.seqMenu2.get()
        if val == self.ALL:
            seqs2 = self.mav.seqs
        else:
            seqs2 = [s for s in self.mav.seqs if s.name == val]

        denom = self.denominator.get()
        for s1 in seqs1:
            for s2 in seqs2:
                pi = percentIdentity(s1, s2, denominator=denom)
                self.mav.status("%s vs. %s:\n"
                                "   %.2f%% identity\n" %
                                (s1.name, s2.name, pi))
                # since once OK is clicked, the mouse may be
                # over a part of the alignment that causes a
                # status message, also send to regular status
                # line
                replyobj.status("%s vs. %s: %.2f%% identity\n" %
                                (s1.name, s2.name, pi),
                                log=True)
        if len(seqs1) > 1 or len(seqs2) > 1:
            self.mav.status("Percent identity info in Reply Log")
            from chimera import dialogs, tkgui
            dialogs.display(tkgui._ReplyDialog.name)
 def Apply(self):
     selectedResidues = chimera.selection.currentResidues()
     if not selectedResidues:
         self.enter()
         raise UserError("No residues selected")
     if len(selectedResidues) > 10:
         from chimera.baseDialog import AskYesNoDialog
         numSel = len(selectedResidues)
         if AskYesNoDialog("You have %d residues selected which"
                           " could bring up %d rotamer dialogs.\n"
                           "Continue?" % (numSel, numSel)).run(
                               chimera.tkgui.app) == "no":
             self.enter()
             return
     resType = self.resType.get()
     lib = self.rotLib.get()
     from Rotamers import NoResidueRotamersError
     try:
         for sr in selectedResidues:
             RotamerDialog(sr, resType, lib)
     except NoResidueRotamersError:
         from SwapRes import swap
         for sr in selectedResidues:
             replyobj.info("Swapping %s to %s\n" % (sr, resType))
             swap(sr, resType, bfactor=None)
         replyobj.status("Swapped %d residue(s)\n" % len(selectedResidues))
Exemple #3
0
def write_grasp_surface_file():

    from chimera import openModels
    from _surface import SurfaceModel
    mlist = openModels.list(modelTypes=[SurfaceModel])

    if len(mlist) == 0:
        from chimera import replyobj
        replyobj.status('No displayed surfaces')
        return

    varray, tarray, narray = surface_geometry(mlist)
    if len(tarray) == 0:
        from chimera import replyobj
        replyobj.status('No displayed triangles')
        return

    def save_geometry(okay, d, varray=varray, tarray=tarray, narray=narray):
        if not okay:
            return  # User canceled action.
        path = d.getPaths()[0]
        f = grasp_surface_file(varray, tarray, narray)
        file = open(path, 'wb')
        file.write(f)
        file.close()

    from OpenSave import SaveModeless
    SaveModeless(title="Save Surface",
                 filters=[('GRASP surface', ['*.srf'], '.srf')],
                 command=save_geometry)
 def _deregisteredTask(self, iTask):
     # This is called after the user task instance has been
     # disposed of.
     from chimera import replyobj
     if iTask.modal:
         self._modalTasks.remove(iTask)
     if iTask.canceled:
         msg = "canceled"
     else:
         msg = "finished"
     replyobj.status("%s: %s\n" % (iTask.title, msg), blankAfter=10)
     import statusline
     sl = statusline.status_line(create=False)
     if iTask.modal:
         # Terminate the input grab
         if sl:
             sl.grab_task_button(False)
     else:
         # If there are no more tasks with status updates,
         # deregister our "check for changed" handler
         if self._cfcHandler and self._statusCount() == 0:
             import chimera
             chimera.triggers.deleteHandler(CFC, self._cfcHandler)
             self._cfcHandler = None
     if sl:
         sl.update_task_buttons()
     from chimera import dialogs
     d = dialogs.find(TaskPanel.name, create=False)
     if d:
         d.updateTaskStatus(iTask)
         d.refreshCancelButtons()
def startCommand(molecule,
                 name="default",
                 method="corkscrew",
                 rate="linear",
                 frames=20,
                 cartesian=False):
    from chimera import UserError
    if len(molecule) != 1:
        raise UserError("You must specify exactly one molecule")
    m = molecule[0]

    try:
        ms = _find(name)
    except UserError:
        pass
    else:
        raise UserError("You already defined \"%s\"" % name)
    kw = {
        "method": method,
        "rate": rate,
        "frames": frames,
        "cartesian": cartesian,
    }
    _verifyOpts(kw)
    from base import Script
    ms = Script(m, closeCB=_close, **kw)
    _add(name, ms)
    from chimera import replyobj
    msg = "Interpolation \"%s\" created\n" % name
    replyobj.message(msg)
    replyobj.status(msg)
    return ms
Exemple #6
0
def move_atom_to_maximum(a,
                         max_steps=2000,
                         ijk_step_size_min=0.001,
                         ijk_step_size_max=0.5):

    from chimerax.map import active_volume
    dr = active_volume()
    if dr == None or dr.model_transform() == None:
        from chimera.replyobj import status
        status('No data shown by volume viewer dialog')
        return

    points = atom_coordinates([a])
    point_weights = None
    move_tf, stats = motion_to_maximum(points,
                                       point_weights,
                                       dr,
                                       max_steps,
                                       ijk_step_size_min,
                                       ijk_step_size_max,
                                       optimize_translation=True,
                                       optimize_rotation=False)

    # Update atom position.
    p = a.structure.position.inverse() * (move_tf * a.xformCoord())
    a.setCoord(p)
Exemple #7
0
def pairAlign(chains, cutoff, gapChar, statusPrefix=""):
	chain1, chain2 = chains

	# go through chain 1 and put each residue's principal
	# atom in a spatial tree
	from chimera.misc import principalAtom
	from CGLutil.AdaptiveTree import AdaptiveTree
	xyzs = []
	data = []
	for i in range(len(chain1)):
		res = chain1.residues[i]
		pa = principalAtom(res)
		if not pa:
			replyobj.warning("Cannot determine principal"
					" atom for residue %s\n"
					% res.oslIdent())
			continue
		xyzs.append(pa.xformCoord().data())
		data.append((i, pa.xformCoord()))
	tree = AdaptiveTree(xyzs, data, cutoff)

	# initialize score array
	from numpy import zeros
	scores = zeros((len(chain1),len(chain2)), float)
	scores -= 1.0

	# find matches and update score array
	for i2 in range(len(chain2)):
		res = chain2.residues[i2]
		pa = principalAtom(res)
		if not pa:
			replyobj.warning("Cannot determine principal"
					" atom for residue %s\n"
					% res.oslIdent())
			continue
		coord2 = pa.xformCoord()
		matches = tree.searchTree(coord2.data(), cutoff)
		for i1, coord1 in matches:
			dist = coord1.distance(coord2)
			if dist > cutoff:
				continue
			scores[i1][i2] = cutoff - dist

	# use NeedlemanWunsch to establish alignment
	from NeedlemanWunsch import nw
	score, seqs = nw(chain1, chain2, scoreMatrix=scores, gapChar=gapChar,
			returnSeqs=True, scoreGap=0, scoreGapOpen=0)
	smallest = min(len(chain1), len(chain2))
	minDots = max(len(chain1), len(chain2)) - smallest
	extraDots = len(seqs[0]) - smallest - minDots
	numMatches = smallest - extraDots
	replyobj.status("%s%d residue pairs aligned\n"
				% (statusPrefix, numMatches), log=True)

	if numMatches == 0:
		from chimera import UserError
		raise UserError("Cannot generate alignment because no"
					" residues within cutoff distance")
		
	return score, seqs
Exemple #8
0
	def myRunCommand(*args):
		from Midas import MidasError
		try:
			runCommand(*args)
		except MidasError, v:
			from chimera import replyobj
			replyobj.status(str(v), color="red")
def startCommand(molecule, name="default", method="corkscrew",
			rate="linear", frames=20, cartesian=False):
	from chimera import UserError
	if len(molecule) != 1:
		raise UserError("You must specify exactly one molecule")
	m = molecule[0]

	try:
		ms = _find(name)
	except UserError:
		pass
	else:
		raise UserError("You already defined \"%s\"" % name)
	kw = {
		"method": method,
		"rate": rate,
		"frames": frames,
		"cartesian": cartesian,
	}
	_verifyOpts(kw)
	from base import Script
	ms = Script(m, closeCB=_close, **kw)
	_add(name, ms)
	from chimera import replyobj
	msg = "Interpolation \"%s\" created\n" % name
	replyobj.message(msg)
	replyobj.status(msg)
	return ms
Exemple #10
0
def fetch_file(url, name, minimum_file_size = None, save_dir = '',
			save_name = '', uncompress = False, ignore_cache = False):
	"""a fetched non-local file that doesn't get cached will be
	   removed when Chimera exits

	   if 'ignore_cache' is True, then cached values will be ignored,
	   though the retrieved values will still be cached if appropriate
	"""

	from chimera.replyobj import status
	status('Fetching %s\n' % (name,))
	
	if save_name and not ignore_cache:
		path = fetch_local_file(save_dir, save_name)
		if path:
			return path, {}

	from chimera import tasks
	task = tasks.Task("Fetch %s" % name, modal=True)
	def report_cb(barrived, bsize, fsize):
		if fsize > 0:
			percent = min(100.0,(100.0*barrived*bsize)/fsize)
			prog = '%.0f%% of %s' % (percent, byte_text(fsize))
		else:
			prog = '%s received' % (byte_text(barrived*bsize),)
		task.updateStatus(prog)
	# TODO: In Python 2.5 socket.error is not an IOError, but in Python 2.6
	#       it is.  Remove socket error when Chimera uses Python 2.6.
	import urllib, socket
	try:
		path, headers = urllib.urlretrieve(url, reporthook = report_cb)
	except (IOError, socket.error), v:
		from chimera import NonChimeraError
		raise NonChimeraError('Error fetching %s: %s' % (name, str(v)))
 def __init__(self, topology, trajFileName):
     # since we need to be able to do seeks, can't use osOpen
     # which might return an unseekable stream
     self.topology = topology
     from OpenSave import osUncompressedPath
     path = osUncompressedPath(trajFileName)
     import os
     self.trajFileSize = os.stat(path).st_size
     self.traj = open(path, "rb")
     from xdrlib import Unpacker
     self.fileString = FileString(self.traj, 0, self.trajFileSize)
     self.xdr = Unpacker(self.fileString)
     self.crdStarts = []
     while True:
         replyobj.status("Reading frame %d header\n" %
                         (len(self.crdStarts) + 1))
         try:
             crdStart, endFrame = self._readHeader()
         except ValueError, e:
             raise ValueError("Frame %d: %s" %
                              (len(self.crdStarts) + 1, str(e)))
         if endFrame > self.trajFileSize:
             if not self.crdStarts:
                 raise ValueError("Computed size of"
                                  " first frame (%d) greater than"
                                  " trajectory file size (%s)" %
                                  (endFrame, self.trajFileSize))
             replyobj.warning("Truncated trajectory file;"
                              " skipping last partial frame.\n")
         else:
             self.crdStarts.append(crdStart)
         if endFrame == self.trajFileSize:
             break
         self.xdr.set_position(endFrame)
    def toggle_fly_mode(self):

        self.fly_mode = not self.fly_mode
        from chimera import viewer
        viewer.clipping = False
        from chimera.replyobj import status
        status('fly through mode: %s' % self.fly_mode)
Exemple #13
0
    def toggle_fly_mode(self):

        self.fly_mode = not self.fly_mode
        from chimera import viewer
        viewer.clipping = False
        from chimera.replyobj import status
        status('fly through mode: %s' % self.fly_mode)
def report_correlations_with_rotation(v1, v2, aboveThreshold, axis, center,
                                      angleRange, plot):

    from chimera import Vector, Point, replyobj

    # Convert axis and center to v1 local coordinates so transformation
    # is still valid if user rotates entire scene.
    xf = v1.openState.xform.inverse()
    axis = xf.apply(Vector(*axis)).data()
    center = xf.apply(Point(*center)).data()

    import FitMap, Matrix
    replyobj.info('Correlation between %s and %s\n' % (v1.name, v2.name) +
                  'Rotation\tCorrelation\n')
    a0, a1, astep = angleRange
    angle = a0
    clist = []
    from Matrix import multiply_matrices, xform_matrix, rotation_transform, chimera_xform
    while angle < a1:
        tf = multiply_matrices(xform_matrix(v1.openState.xform),
                               rotation_transform(axis, angle, center),
                               xform_matrix(v1.openState.xform.inverse()))
        xf = chimera_xform(tf)
        olap, cor = FitMap.map_overlap_and_correlation(v1, v2, aboveThreshold,
                                                       xf)
        replyobj.status('angle = %.4g, correlation = %.4g\n' % (angle, cor))
        replyobj.info('%.4g\t%.4g\n' % (angle, cor))
        clist.append((angle, cor))
        angle += astep

    if plot:
        angles = [a for a, c in clist]
        corr = [c for a, c in clist]
        plot_correlation(angles, corr, v1, v2, axis, center)
def write_grasp_surface_file():

    from chimera import openModels
    from _surface import SurfaceModel
    mlist = openModels.list(modelTypes = [SurfaceModel])

    if len(mlist) == 0:
        from chimera import replyobj
        replyobj.status('No displayed surfaces')
        return

    varray, tarray, narray = surface_geometry(mlist)
    if len(tarray) == 0:
        from chimera import replyobj
        replyobj.status('No displayed triangles')
        return
    
    def save_geometry(okay, d, varray=varray, tarray=tarray, narray=narray):
        if not okay:
            return          # User canceled action.
        path = d.getPaths()[0]
        f = grasp_surface_file(varray, tarray, narray)
        file = open(path, 'wb')
        file.write(f)
        file.close()

    from OpenSave import SaveModeless
    SaveModeless(title = "Save Surface",
                 filters = [('GRASP surface', ['*.srf'], '.srf')],
                 command = save_geometry)
def align_backbones_using_selected_atoms():

    # Find atom pairs
    from chimera import selection
    a1, a2 = backbone_atom_pairs(selection.currentAtoms())
    if a1 == None:
        return

    # Compute alignment
    from chimera import match
    xform, rmsd = match.matchAtoms(a1, a2)

    # Apply transformation
    m1 = a1[0].molecule
    m2 = a2[0].molecule
    xf = m1.openState.xform
    xf.multiply(xform)
    xf2 = m2.openState.xform
    m2.openState.xform = xf

    # Report atom count, rmsd, and angle
    xf2.invert()
    xf.multiply(xf2)
    axis, angle = xf.getRotation()
    from chimera import replyobj
    replyobj.status('RMSD between %d atom pairs is %.3f angstroms, rotation angle = %.2f degrees\n'
                    % (len(a1), rmsd, angle), log = True)
def backbone_atom_pairs(atoms):
    
    nmol = len(atom_molecules(atoms))
    if nmol != 2:
        from chimera import replyobj
        replyobj.status('alignment: Must select atoms from 2 molecules (%d selected).\n' % nmol, log = True)
        return None, None

    bb_atoms = filter(lambda a: a.name == 'CA' or a.name == 'P', atoms)
        
    atom_pairs = paired_alignment_atoms(bb_atoms)
    if len(atom_pairs) < 3:
        from chimera import replyobj
        replyobj.status('alignment: Too few backbone atom pairs (%d).\n' %
                        len(atom_pairs), log = True)
        return None, None

    a1 = map(lambda p: p[0], atom_pairs)
    a2 = map(lambda p: p[1], atom_pairs)

    m1 = a1[0].molecule
    m2 = a2[0].molecule
    if (m1.id, m1.subid) > (m2.id, m2.subid):
        return a2, a1

    return a1, a2
Exemple #18
0
def show_field_lines(v,
                     num_lines=1000,
                     min_potential=10,
                     step=0.5,
                     color=(.7, .7, .7, 1),
                     line_width=1,
                     tube_radius=None,
                     circle_subdivisions=12,
                     markers=False,
                     model_id=None):

    if min_potential is None:
        min_potential = v.surface_levels[-1] if v.surface_levels else 10

    start_points, cutoff = find_starting_points(v, num_lines, min_potential)

    n = len(start_points)
    lines = []
    for i, xyz in enumerate(start_points):
        if i % 100 == 0:
            from chimera.replyobj import status
            status('Computing field line %d of %d' % (i, n))
        line = trace_field_line(v, xyz, cutoff, min_potential, step)
        lines.append(line)

    if markers:
        draw_marker_lines(lines, v, color, tube_radius, model_id)
    elif tube_radius is None:
        draw_mesh_lines(lines, v, color, line_width, model_id)
    else:
        draw_tube_lines(lines, v, color, tube_radius, circle_subdivisions,
                        model_id)
Exemple #19
0
def align_backbones_using_selected_atoms():

    # Find atom pairs
    from chimera import selection
    a1, a2 = backbone_atom_pairs(selection.currentAtoms())
    if a1 == None:
        return

    # Compute alignment
    from chimera import match
    xform, rmsd = match.matchAtoms(a1, a2)

    # Apply transformation
    m1 = a1[0].molecule
    m2 = a2[0].molecule
    xf = m1.openState.xform
    xf.multiply(xform)
    xf2 = m2.openState.xform
    m2.openState.xform = xf

    # Report atom count, rmsd, and angle
    xf2.invert()
    xf.multiply(xf2)
    axis, angle = xf.getRotation()
    from chimera import replyobj
    replyobj.status(
        'RMSD between %d atom pairs is %.3f angstroms, rotation angle = %.2f degrees\n'
        % (len(a1), rmsd, angle),
        log=True)
Exemple #20
0
	def _deregisteredTask(self, iTask):
		# This is called after the user task instance has been
		# disposed of.
		from chimera import replyobj
		if iTask.modal:
			self._modalTasks.remove(iTask)
		if iTask.canceled:
			msg = "canceled"
		else:
			msg = "finished"
		replyobj.status("%s: %s\n" % (iTask.title, msg), blankAfter=10)
		import statusline
		sl = statusline.status_line(create=False)
		if iTask.modal:
			# Terminate the input grab
			if sl:
				sl.grab_task_button(False)
		else:
			# If there are no more tasks with status updates,
			# deregister our "check for changed" handler
			if self._cfcHandler and self._statusCount() == 0:
				import chimera
				chimera.triggers.deleteHandler(CFC,
						self._cfcHandler)
				self._cfcHandler = None
		if sl:
			sl.update_task_buttons()
		from chimera import dialogs
		d = dialogs.find(TaskPanel.name, create=False)
		if d:
			d.updateTaskStatus(iTask)
			d.refreshCancelButtons()
  def mouse_drag_cb(self, v, e):

    if self.last_xy is None:
      self.last_xy = (e.x, e.y)
      return
    
    import Surface
    plist = Surface.selected_surface_pieces()
    if len(plist) == 0:
      from chimera.replyobj import status
      status('No surfaces selected for resizing')
      return

    dx, dy = (e.x - self.last_xy[0], self.last_xy[1] - e.y)
    delta = dx + dy
    self.last_xy = (e.x, e.y)

    shift_mask = 1
    shift = (e.state & shift_mask)
    if shift:
      factor_per_pixel = 1.001  # shift key held so scale by smaller amount
    else:
      factor_per_pixel = 1.01

    factor = factor_per_pixel ** delta
    for p in plist:
      scale_surface_piece(p, factor)
Exemple #22
0
def names_of_last_opened():
    'Show the names of the last 3 opened files on the status line'
    paths = recent_opened_files()
    import os.path
    last3 = ', '.join(map(os.path.basename, paths[:3]))
    from chimera.replyobj import status
    status(last3)
Exemple #23
0
def backbone_atom_pairs(atoms):

    nmol = len(atom_molecules(atoms))
    if nmol != 2:
        from chimera import replyobj
        replyobj.status(
            'alignment: Must select atoms from 2 molecules (%d selected).\n' %
            nmol,
            log=True)
        return None, None

    bb_atoms = filter(lambda a: a.name == 'CA' or a.name == 'P', atoms)

    atom_pairs = paired_alignment_atoms(bb_atoms)
    if len(atom_pairs) < 3:
        from chimera import replyobj
        replyobj.status('alignment: Too few backbone atom pairs (%d).\n' %
                        len(atom_pairs),
                        log=True)
        return None, None

    a1 = map(lambda p: p[0], atom_pairs)
    a2 = map(lambda p: p[1], atom_pairs)

    m1 = a1[0].molecule
    m2 = a2[0].molecule
    if (m1.id, m1.subid) > (m2.id, m2.subid):
        return a2, a1

    return a1, a2
Exemple #24
0
	def __init__(self, topology, trajFileName):
		# since we need to be able to do seeks, can't use osOpen
		# which might return an unseekable stream
		self.topology = topology
		from OpenSave import osUncompressedPath
		path = osUncompressedPath(trajFileName)
		import os
		self.trajFileSize = os.stat(path).st_size
		self.traj = open(path, "rb")
		from xdrlib import Unpacker
		self.fileString = FileString(self.traj, 0, self.trajFileSize)
		self.xdr = Unpacker(self.fileString)
		self.crdStarts = []
		while True:
			replyobj.status("Reading frame %d header\n" % (
						len(self.crdStarts) + 1))
			try:
				crdStart, endFrame = self._readHeader()
			except ValueError, e:
				raise ValueError("Frame %d: %s" %
					(len(self.crdStarts) + 1, str(e)))
			if endFrame > self.trajFileSize:
				if not self.crdStarts:
					raise ValueError("Computed size of"
						" first frame (%d) greater than"
						" trajectory file size (%s)" %
						(endFrame, self.trajFileSize))
				replyobj.warning("Truncated trajectory file;"
					" skipping last partial frame.\n")
			else:
				self.crdStarts.append(crdStart)
			if endFrame == self.trajFileSize:
				break
			self.xdr.set_position(endFrame)
Exemple #25
0
    def color_and_measure(self, window_x, window_y):

        from VolumeViewer import slice
        xyz_in, xyz_out = slice.clip_plane_points(window_x, window_y)

        import PickBlobs
        smlist = PickBlobs.surface_models()
        p, vlist, tlist = PickBlobs.picked_surface_component(
            smlist, xyz_in, xyz_out)
        if p is None:
            self.message('No intercept with surface.')
            return

        PickBlobs.color_blob(p, vlist, self.blob_color.rgba)

        # Report enclosed volume and area
        from MeasureVolume import enclosed_volume, surface_area
        varray, tarray = PickBlobs.blob_geometry(p, vlist, tlist)
        v, h = enclosed_volume(varray, tarray)
        if v == None:
            vstr = 'undefined (non-oriented surface)'
        else:
            vstr = '%.5g' % v
            if h > 0:
                vstr += ' (%d holes)' % h
        area = surface_area(varray, tarray)

        s = p.model
        msg = ('Surface %s (%s) piece: volume = %s, area = %.5g' %
               (s.name, s.oslIdent(), vstr, area))
        self.message(msg)
        from chimera.replyobj import info, status
        info(msg + '\n')
        status(msg)
def split_selected_surfaces():

    plist = selected_surface_pieces()
    if plist:
        pplist = split_surfaces(plist)
        from chimera.replyobj import status
        status('%d surface pieces' % len(pplist))
Exemple #27
0
    def report_surface_areas(self, compareas):

        mname = self.molecule.name
        cname = self.category
        ncomp = len(compareas)
        lines = \
            ['',
             'Surface %s, category %s, probe radius %.4g, vertex density %.4g'
             % (mname, cname, self.probeRadius, self.density),
             '  %d connected surface components' % ncomp,
             '  Total solvent excluded surface area = %.6g' % self.areaSES]
        if ncomp > 1:
            careas = [(sesa, sasa) for sesa, sasa in compareas]
            careas.sort()
            careas.reverse()
            eareas = ', '.join(['%.6g' % sesa for sesa, sasa in careas])
            aareas = ', '.join(['%.6g' % sasa for sesa, sasa in careas])
            lines.append('    component areas = %s' % eareas)
        lines.append('  Total solvent accessible surface area = %.6g'
                     % self.areaSAS)
        if ncomp > 1:
            lines.append('    component areas = %s' % aareas)
        msg = '\n'.join(lines) + '\n'
        from chimera.replyobj import info, status
        info(msg)

        smsg = ('Surface %s, category %s has %d components'
                % (mname, cname, ncomp))
        status(smsg)
Exemple #28
0
def report_correlations_with_rotation(v1, v2, aboveThreshold,
                                      axis, center, angleRange, plot):

    from chimera import Vector, Point, replyobj

    # Convert axis and center to v1 local coordinates so transformation
    # is still valid if user rotates entire scene.
    xf = v1.openState.xform.inverse()
    axis = xf.apply(Vector(*axis)).data()
    center = xf.apply(Point(*center)).data()

    import FitMap, Matrix
    replyobj.info('Correlation between %s and %s\n' % (v1.name, v2.name) +
                  'Rotation\tCorrelation\n')
    a0, a1, astep = angleRange
    angle = a0
    clist = []
    from Matrix import multiply_matrices, xform_matrix, rotation_transform, chimera_xform
    while angle < a1:
        tf = multiply_matrices(xform_matrix(v1.openState.xform),
                               rotation_transform(axis, angle, center),
                               xform_matrix(v1.openState.xform.inverse()))
        xf = chimera_xform(tf)
        olap, cor = FitMap.map_overlap_and_correlation(v1, v2,
                                                       aboveThreshold, xf)
        replyobj.status('angle = %.4g, correlation = %.4g\n' % (angle, cor))
        replyobj.info('%.4g\t%.4g\n' % (angle, cor))
        clist.append((angle,cor))
        angle += astep

    if plot:
        angles = [a for a,c in clist]
        corr = [c for a,c in clist]
        plot_correlation(angles, corr, v1, v2, axis, center)
	def Apply(self):
		val = self.seqMenu1.get()
		if val == self.ALL:
			seqs1 = self.mav.seqs
		else:
			seqs1 = [s for s in self.mav.seqs if s.name == val]
		val = self.seqMenu2.get()
		if val == self.ALL:
			seqs2 = self.mav.seqs
		else:
			seqs2 = [s for s in self.mav.seqs if s.name == val]

		denom = self.denominator.get()
		for s1 in seqs1:
			for s2 in seqs2:
				pi = percentIdentity(s1, s2, denominator=denom)
				self.mav.status("%s vs. %s:\n"
					"   %.2f%% identity\n" % (s1.name,
					s2.name, pi))
				# since once OK is clicked, the mouse may be
				# over a part of the alignment that causes a
				# status message, also send to regular status
				# line
				replyobj.status("%s vs. %s: %.2f%% identity\n"
					% (s1.name, s2.name, pi), log=True)
		if len(seqs1) > 1 or len(seqs2) > 1:
			self.mav.status("Percent identity info in Reply Log")
			from chimera import dialogs, tkgui
			dialogs.display(tkgui._ReplyDialog.name)
Exemple #30
0
 def _align(self, ref, match, matrix, alg, gapOpen, gapExtend, ksdsspCache,
            **alignKw):
     replyobj.status(
         "test match %s %s to %s %s" %
         (ref.molecule.name, ref.name, match.molecule.name, match.name))
     return align(ref, match, matrix, alg, gapOpen, gapExtend, ksdsspCache,
                  **alignKw)
Exemple #31
0
	def Apply(self):
		selectedResidues = chimera.selection.currentResidues()
		if not selectedResidues:
			self.enter()
			raise UserError("No residues selected")
		if len(selectedResidues) > 10:
			from chimera.baseDialog import AskYesNoDialog
			numSel = len(selectedResidues)
			if AskYesNoDialog("You have %d residues selected which"
					" could bring up %d rotamer dialogs.\n"
					"Continue?" % (numSel, numSel)).run(
					chimera.tkgui.app) == "no":
				self.enter()
				return
		resType = self.resType.get()
		lib = self.rotLib.get()
		from Rotamers import NoResidueRotamersError
		try:
			for sr in selectedResidues:
				RotamerDialog(sr, resType, lib)
		except NoResidueRotamersError:
			from SwapRes import swap
			for sr in selectedResidues:
				replyobj.info("Swapping %s to %s\n"
							% (sr, resType))
				swap(sr, resType, bfactor=None)
			replyobj.status("Swapped %d residue(s)\n"
						% len(selectedResidues))
def interpolateCommand(molecule,
                       name="default",
                       method=None,
                       rate=None,
                       frames=None,
                       cartesian=False):
    if len(molecule) != 1:
        from chimera import UserError
        raise UserError("You must specify exactly one molecule")
    m = molecule[0]

    ms = _find(name)
    kw = {}
    if method is not None:
        kw["method"] = method
    if rate is not None:
        kw["rate"] = rate
    if frames is not None:
        kw["frames"] = frames
    _verifyOpts(kw)
    ms.addAction(m, **kw)
    from chimera import replyobj
    msg = "Interpolation \"%s\" updated\n" % name
    replyobj.message(msg)
    replyobj.status(msg)
Exemple #33
0
    def report_surface_areas(self, compareas):

        mname = self.molecule.name
        cname = self.category
        ncomp = len(compareas)
        lines = \
            ['',
             'Surface %s, category %s, probe radius %.4g, vertex density %.4g'
             % (mname, cname, self.probeRadius, self.density),
             '  %d connected surface components' % ncomp,
             '  Total solvent excluded surface area = %.6g' % self.areaSES]
        if ncomp > 1:
            careas = [(sesa, sasa) for sesa, sasa in compareas]
            careas.sort()
            careas.reverse()
            eareas = ', '.join(['%.6g' % sesa for sesa, sasa in careas])
            aareas = ', '.join(['%.6g' % sasa for sesa, sasa in careas])
            lines.append('    component areas = %s' % eareas)
        lines.append('  Total solvent accessible surface area = %.6g' %
                     self.areaSAS)
        if ncomp > 1:
            lines.append('    component areas = %s' % aareas)
        msg = '\n'.join(lines) + '\n'
        from chimera.replyobj import info, status
        info(msg)

        smsg = ('Surface %s, category %s has %d components' %
                (mname, cname, ncomp))
        status(smsg)
Exemple #34
0
def symmetry(operation,
             volume,
             minimumCorrelation=0.99,
             nMax=8,
             helix=None,
             points=10000,
             set=True):

    from VolumeViewer import Volume
    vlist = [m for m in volume if isinstance(m, Volume)]
    if len(vlist) == 0:
        raise CommandError('No volume specified')

    if not helix is None:
        rise, angle, n, optimize = parse_helix_option(helix)

    import symmetry as S
    for v in vlist:
        if helix:
            syms, msg = S.find_helix_symmetry(v, rise, angle, n, optimize,
                                              nMax, minimumCorrelation, points)
        else:
            syms, msg = S.find_point_symmetry(v, nMax, minimumCorrelation,
                                              points)

        if set and syms:
            v.data.symmetries = syms

        from chimera.replyobj import info, status
        status(msg)
        info(msg + '\n')
Exemple #35
0
def map_values(operation, volume, atoms, name=None, report=10):

    from VolumeViewer import Volume
    vlist = [v for v in volume if isinstance(v, Volume)]
    if len(vlist) != 1:
        raise CommandError('No volume model specified')
    v = vlist[0]

    import AtomDensity
    if name is None:
        name = 'value_' + v.name
        name = AtomDensity.replace_special_characters(name, '_')
    AtomDensity.set_atom_volume_values(atoms, v, name)

    if report:
        arep = atoms[:report] if isinstance(report, int) else atoms
        values = '\n'.join(
            ['%s %.5g' % (a.oslIdent(), getattr(a, name)) for a in arep])
        n = len(atoms)
        t = '%s map values at %d atom positions\n%s\n' % (v.name, n, values)
        if n > len(arep):
            t += '...\n'
        if n == 1:
            s = '%s map value at atom %s = %.5g' % (
                v.name, atoms[0].oslIdent(), getattr(a, name))
        else:
            maxa = 3
            values = ', '.join(
                ['%.5g' % getattr(a, name) for a in atoms[:maxa]])
            if n > maxa:
                values += ', ...'
            s = '%s map values at %d atoms: %s' % (v.name, n, values)
        from chimera import replyobj
        replyobj.info(t)
        replyobj.status(s)
Exemple #36
0
def processModBaseID(IDcode):
	"""Locate a database ID code via ModBase, read it, and add it to the list of open models.

	_openModBaseIDModel(IDcode) => [model(s)]

	'explodeNMR' controls whether multi-MODEL files are split into
	multiple Molecules (if False, use coord sets instead)
	"""
	identifyAs = IDcode

	from chimera import replyobj
	statusName = identifyAs or IDcode

	path = fetchModBase(IDcode)

	# Open PDB file as models
	from chimera import PDBio
	import os
	pdbio = PDBio()
	pdbio.explodeNMR = False
	molList = pdbio.readPDBfile(path)
	if not pdbio.ok():
		replyobj.status("\n")
		raise UserError("Error reading PDB file: %s" % pdbio.error())
	for m in molList:
		m.name = identifyAs

	# Post-process models to convert remark records
	# into molecule dictionary attribute
	#from baseDialog import buttonFuncName as makeIdentifier
	for m in molList:
		attr = {}
		remarks = m.pdbHeaders.get("REMARK", [])
		for remark in remarks:
			parts = remark.split(None, 2)
			try:
				info = parts[2]
			except IndexError:
				continue
			try:
				key, value = [ v.strip()
						for v in info.split(':', 1) ]
			except ValueError:
				continue
			try:
				value = int(value)
			except ValueError:
				try:
					value = float(value)
				except ValueError:
					pass
			attr[key] = value
			#setattr(m, "modbase_%s" % makeIdentifier(key), value)
		assignModbaseInfo(m, attr)

	# Register open message
	chimera._openedInfo = "Opened %s\n" % statusName
	ModBaseDialog(IDcode, molList)
	return molList
Exemple #37
0
    def addTraj(self, trajFileName):
	replyobj.status("Reading %s file %s" % (self.TrajName, trajFileName),
								blankAfter=0)
	try:
		self.trajectory.addFile(trajFileName)
	finally:
		replyobj.status("Done reading %s file %s\n"
						% (self.TrajName, trajFileName))
Exemple #38
0
def split_selected_surfaces(session, in_place=True):

    import Surface
    plist = Surface.selected_surface_pieces()
    if plist:
        pplist = split_surfaces(plist, session, in_place)
        from chimera.replyobj import status
        status('%d surface pieces' % len(pplist))
Exemple #39
0
 def addTraj(self, trajFileName):
     replyobj.status("Reading %s file %s" % (self.TrajName, trajFileName),
                     blankAfter=0)
     try:
         self.trajectory.addFile(trajFileName)
     finally:
         replyobj.status("Done reading %s file %s\n" %
                         (self.TrajName, trajFileName))
 def Execute(self, options):
     #print self, "Executing DelPhi..."
     self.options = options
     self.executor = DelPhiExecutor.DelPhiExecutor(self.options)
     self.process = self.executor()
     self.checkHandler = chimera.triggers.addHandler(
         "check for changes", self.CheckProcess, None)
     replyobj.status("Running DelPhi in background")
def displayDialog(wait=False):
    if dialogs.find(BugReportGUI.name):
	replyobj.status("Bug report already in progress!",
			color="red", blankAfter=15)
	return None
    else:
	br_gui = dialogs.display(BugReportGUI.name, wait)
	return br_gui
Exemple #42
0
def report_correlation(v1, v2, aboveThreshold):
            
    from chimera import replyobj
    import FitMap
    olap, cor = FitMap.map_overlap_and_correlation(v1, v2, aboveThreshold)
    replyobj.status('correlation = %.4g\n' % cor)
    replyobj.info('Correlation between %s and %s = %.4g\n'
                  % (v1.name, v2.name, cor))
def report_correlation(v1, v2, aboveThreshold):

    from chimera import replyobj
    import FitMap
    olap, cor = FitMap.map_overlap_and_correlation(v1, v2, aboveThreshold)
    replyobj.status('correlation = %.4g\n' % cor)
    replyobj.info('Correlation between %s and %s = %.4g\n' %
                  (v1.name, v2.name, cor))
def findPruneCrosslinks(allLinks,
                        pairings,
                        seq1,
                        seq2,
                        linkList,
                        links1,
                        links2,
                        tag="",
                        statusPrefix=""):
    replyobj.status("%sFinding crosslinks %s\n" % (statusPrefix, tag),
                    blankAfter=0)

    # find crossings
    ends = []
    seq2links = []
    for links in links2:
        ends.append(len(seq2links))
        seq2links.extend(links)
    l2lists = []
    for end in ends:
        l2lists.append(seq2links[:end])
    for link1 in linkList:
        i1 = link1.info[0].pos
        i2 = link1.info[1].pos
        for link2 in l2lists[i2]:
            if link2.info[0].pos <= i1:
                continue
            link1.crosslinks.append(link2)
            link2.crosslinks.append(link1)
            link1.penalty += link2.val
            link2.penalty += link1.val

    replyobj.status("%sPruning crosslinks %s\n" % (statusPrefix, tag),
                    blankAfter=0)
    while linkList:
        pen = pos = None
        for i, x in enumerate(linkList):
            if pen is None or x.penalty > pen:
                pos = i
                pen = x.penalty
        if pen <= 0.0001:
            break
        link = linkList.pop(pos)
        links1[link.info[0].pos].remove(link)
        links2[link.info[1].pos].remove(link)
        for clink in link.crosslinks:
            clink.penalty -= link.val
    for link in linkList:
        delattr(link, "crosslinks")
        delattr(link, "penalty")

    p1 = pairings[seq1]
    for i, l in enumerate(links1):
        p1[i].extend(l)
        allLinks.extend(l)
    p2 = pairings[seq2]
    for i, l in enumerate(links2):
        p2[i].extend(l)
def message(text, show_reply_log=False):

    from chimera.replyobj import message, status
    message(text + '\n')
    status(text, blankAfter=0)

    if show_reply_log:
        from Accelerators.standard_accelerators import show_reply_log as srl
        srl()
	def Execute(self, options):
		#print self, "Executing DelPhi..."
		self.options = options
		self.executor = DelPhiExecutor.DelPhiExecutor(self.options)
		self.process = self.executor()		
		self.checkHandler = chimera.triggers.addHandler(
						"check for changes",
						self.CheckProcess, None)
		replyobj.status("Running DelPhi in background")
def print_path_length():

  from chimera import selection
  bonds = selection.currentBonds()

  msg = '%d bonds with total length %g\n' % (len(bonds), path_length(bonds))
  from chimera import replyobj
  replyobj.status(msg)          # Show on status line
  replyobj.message(msg)         # Record in reply log
Exemple #48
0
def print_path_length():

    from chimera import selection
    bonds = selection.currentBonds()

    msg = '%d bonds with total length %g\n' % (len(bonds), path_length(bonds))
    from chimera import replyobj
    replyobj.status(msg)  # Show on status line
    replyobj.message(msg)  # Record in reply log
Exemple #49
0
def displayDialog(wait=False):
    if dialogs.find(BugReportGUI.name):
        replyobj.status("Bug report already in progress!",
                        color="red",
                        blankAfter=15)
        return None
    else:
        br_gui = dialogs.display(BugReportGUI.name, wait)
        return br_gui
def message(text, show_reply_log = False):

    from chimera.replyobj import message, status
    message(text + '\n')
    status(text, blankAfter = 0)

    if show_reply_log:
        from Accelerators.standard_accelerators import show_reply_log as srl
        srl()
	def status(self, msg, blankAfter=None, echoToMain=False, log=False,
			followWith="", followTime=20, color='black'):
		"""Display a status message

		   'blankAfter' controls how long (in seconds) before the
		   status area is automatically cleared.  Use zero to disable
		   auto-clearing this message.  'None' uses the user preference.

		   'echoToMain' and 'log' control sending an identical message
		   to the main window status line and the reply log,
		   respectively.

		   'followWith' is a message to follow the first one with.
		   'followTime' is how long until the followup message is
		   cleared (ala blankAfter).

		   Show the text in 'color' color.
		"""
		from chimera import replyobj
		if not self.provideStatus:
			raise ValueError("no status support in dialog")
		if self._statusBlankHandle:
			self.statusLine.after_cancel(self._statusBlankHandle)
			self._statusBlankHandle = None

		if echoToMain:
			replyobj.status(msg, blankAfter=blankAfter, color=color)
		if log:
			replyobj.info(msg)
			if followWith:
				if not msg.endswith("\n"):
					msg += "\n"
				msg += "[above message copied to Reply Log]"
		self.statusLine.configure(text=msg.strip(), fg=color)
		self.statusLine.update_idletasks()

		blankTime = blankAfter
		if blankAfter is None:
			import preferences
			from replyobj import REPLY_PREFERENCES, STATUS_CLEARING
			blankTime = preferences.get(REPLY_PREFERENCES,
							STATUS_CLEARING)
		if blankTime != 0:
			if followWith:
				nextMsg = followWith
				nextTime = followTime
			elif log:
				nextMsg = "Previous message also written" \
						" to reply log"
				nextTime = 20
			else:
				nextMsg = ""
				nextTime = 0
			self._statusBlankHandle = self.statusLine.after(
				1000 * blankTime, lambda:
				self.status(nextMsg, blankAfter=nextTime))
Exemple #52
0
def _postAddCharge(mols, runSaveMol2Dialog=False, doneCB=None):
	if runSaveMol2Dialog:
		from WriteMol2.gui import WriteMol2Dialog
		wmDlg = chimera.dialogs.display(WriteMol2Dialog.name)
		wmDlg.saveRelativeVar.set(True)
		wmDlg.rigidVar.set(True)
		wmDlg.multiSaveMenu.invoke(wmDlg.labelMap["combined"])
	replyobj.status("Dock prep finished")
	if doneCB:
		doneCB()
def _postAddCharge(mols, runSaveMol2Dialog=False, doneCB=None):
    if runSaveMol2Dialog:
        from WriteMol2.gui import WriteMol2Dialog
        wmDlg = chimera.dialogs.display(WriteMol2Dialog.name)
        wmDlg.saveRelativeVar.set(True)
        wmDlg.rigidVar.set(True)
        wmDlg.multiSaveMenu.invoke(wmDlg.labelMap["combined"])
    replyobj.status("Dock prep finished")
    if doneCB:
        doneCB()
def showAlignment(seqs, title):
	from MultAlignViewer.MAViewer import MAViewer
	replyobj.status("Showing alignment\n")
	mav = MAViewer(seqs, autoAssociate=False, title=title)
	mav.associate(None)
	mav.autoAssociate = True
	if len(seqs) < 3:
		mav.hideHeaders(mav.headers(shownOnly=True))
	mav.showHeaders([h for h in mav.headers() if h.name == "RMSD"])
	return mav
def move_atoms_to_maxima():

    from chimera.selection import currentAtoms
    atoms = currentAtoms()
    if len(atoms) == 0:
        from chimera.replyobj import status
        status('No atoms selected.')
        return
        
    for a in atoms:
        move_atom_to_maximum(a)
Exemple #56
0
	def Apply(self):
		path = self.getPaths()[0]
		surf = self.surfList.getvalue()
		if not surf:
			replyobj.error("No surface chosen to save.\n")
			return
		from WriteDMS import writeDMS
		replyobj.status("Writing DMS surface to %s\n" % path)
		writeDMS(surf, path, writeNormals=self.saveNormalsVar.get(),
			displayedOnly=self.displayedOnlyVar.get())
		replyobj.status("Wrote DMS surface to %s\n" % path)
	def CheckProcess(self, triggerName, data, data2):
		if not self.process.isRunning():
			chimera.triggers.deleteHandler("check for changes",
						self.checkHandler)
			self.checkHandler = None
			if self.executor.success():
				#print self, "Done executing DelPhi."
				self.OutputGUI()
				self.gui.savePrefs()
				replyobj.status("DelPhi finished")
			else:
				replyobj.status("DelPhi failed")
def zone_volume(outside = False):

  from volumedialog import active_volume
  v = active_volume()
  if v is None:
    from chimera.replyobj import status
    status('No volume shown in volume dialog')
    return

  mv = v.copy_zone(outside)
  if mv is None:
    from chimera.replyobj import status
    status('No zone for volume %s' % v.name)
Exemple #59
0
def findPruneCrosslinks(allLinks, pairings, seq1, seq2,
			linkList, links1, links2, tag="", statusPrefix=""):
	replyobj.status("%sFinding crosslinks %s\n" % (statusPrefix, tag),
							blankAfter=0)

	# find crossings
	ends = []
	seq2links = []
	for links in links2:
		ends.append(len(seq2links))
		seq2links.extend(links)
	l2lists = []
	for end in ends:
		l2lists.append(seq2links[:end])
	for link1 in linkList:
		i1 = link1.info[0].pos
		i2 = link1.info[1].pos
		for link2 in l2lists[i2]:
			if link2.info[0].pos <= i1:
				continue
			link1.crosslinks.append(link2)
			link2.crosslinks.append(link1)
			link1.penalty += link2.val
			link2.penalty += link1.val

	replyobj.status("%sPruning crosslinks %s\n" % (statusPrefix, tag),
							blankAfter=0)
	while linkList:
		pen = pos = None
		for i, x in enumerate(linkList):
			if pen is None or x.penalty > pen:
				pos = i
				pen = x.penalty
		if pen <= 0.0001:
			break
		link = linkList.pop(pos)
		links1[link.info[0].pos].remove(link)
		links2[link.info[1].pos].remove(link)
		for clink in link.crosslinks:
			clink.penalty -= link.val
	for link in linkList:
		delattr(link, "crosslinks")
		delattr(link, "penalty")

	p1 = pairings[seq1]
	for i, l in enumerate(links1):
		p1[i].extend(l)
		allLinks.extend(l)
	p2 = pairings[seq2]
	for i, l in enumerate(links2):
		p2[i].extend(l)