Ejemplo n.º 1
0
 def close_current_models(self):
     self.selected_neurons = OrderedDict([])
     self.colors = []
     current_models = set(openModels.list())
     models_to_close = current_models - self.init_models
     openModels.close(models_to_close)
     update.checkForChanges()  # to avoid memory leaks (see: http://www.cgl.ucsf.edu/chimera/docs/ProgrammersGuide/faq.html)
Ejemplo n.º 2
0
def make_molecule_map(atoms, resolution, step, pad, cutoff_range, sigma_factor,
                      display_threshold, model_id, replace, show_dialog):

    atoms = tuple(atoms)

    grid, molecules = molecule_grid_data(atoms, resolution, step, pad,
                                         cutoff_range, sigma_factor)

    from chimera import openModels as om
    if replace:
        from VolumeViewer import volume_list
        vlist = [
            v for v in volume_list()
            if getattr(v, 'molmap_atoms', None) == atoms
        ]
        om.close(vlist)

    from VolumeViewer import volume_from_grid_data
    v = volume_from_grid_data(grid, open_model=False, show_dialog=show_dialog)
    v.initialize_thresholds(mfrac=(display_threshold, 1), replace=True)
    v.show()

    v.molmap_atoms = tuple(atoms)  # Remember atoms used to calculate volume
    v.molmap_parameters = (resolution, step, pad, cutoff_range, sigma_factor)

    if len(molecules) == 1 and model_id is None:
        om.add([v], sameAs=tuple(molecules)[0])
    else:
        if model_id is None:
            model_id = (om.Default, om.Default)
        om.add([v], baseId=model_id[0], subid=model_id[1])
        v.openState.xform = atoms[0].molecule.openState.xform

    return v
Ejemplo n.º 3
0
	def removeAniso(self, targets):
		if isinstance(targets, dict):
			molMap = targets
		else:
			molMap = self._makeMolMap(targets)
		someShowing = bool(self._surfMap)
		for m, atoms in molMap.items():
			if m not in self._surfMap:
				continue
			surfMap = self._surfMap[m]
			for a in atoms:
				try:
					pieceInfo = surfMap[a]
				except KeyError:
					continue
				if not a.__destroyed__:
					a.labelOffset = None
				for key, pieces in pieceInfo.items():
					if key == "anisoParams" or not pieces:
						continue
					for piece in pieces:
						piece.model.removePiece(piece)
				del surfMap[a]
				del self._atomMolLookup[a]
			if len(surfMap) == 1:
				openModels.close([surfMap.pop("model")])
				del self._surfMap[m]
		if someShowing and not self._surfMap:
			triggers.deleteHandler('Atom', self._handlerID)
Ejemplo n.º 4
0
def make_molecule_map(atoms, resolution, step, pad, cutoff_range,
                      sigma_factor, display_threshold, model_id, replace,
		      show_dialog):

    atoms = tuple(atoms)

    grid, molecules = molecule_grid_data(atoms, resolution, step, pad,
                                         cutoff_range, sigma_factor)

    from chimera import openModels as om
    if replace:
        from VolumeViewer import volume_list
        vlist = [v for v in volume_list()
                 if getattr(v, 'molmap_atoms', None) == atoms]
        om.close(vlist)

    from VolumeViewer import volume_from_grid_data
    v = volume_from_grid_data(grid, open_model = False,
                              show_dialog = show_dialog)
    v.initialize_thresholds(mfrac = (display_threshold, 1), replace = True)
    v.show()

    v.molmap_atoms = tuple(atoms)   # Remember atoms used to calculate volume
    v.molmap_parameters = (resolution, step, pad, cutoff_range, sigma_factor)

    if len(molecules) == 1 and model_id is None:
        om.add([v], sameAs = tuple(molecules)[0])
    else:
        if model_id is None:
            model_id = (om.Default, om.Default)
        om.add([v], baseId = model_id[0], subid = model_id[1])
        v.openState.xform = atoms[0].molecule.openState.xform

    return v
def split_molecules(cmdname, args):

    fields = args.split()

    from chimera import openModels, Molecule
    if len(fields) >= 1:
        from chimera import specifier
        sel = specifier.evalSpec(fields[0])
        mlist = sel.molecules()
    else:
        mlist = openModels.list(modelTypes=[Molecule])

    if len(mlist) == 0:
        from Midas.midas_text import error
        error('%s: No molecules to split.' % cmdname)
        return

    slist = []
    for m in mlist:
        clist = split_molecule(m)
        if clist:
            openModels.add(clist, baseId=m.id, noprefs=True)
            for c in clist:
                c.openState.xform = m.openState.xform
            slist.append(m)
            from chimera import makeLongBondsDashed, makePseudoBondsToMetals
            makePseudoBondsToMetals(clist)
            makeLongBondsDashed(clist)

    openModels.close(slist)
Ejemplo n.º 6
0
def remove_sphere_key():

    from chimera import openModels as om
    from _surface import SurfaceModel
    om.close([
        m for m in om.list(modelTypes=[SurfaceModel])
        if m.name == 'Direction colors'
    ])
Ejemplo n.º 7
0
    def close(self):

        if self.molecule:
            from chimera import openModels
            openModels.close([self.molecule])

        if self.curve_model:
            from chimera import openModels
            openModels.close([self.curve_model])
            self.curve_model = None
Ejemplo n.º 8
0
def remove_extra_copies(m, nkeep):

  clist = []
  while True:
    name = m.name + (' #%d' % (len(clist)+nkeep+1))
    c = find_model_by_name(name)
    if c is None:
      break
    clist.append(c)
  from chimera import openModels
  openModels.close(clist)
def remove_extra_copies(m, nkeep):

    clist = []
    while True:
        name = m.name + (' #%d' % (len(clist) + nkeep + 1))
        c = find_model_by_name(name)
        if c is None:
            break
        clist.append(c)
    from chimera import openModels
    openModels.close(clist)
    def show_outline_cb(self):

        m = self.menu_molecule()
        if m == None:
            return

        name = self.outline_model_name(m)
        om = find_model_by_name(name)  # Close outline if shown
        if om:
            from chimera import openModels
            openModels.close([om])
        else:
            self.show_outline_model(m)
Ejemplo n.º 11
0
  def show_outline_cb(self):

    m = self.menu_molecule()
    if m == None:
      return

    name = self.outline_model_name(m)
    om = find_model_by_name(name)       # Close outline if shown
    if om:
      from chimera import openModels
      openModels.close([om])
    else:
      self.show_outline_model(m)
Ejemplo n.º 12
0
	def destroy(self):
		if self.cavities:
			cav1 = self.cavities[0]
			atoms = (cav1.mouthInfo["atoms"].atoms()
				or cav1.pocketInfo["atoms"].atoms())
			if atoms:
				# close surface too...
				from chimera import openModels
				mol = atoms[0].molecule
				openModels.close(openModels.list(
						id=mol.id, subid=mol.subid))
		for chk in [self.doSelect, self.doColor, self.doSurface,
						self.doZoom, self.excludeMouth]:
			chk.destroy()
		chimera.extension.manager.deregisterInstance(self)
		ModelessDialog.destroy(self)
Ejemplo n.º 13
0
def generate_images(cubs, pdbs):
    if 'CHIMERA' not in os.environ:
        sys.exit("To render movies, you must run the script with "
                 "pychimera: pychimera wfnmovie.py [...]")
    from chimera import runCommand as rc, openModels
    print('Generating .png images for {} cub/pdb files'.format(len(cubs)))
    for i, (cub, pdb) in tqdm(enumerate(zip(cubs, pdbs))):
        cubmodel = openModels.open(cub)[0]
        pdbmodel = openModels.open(pdb)[0]
        rc('vol #0 level 0.70')
        rc('scolor #0 gradient #0 cmap rainbow')
        rc('transp 50 #0')
        rc('turn y 180')
        rc('turn x -60')
        rc('focus')
        rc('copy file {}.png width 1280 height 720'.format(cub.split('.')[0]))
        openModels.close([cubmodel, pdbmodel])
Ejemplo n.º 14
0
def show_crystal_contacts(
        molecule,
        dist,
        make_copies=False,
        angle_tolerance=pi / 1800,  # 0.1 degrees
        shift_tolerance=0.1,  # Angstroms
        replace=False):

    if not hasattr(molecule, 'pdbHeaders'):
        return None

    # Find all unique pairs of contacting asymmetric units.
    clist = report_crystal_contacts(molecule, dist, angle_tolerance,
                                    shift_tolerance)

    crystal = Crystal(molecule.pdbHeaders)

    # Incorrect matrices in PDB header may not be orthogonal.  Check.
    check_orthogonality(crystal.ncs_matrices, 'NCS', tolerance=1e-3)
    check_orthogonality(crystal.smtry_matrices, 'SMTRY', tolerance=1e-3)

    # Get list of clashing asymmetric units.
    asu_list = contacting_asymmetric_units(clist,
                                           crystal,
                                           include_000_unit_cell=True)

    # Place markers representing each asym unit.
    marker_set = contact_marker_model(molecule, crystal, clist, asu_list)
    cmodels = [marker_set.marker_model()]

    if make_copies:
        # Make molecule copies.
        cm = make_asu_copies(molecule, contacting_asu(clist), crystal)
        cmodels.extend(cm)

    # Zoom to show all asym units.
    zoom_to_fit(padding=0.05)

    # Remember contact models so they can be replaced if recalculated.
    if replace and hasattr(molecule, 'crystal_contact_models'):
        from chimera import openModels
        openModels.close(molecule.crystal_contact_models)
    molecule.crystal_contact_models = cmodels

    return cmodels
Ejemplo n.º 15
0
def create_volume_plane_surface(volume, height, interpolate = 'cubic',
                                mesh = 'isotropic', colormap = 'rainbow',
                                smoothing_factor = 0.3,
                                smoothing_iterations = 0,
                                color = (.7, .7, .7, 1),
                                replace = True):

    m = volume.matrix()
    axes = [a for a in range(3) if m.shape[2-a] == 1]
    if len(axes) != 1:
        from chimera.replyobj import warning
        warning('Volume %s has more than one plane shown (%d,%d,%d)' %
                ((volume.name,) + tuple(reversed(m.shape))))
        return
    axis = axes[0]
    m = m.squeeze()     # Convert 3d array to 2d

    tf = volume.matrix_indices_to_xyz_transform()
    perm = {0: ((0,0,1,0),(1,0,0,0),(0,1,0,0)),     # 2d matrix xyh -> 3d yzx
            1: ((1,0,0,0),(0,0,1,0),(0,1,0,0)),     # 2d matrix xyh -> 3d xzy
            2: ((1,0,0,0),(0,1,0,0),(0,0,1,0))}[axis]
    from Matrix import multiply_matrices
    tf = multiply_matrices(tf, perm)
    
    s = create_surface(m, height, tf, color, interpolate, mesh,
                       smoothing_factor, smoothing_iterations)
    s.name = volume.name + ' height'

    if colormap == 'rainbow':
        invert = not height is None and height < 0
        tf = volume.data.ijk_to_xyz_transform
        normal = [tf[i][axis] for i in range(3)]
        colormap_surface(s, normal, rainbow_colormap(invert))

    from chimera import openModels
    if replace:
        openModels.close([m for m in openModels.list()
                          if getattr(m, 'topography_volume', None) == volume])
    openModels.add([s])
    s.openState.xform = volume.model_transform()
    s.topography_volume = volume

    return s
Ejemplo n.º 16
0
def show_crystal_contacts(molecule, dist,
                          make_copies = False,
                          angle_tolerance = pi/1800,   # 0.1 degrees
                          shift_tolerance = 0.1,       # Angstroms
			  replace = False):

    if not hasattr(molecule, 'pdbHeaders'):
        return None

    # Find all unique pairs of contacting asymmetric units.
    clist = report_crystal_contacts(molecule, dist,
                                    angle_tolerance, shift_tolerance)

    crystal = Crystal(molecule.pdbHeaders)

    # Incorrect matrices in PDB header may not be orthogonal.  Check.
    check_orthogonality(crystal.ncs_matrices, 'NCS', tolerance = 1e-3)
    check_orthogonality(crystal.smtry_matrices, 'SMTRY', tolerance = 1e-3)

    # Get list of clashing asymmetric units.
    asu_list = contacting_asymmetric_units(clist, crystal,
                                           include_000_unit_cell = True)

    # Place markers representing each asym unit.
    marker_set = contact_marker_model(molecule, crystal, clist, asu_list)
    cmodels = [marker_set.marker_model()]

    if make_copies:
        # Make molecule copies.
	cm = make_asu_copies(molecule, contacting_asu(clist), crystal)
        cmodels.extend(cm)

    # Zoom to show all asym units.
    zoom_to_fit(padding = 0.05)

    # Remember contact models so they can be replaced if recalculated.
    if replace and hasattr(molecule, 'crystal_contact_models'):
        from chimera import openModels
        openModels.close(molecule.crystal_contact_models)
    molecule.crystal_contact_models = cmodels

    return cmodels
Ejemplo n.º 17
0
    def close_model(self):

        v = self.volume
        if v:
            from chimera import openModels
            openModels.close([v])
Ejemplo n.º 18
0
	if refMol == None:
		refMol = mols[:1]
	if len(refMol) == 0:
		raise MidasError("No reference molecule specified")
	elif len(refMol) > 1:
		raise MidasError("Multiple reference molecules specified")
	refMol = refMol[0]
	if modelId is not None and type(modelId) != int:
		try:
			modelId = int(modelId[1:])
		except:
			raise MidasError("modelId value must be integer")
	from chimera import suppressNewMoleculeProcessing, \
					restoreNewMoleculeProcessing
	suppressNewMoleculeProcessing()
	try:
		m = combine(mols, refMol, newChainIDs=newChainIDs, log=log)
	except CombineError, v:
		restoreNewMoleculeProcessing()
		raise MidasError(v)
	from chimera import openModels
	m.name = name
	kw = {'shareXform': False}
	if modelId != None:
		kw['baseId'] = modelId
	openModels.add([m], **kw)
	m.openState.xform = refMol.openState.xform
	restoreNewMoleculeProcessing()
	if close:
		openModels.close(mols)
    if refMol == None:
        refMol = mols[:1]
    if len(refMol) == 0:
        raise MidasError("No reference molecule specified")
    elif len(refMol) > 1:
        raise MidasError("Multiple reference molecules specified")
    refMol = refMol[0]
    if modelId is not None and type(modelId) != int:
        try:
            modelId = int(modelId[1:])
        except:
            raise MidasError("modelId value must be integer")
    from chimera import suppressNewMoleculeProcessing, \
        restoreNewMoleculeProcessing
    suppressNewMoleculeProcessing()
    try:
        m = combine(mols, refMol, newChainIDs=newChainIDs, log=log)
    except CombineError, v:
        restoreNewMoleculeProcessing()
        raise MidasError(v)
    from chimera import openModels
    m.name = name
    kw = {'shareXform': False}
    if modelId != None:
        kw['baseId'] = modelId
    openModels.add([m], **kw)
    m.openState.xform = refMol.openState.xform
    restoreNewMoleculeProcessing()
    if close:
        openModels.close(mols)
Ejemplo n.º 20
0
def make_orthoslice_images(
    rlist,  # Segmentation regions.
    volume,  # Volume model.
    trace_spacing=None,  # Physical units.
    trace_tip_length=None,  # Physical units.
    unbend_size=1.5,  # Factor multipied by region diameter.
    unbend_yaxis=(0, 0, 1),
    unbend_grid_spacing=1,  # Factor multiplied by minimum voxel size.
    slice_spacing=None,  # 3-tuple, physical units.
    xy_trim=0.3,  # Factor multipled by unbent grid width/height.
    panel_aspect=0.5,  # Minimum aspect ratio for tiled layout.
    image_spacing=20,  # Pixels between 3 sets of slices.
    show_image=True,
    task=None,
):

    from math import ceil
    from Measure.spine import trace_spine, measure_diameter
    from VolumeFilter.unbend import atom_path, unbend_volume
    from VolumeFilter.tile import tile_planes
    from chimera import openModels

    ubgs = unbend_grid_spacing * min(volume.data.step)

    axes = ('x', 'y', 'z')
    pstep = (10, 10, 10) if slice_spacing is None else [
        int(ceil(s / ubgs)) for s in slice_spacing
    ]
    orders = ('ulh', 'urv', 'ulhr')

    for ri, r in enumerate(rlist):

        if task:
            task.updateStatus('region %d (%d of %d)' %
                              (r.rid, ri + 1, len(rlist)))

        # Trace center-line.
        mset = trace_spine(r, trace_spacing, trace_tip_length)

        # Unbend volume.
        p = atom_path([m.atom for m in mset.markers()])
        dmax, dmin = measure_diameter(r, mset)
        if dmax is None:
            print 'Region %d has no diameter' % r.rid
            mset.close()
            continue
        xsize = ysize = unbend_size * dmax
        ubv = unbend_volume(volume,
                            p,
                            unbend_yaxis,
                            xsize,
                            ysize,
                            ubgs,
                            open=False)
        #        ubv.set_representation('solid')
        #        ubv.set_parameters(show_outline_box = True)

        # Create tiled cross-section volumes along 3 axes.
        etrim = (xy_trim * ubv.data.size[0], xy_trim * ubv.data.size[1], 0)
        etrim = [int(ceil(t)) for t in etrim]
        rowcol = rows_and_columns(ubv.data.size, pstep, etrim, panel_aspect)
        tparams = zip(axes, pstep, etrim, rowcol, orders)
        tv = [
            tile_planes(ubv, axis, step, trim, rows, cols, order, open=False)
            for axis, step, trim, (rows, cols), order in tparams
        ]
        if [v for v in tv if v is None]:
            print 'Region %d has no sections for some axes' % r.rid
            mset.close()
            openModels.close([v for v in tv if v] + [ubv])
            continue

        # Make images for each set of slices and combine them side-by-side.
        images = (volume_image(tv[0]), volume_image(tv[1], xflip=True),
                  volume_image(tv[2]))
        image = montage_image(images, pad=image_spacing)
        image.title = 'Region %d' % r.rid
        if show_image:
            from Segger.imageviewer import showImage
            showImage(image, title=image.title, fit_to_window=True)

        # Set image region attribute
        r.set_attribute('slices', image)

        # Close center line.
        mset.close()
Ejemplo n.º 21
0
  def close_model(self):

    v = self.volume
    if v:
      from chimera import openModels
      openModels.close([v])
Ejemplo n.º 22
0
    def onPick(self, event):
        if self.selection_mode == 'Cell': # Select unique cells
            if event.mouseevent.button == 3 or self.ctrl_pressed:
                self.keep_selection = True
            else:
                self.keep_selection = False

            if not self.keep_selection:
                self.close_current_models()
            else:
                if len(self.selected_neurons) == 1:
                    if self.i is not None and self.j is not None:
                        self.add_model(name='%d,%d' % (self.i, self.j))
            if event.mouseevent.button == 1 or event.mouseevent.button == 3:
                x, y = event.mouseevent.xdata, event.mouseevent.ydata
                self.j, self.i = int(x), int(y)
                if (self.i, self.j) not in self.selected_neurons.keys():
                    frame_id = self.rep_map[self.i, self.j] + 1
                    if not numpy.isnan(frame_id):
                        frame_id = int(frame_id)
                        if self.keep_selection:
                            self.colors.append('g')
                        else:
                            self.colors.append('r')
                        self.display_frame(frame_id)
                        if self.keep_selection:
                            self.add_model(name='%d,%d' % (self.i, self.j))
                        self.selected_neurons[(self.i, self.j)] = openModels.list()[-1]
                        self.update_model_color()
                else:
                    model_to_del = self.selected_neurons[(self.i, self.j)]
                    if model_to_del not in self.init_models:
                        openModels.close([model_to_del])
                        del self.selected_neurons[(self.i, self.j)]
                self.get_basin(None) # to display the basin around the selected cell
                #self._displayData() # commented as it's already done by self.get_basin(None) above
        elif self.selection_mode == 'Cluster' and event.mouseevent.button == 1:
            self.close_current_models()
            if self.highlighted_cluster is not None:
                self.highlighted_cluster[numpy.isnan(self.highlighted_cluster)] = False
                self.highlighted_cluster = numpy.bool_(self.highlighted_cluster)
                frame_ids = self.rep_map[self.highlighted_cluster] + 1
                frame_ids = frame_ids[~numpy.isnan(frame_ids)]
                n = len(frame_ids)
                if self.clustermode[1] == "Frames":
                    if n > 10:
                        frame_ids = frame_ids[::n/10] # take only ten representatives
                    for frame_id in frame_ids:
                        frame_id = int(frame_id)
                        self.display_frame(frame_id)
                        self.add_model(name='cluster')
                elif self.clustermode[1] == 'Density':
                    if n > 100:
                        frame_ids = frame_ids[::n/100] # take only 100 representatives
                    trajMol = self.movie.model._mol

                    if chimera.selection.currentEmpty():
                        #something to select all atoms
                        runCommand("select #%d" % self.movie_id)
                    atoms = [a for a in chimera.selection.currentAtoms() if a.molecule == trajMol]    
                    name="ClusterDensityMap"
                    self.computeVolume(atoms, frame_ids=frame_ids,volumeName=name, spacing=self.clustermode[0])
                    model_id=openModels.listIds()[-1][0]
                    #Midas.color('aquamarine,s', '#%d' %model_id)
                    runCommand("volume #%d level 50. color aquamarine style surface" %model_id)
Ejemplo n.º 23
0
class CombineDialog(ModelessDialog):
	title = "Copy/Combine Molecular Models"
	help = "UsersGuide/modelpanel.html#combine"

	def __init__(self, models=None):
		self.initModels = models
		ModelessDialog.__init__(self)

	def fillInUI(self, parent):
		from chimera.widgets import MoleculeScrolledListBox
		self.molListBox = MoleculeScrolledListBox(parent,
			listbox_selectmode='extended', labelpos='w',
			label_text="Molecules to combine/copy:")
		if self.initModels:
			self.molListBox.setvalue(self.initModels)
		self.molListBox.grid(row=0, column=0, columnspan=2,
							sticky="nsew")
		parent.rowconfigure(0, weight=1)
		parent.columnconfigure(1, weight=1)
		from chimera.tkoptions import StringOption, IntOption
		self.molNameEntry = StringOption(parent, 1, "New model's"
						" name", "combination", None)

		curIDs = set([i1 for i1, i2 in openModels.listIds()])
		mid = 0
		while mid in curIDs:
			mid += 1
		self.modelID = IntOption(parent, 2, "New model's ID", mid, None)

		from chimera.widgets import MoleculeOptionMenu
		self.refMolMenu = MoleculeOptionMenu(parent, labelpos='w',
			label_text="Coordinate system of:",
			initialitem=self.initModels[0])
		self.refMolMenu.grid(row=3, column=0, columnspan=2, sticky='w')

		import Pmw
		chb = self.chainHandlingButtons = Pmw.RadioSelect(parent,
			buttontype="radiobutton", labelpos='w',
			label_text="If original molecules have duplicate\n"
			"single-letter chain IDs, then:", orient="vertical")
		self.buttonTexts = ["rename them uniquely",
				"retain them (residues may be renumbered)"]
		for bt in self.buttonTexts:
			chb.add(bt)
		chb.setvalue(self.buttonTexts[0])
		chb.grid(row=4, column=0, columnspan=2)

		import Tkinter
		self.closeModelsVar = Tkinter.IntVar(parent)
		self.closeModelsVar.set(False)
		Tkinter.Checkbutton(parent, text="Close source models",
					variable=self.closeModelsVar).grid(
					row=5, column=0, columnspan=2)
			

	def Apply(self):
		mols = self.molListBox.getvalue()
		from chimera import UserError
		if not mols:
			self.enter()
			raise UserError("Must specify at least one molecular"
				" model to combine/copy")
		from chimera import suppressNewMoleculeProcessing, \
						restoreNewMoleculeProcessing
		suppressNewMoleculeProcessing()
		newChainIDs = (self.chainHandlingButtons.getvalue()
						== self.buttonTexts[0])
		refMol = self.refMolMenu.getvalue()
		from Combine import combine, CombineError
		try:
			m = combine(mols, refMol,
					newChainIDs=newChainIDs, log=True)
		except CombineError, v:
			restoreNewMoleculeProcessing()
			self.enter()
			raise UserError(v)
		m.name = self.molNameEntry.get()
		openModels.add([m], baseId=self.modelID.get(), shareXform=False)
		m.openState.xform = refMol.openState.xform
		restoreNewMoleculeProcessing()

		if self.closeModelsVar.get():
			openModels.close(mols)
Ejemplo n.º 24
0
    def unshow_curve(self):

        if self.curve_model:
            from chimera import openModels
            openModels.close([self.curve_model])
            self.curve_model = None