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
예제 #2
0
    def _importExtension(self, path, pkgName, module):
        """Import tool at given path
		
		Import process should cause tool to register
		itself via registerExtension"""

        sys.path.insert(0, os.path.join(path, pkgName))
        try:
            try:
                # When "module" is imported, it should register
                # itself.  Then we delete the module from
                # sys.modules so that the same name may be
                # used when importing another tool.
                try:
                    __import__(module)
                except ImportError:
                    pass
                try:
                    del sys.modules[module]
                except KeyError:
                    pass
            finally:
                del sys.path[0]
        except:
            # need to give some indication of what module the
            # error is occuring in, so prepend info to error
            from chimera import replyobj
            import traceback
            replyobj.pushMode(replyobj.ERROR)
            replyobj.message("Error while importing %s from %s:\n" %
                             (pkgName, path))
            s = apply(traceback.format_exception, sys.exc_info())
            replyobj.message(''.join(s))
            replyobj.popMode()
예제 #3
0
	def apply(self, vFunc = None, eFunc = None):
		sel = selection.ItemizedSelection()
		sels = []  # used as a stack when selections get composited
		funcGlobals = {
			"__doc__": None,
			"__name__": "CodeItemizedSelection",
			"__builtins__": __builtins__
		}
		if self.models is None:
			sm = chimera.openModels.list()
		else:
			sm = self.models
		funcLocals = {
			"models": sm,
			"molecules": filter(lambda m, M=Molecule:
							isinstance(m, M), sm),
			"sel": sel,
			"sels": sels,
			"selection": selection
		}

		try:
			exec self.codeObj in funcGlobals, funcLocals
		except:
			from chimera import replyobj
			replyobj.error(" CodeItemizedSelection failed\n")
			s = apply(traceback.format_exception,
					sys.exc_info())
			replyobj.message(string.join(s, ''))
		sel.apply(vFunc, eFunc)
예제 #4
0
	def _importExtension(self, path, pkgName, module):
		"""Import tool at given path
		
		Import process should cause tool to register
		itself via registerExtension"""

		sys.path.insert(0, os.path.join(path, pkgName))
		try:
			try:
				# When "module" is imported, it should register
				# itself.  Then we delete the module from
				# sys.modules so that the same name may be
				# used when importing another tool.
				try:
					__import__(module)
				except ImportError:
					pass
				try:
					del sys.modules[module]
				except KeyError:
					pass
			finally:
				del sys.path[0]
		except:
			# need to give some indication of what module the
			# error is occuring in, so prepend info to error
			from chimera import replyobj
			import traceback
			replyobj.pushMode(replyobj.ERROR)
			replyobj.message("Error while importing %s from %s:\n"
							% (pkgName, path))
			s = apply(traceback.format_exception,
					sys.exc_info())
			replyobj.message(''.join(s))
			replyobj.popMode()
    def apply(self, vFunc=None, eFunc=None):
        sel = selection.ItemizedSelection()
        sels = []  # used as a stack when selections get composited
        funcGlobals = {
            "__doc__": None,
            "__name__": "CodeItemizedSelection",
            "__builtins__": __builtins__
        }
        if self.models is None:
            sm = chimera.openModels.list()
        else:
            sm = self.models
        funcLocals = {
            "models": sm,
            "molecules": filter(lambda m, M=Molecule: isinstance(m, M), sm),
            "sel": sel,
            "sels": sels,
            "selection": selection
        }

        try:
            exec self.codeObj in funcGlobals, funcLocals
        except:
            from chimera import replyobj
            replyobj.error(" CodeItemizedSelection failed\n")
            s = apply(traceback.format_exception, sys.exc_info())
            replyobj.message(string.join(s, ''))
        sel.apply(vFunc, eFunc)
예제 #6
0
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
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)
예제 #8
0
 def showFileContent(self, filename):
   try:
     url = self.filemap[filename]
   except KeyError:
     from chimera import replyobj
     replyobj.message("SAXS profile: there is no file named \"%s\"" % filename)
   else:
     self.showURLContent("SAXS profile %s" % filename, url)
예제 #9
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
예제 #10
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
예제 #11
0
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()
예제 #12
0
 def showFileContent(self, filename):
     try:
         url = self.filemap[filename]
     except KeyError:
         from chimera import replyobj
         replyobj.message("SAXS profile: there is no file named \"%s\"" %
                          filename)
     else:
         self.showURLContent("SAXS profile %s" % filename, url)
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 _close(script):
    # Callback invoked when a script is changed due to
    # molecules being closed.  If there are still actions,
    # we don't need to do anything.  But if all relevant
    # models are closed, then we also remove this script.
    if script.actions:
        return
    for n, s in _motions.iteritems():
        if script is s:
            _remove(n)
            from chimera import replyobj
            replyobj.message("Morph \"%s\" removed\n" % n)
            break
예제 #15
0
def _close(script):
	# Callback invoked when a script is changed due to
	# molecules being closed.  If there are still actions,
	# we don't need to do anything.  But if all relevant
	# models are closed, then we also remove this script.
	if script.actions:
		return
	for n, s in _motions.iteritems():
		if script is s:
			_remove(n)
			from chimera import replyobj
			replyobj.message("Morph \"%s\" removed\n" % n)
			break
예제 #16
0
def show_volume_statistics(show_reply_log = True):
    
    from VolumeViewer import active_volume
    dr = active_volume()
    if dr == None:
        message('No volume data opened', show_reply_log)
        return

    m = dr.matrix()
    mean, sd, rms = mean_sd_rms(m)
    descrip = subregion_description(dr)
    message('%s%s: mean = %.5g, SD = %.5g, RMS = %.5g'
            % (dr.name, descrip, mean, sd, rms),
            show_reply_log)
def show_volume_statistics(show_reply_log=True):

    from VolumeViewer import active_volume
    dr = active_volume()
    if dr == None:
        message('No volume data opened', show_reply_log)
        return

    m = dr.matrix()
    mean, sd, rms = mean_sd_rms(m)
    descrip = subregion_description(dr)
    message(
        '%s%s: mean = %.5g, SD = %.5g, RMS = %.5g' %
        (dr.name, descrip, mean, sd, rms), show_reply_log)
예제 #18
0
    def map(self, e=None):
	# First check if the server can be accessed
	if self.checkConnection():
	    return
	else:
	    replyobj.pushMode(replyobj.ERROR)
	    replyobj.message(
			'There has been an error while trying to\n'
			'contact the server. Your registration cannot \n'
			'be processed at this time.\n\n'
	    		'If you use a proxy server to connect to the web,\n'
			'try configuring the proxy settings in the \n'
	    		'Web Access Preferences category, restarting \n'
	    		'Chimera, and trying again.\n')
	    replyobj.popMode()
	    self.Close()
예제 #19
0
def makeOslMappings(molOrder, srcMolMap):
	for xfileInfo in molOrder:
		oldOsls = srcMolMap[xfileInfo]
		filename, fileType, defaultType = xfileInfo
		prefixable = 1
		if fileType:
			prefixable = 0
		try:
			mols = chimera.openModels.open(filename, type=fileType,
			defaultType=defaultType, prefixableType=prefixable)
		except IOError:
			remapped = findFile(filename)
			if remapped is None:
				replyobj.message("Skipping restore of %s\n"
								% filename)
				continue
			mols = chimera.openModels.open(remapped, type=fileType,
						defaultType=defaultType,
						prefixableType=prefixable)

			
		while len(mols) < len(oldOsls):
			mols += chimera.openModels.open(filename, type=fileType,
						defaultType=defaultType,
						prefixableType=prefixable)
		for m in mols:
			for r in m.residues:
				r.ribbonColor = None
			for a in m.atoms:
				a.color = None
		curOsls = [m.oslIdent() for m in mols]
		oldOsls.sort(chimera.misc.oslModelCmp)
		curOsls.sort(chimera.misc.oslModelCmp)
		for i in range(len(oldOsls)):
			updateOSLmap(oldOsls[i], curOsls[i])

		# prepopulate osl lookup map
		for m in mols:
			i = curOsls.index(m.oslIdent())
			mapped = oldOsls[i]
			for r in m.residues:
				_oslItemMap[mapped + getOSL(r,
					start=selection.SelSubgraph)] = r
			for a in m.atoms:
				_oslItemMap[mapped + getOSL(a,
					start=selection.SelSubgraph)] = a
예제 #20
0
def print_model_path_lengths():

    from chimera import selection
    bonds = selection.currentBonds()

    mbonds = {}
    for b in bonds:
        m = b.molecule
        if m in mbonds:
            mbonds[m].append(b)
        else:
            mbonds[m] = [b]

    for m, bonds in mbonds.items():
        msg = ('%s: %d bonds with total length %g\n' %
               (m.name, len(bonds), path_length(bonds)))
        from chimera import replyobj
        replyobj.status(msg)  # Show on status line
        replyobj.message(msg)  # Record in reply log
예제 #21
0
def print_model_path_lengths():

  from chimera import selection
  bonds = selection.currentBonds()

  mbonds = {}
  for b in bonds:
    m = b.molecule
    if m in mbonds:
      mbonds[m].append(b)
    else:
      mbonds[m] = [b]

  for m, bonds in mbonds.items():
    msg = ('%s: %d bonds with total length %g\n'
           % (m.name, len(bonds), path_length(bonds)))
    from chimera import replyobj
    replyobj.status(msg)          # Show on status line
    replyobj.message(msg)         # Record in reply log
예제 #22
0
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)
예제 #23
0
    def apply(self, vFunc=None, eFunc=None):
        """Apply given functions to selected objects
		
		selection.apply(vFunc=lambda...) => None

		It is incumbant on the code to follow guarantees that
		the the vertex function is called before the edge
		function.

		Note: many types of exceptions can happen when the code
		is executed.
		"""
        funcGlobals = {
            "__doc__": None,
            "__name__": "CodeSelection",
            "__builtins__": __builtins__
        }
        funcLocals = {
            "models": chimera.openModels.list(),
            "vFunc": vFunc,
            "eFunc": eFunc,
            "funcs": {
                SelVertex: vFunc,
                SelEdge: eFunc
            }
        }
        # helper function, so code can call 'selApply(obj)' without
        # knowing what the selection type of the object is.
        funcLocals["selApply"] = lambda obj, funcs=funcLocals["funcs"]:\
         funcs[obj.oslLevel()](obj)
        try:
            exec self.codeObj in funcGlobals, funcLocals
        except:
            import string
            from chimera import replyobj
            replyobj.pushMode(replyobj.ERROR)
            replyobj.message(str(self.name()) + " Code Selection failed\n")
            s = apply(traceback.format_exception, sys.exc_info())
            replyobj.message(string.join(s, ''))
            replyobj.popMode()
예제 #24
0
	def apply(self, vFunc = None, eFunc = None):
		"""Apply given functions to selected objects
		
		selection.apply(vFunc=lambda...) => None

		It is incumbant on the code to follow guarantees that
		the the vertex function is called before the edge
		function.

		Note: many types of exceptions can happen when the code
		is executed.
		"""
		funcGlobals = {
			"__doc__": None,
			"__name__": "CodeSelection",
			"__builtins__": __builtins__
		}
		funcLocals = {
			"models": chimera.openModels.list(),
			"vFunc": vFunc, "eFunc" : eFunc,
			"funcs": {
				SelVertex: vFunc, SelEdge: eFunc
			}
		}
		# helper function, so code can call 'selApply(obj)' without
		# knowing what the selection type of the object is.
		funcLocals["selApply"] = lambda obj, funcs=funcLocals["funcs"]:\
			funcs[obj.oslLevel()](obj)
		try:
			exec self.codeObj in funcGlobals, funcLocals
		except:
			import string
			from chimera import replyobj
			replyobj.pushMode(replyobj.ERROR)
			replyobj.message(str(self.name()) +
						" Code Selection failed\n")
			s = apply(traceback.format_exception,
					sys.exc_info())
			replyobj.message(string.join(s, ''))
			replyobj.popMode()
예제 #25
0
	def makeTrajectory(self, minimize=False, steps=60):
		from chimera import replyobj
		#
		# It's an all-or-nothing deal.  If any step requires
		# minimization, all molecules must have hydrogens
		# because the interpolation routines requires a 1-1
		# atom mapping between the two conformations
		#
		if not minimize:
			molMap = {}
			for mol, options in self.actions:
				molMap[mol] = mol
		else:
			import AddH
			kw = {
				"delSolvent": False,
				"nogui": True,
				"addHFunc": AddH.simpleAddHydrogens,
			}
			import DockPrep
			from util import mapAtoms, copyMolecule
			refMol = None
			for mol, options in self.actions:
				if self.addhMap.has_key(mol):
					refMol = mol
			if refMol is None:
				refMol = self.actions[0][0]
				replyobj.message("Add hydrogens to %s\n"
							% refMol.oslIdent())
				m, aMap, rMap = copyMolecule(refMol)
				DockPrep.prep([m], **kw)
				self.addhMap[refMol] = m
			for mol, options in self.actions:
				if self.addhMap.has_key(mol):
					continue
				amap = mapAtoms(mol, refMol,
						ignoreUnmatched=True)
				for a, refa in amap.iteritems():
					a.idatmType = refa.idatmType
				replyobj.message("Add hydrogens to %s\n"
							% mol.oslIdent())
				m, aMap, rMap = copyMolecule(mol)
				DockPrep.prep([m], **kw)
				self.addhMap[mol] = m
			molMap = self.addhMap

		import copy
		mol, options = self.actions[0]
		initOptions = copy.copy(options)
		if self.motion is None:
			from Motion import MolecularMotion
			self.motion = MolecularMotion(molMap[mol],
							mol.openState.xform,
							minimize=minimize,
							steps=steps,
							**initOptions)
		else:
			self.motion.reset(minimize=minimize, steps=steps,
							**initOptions)
		prevMol = mol
		prevOptions = copy.copy(options)

		for i in range(1, len(self.actions)):
			msg = "Computing interpolation %d\n" % i
			replyobj.message(msg)
			replyobj.status(msg)
			mol, options = self.actions[i]
			prevOptions.update(options)
			try:
				self.motion.interpolate(molMap[mol],
							mol.openState.xform,
							**prevOptions)
			except ValueError, msg:
				from chimera import UserError
				raise UserError("cannot interpolate models: %s"
						% msg)
			prevMol = mol
예제 #26
0
def findHBonds(models, intermodel=True, intramodel=True, donors=None,
				acceptors=None, distSlop=0.0, angleSlop=0.0,
				interSubmodel=False, cacheDA=False):
	# to restrict to specific donor/acceptor atoms, 'donors' and/or
	# acceptors should be atom lists (or dictionaries with atom keys)
	# 
	# 'cacheDA' allows donors/acceptors in molecules to be cached if
	# it is anticipated that the same structures will be examined for
	# H-bonds repeatedly (e.g. a dynamics trajectory).

	if donors and not isinstance(donors, (dict, set)):
		limitedDonors = set(donors)
	else:
		limitedDonors = donors
	if acceptors and not isinstance(acceptors, (dict, set)):
		limitedAcceptors = set(acceptors)
	else:
		limitedAcceptors = acceptors
	global _Dcache, _Acache, _prevLimited
	if cacheDA:
		if limitedDonors:
			dIDs = [id(d) for d in limitedDonors]
			dIDs.sort()
		else:
			dIDs = None
		if limitedAcceptors:
			aIDs = [id(a) for a in limitedAcceptors]
			aIDs.sort()
		else:
			aIDs = None
		key = (dIDs, aIDs)
		if _prevLimited and _prevLimited != key:
			flushCache()
		_prevLimited = key
		from weakref import WeakKeyDictionary
		if _Dcache is None:
			_Dcache = WeakKeyDictionary()
			_Acache = WeakKeyDictionary()
	else:
		flushCache()
	global donorParams, acceptorParams
	global processedDonorParams, processedAcceptorParams
	global _computeCache
	global verbose
	global _problem
	_problem = None

	badConnectivities = 0

	# Used as necessary to cache expensive calculations (by other
	# functions also)
	_computeCache = {}

	processKey = (distSlop, angleSlop)
	if processKey not in processedAcceptorParams:
		# copy.deepcopy() refuses to copy functions (even as
		# references), so do this instead...
		aParams = []
		for p in acceptorParams:
			aParams.append(copy.copy(p))

		for i in range(len(aParams)):
			aParams[i][3] = _processArgTuple(aParams[i][3],
							distSlop, angleSlop)
		processedAcceptorParams[processKey] = aParams
	else:
		aParams = processedAcceptorParams[processKey]

	# compute some info for generic acceptors/donors
	genericAccInfo = {}
	# oxygens...
	genericOAccArgs = _processArgTuple([3.53, 90], distSlop,
							angleSlop)
	genericAccInfo['miscO'] = (accGeneric, genericOAccArgs)
	# dictionary based on bonded atom's geometry...
	genericAccInfo['O2-'] = {
		single: (accGeneric, genericOAccArgs),
		linear: (accGeneric, genericOAccArgs),
		planar: (accPhiPsi, _processArgTuple([3.53, 90, 130],
						distSlop, angleSlop)),
		tetrahedral: (accGeneric, genericOAccArgs)
	}
	genericAccInfo['O3-'] = genericAccInfo['O2-']
	genericAccInfo['O2'] = {
		single: (accGeneric, genericOAccArgs),
		linear: (accGeneric, genericOAccArgs),
		planar: (accPhiPsi, _processArgTuple([3.30, 110, 130],
						distSlop, angleSlop)),
		tetrahedral: (accThetaTau, _processArgTuple(
			[3.03, 100, -180, 145], distSlop, angleSlop))
	}
	# list based on number of known bonded atoms...
	genericAccInfo['O3'] = [
		(accGeneric, genericOAccArgs),
		(accThetaTau, _processArgTuple([3.17, 100, -161, 145],
						distSlop, angleSlop)),
		(accPhiPsi, _processArgTuple([3.42, 120, 135],
						distSlop, angleSlop))
	]
	# nitrogens...
	genericNAccArgs = _processArgTuple([3.42, 90], distSlop,
							angleSlop)
	genericAccInfo['miscN'] = (accGeneric, genericNAccArgs)
	genericAccInfo['N2'] = (accPhiPsi, _processArgTuple([3.42, 140, 135],
						distSlop, angleSlop))
	# tuple based on number of bonded heavy atoms...
	genericN3MultHeavyAccArgs = _processArgTuple([3.30, 153, -180, 145],
						distSlop, angleSlop)
	genericAccInfo['N3'] = (
		(accGeneric, genericNAccArgs),
		# only one example to draw from; weaken by .1A, 5 degrees
		(accThetaTau, _processArgTuple([3.13, 98, -180, 150],
						distSlop, angleSlop)),
		(accThetaTau, genericN3MultHeavyAccArgs),
		(accThetaTau, genericN3MultHeavyAccArgs)
	)
	# one example only; weaken by .1A, 5 degrees
	genericAccInfo['N1'] = (accThetaTau, _processArgTuple(
				[3.40, 136, -180, 145], distSlop, angleSlop))
	# sulfurs...
	# one example only; weaken by .1A, 5 degrees
	genericAccInfo['S2'] = (accPhiPsi, _processArgTuple([3.83, 85, 140],
						distSlop, angleSlop))
	genericAccInfo['Sar'] = genericAccInfo['S3-'] = (accGeneric,
			_processArgTuple([3.83, 85], distSlop, angleSlop))
	# now the donors...
	
	# planar nitrogens
	genDonNpl1HParams = (donThetaTau, _processArgTuple([2.23, 136,
		2.23, 141, 140, 2.46, 136, 140], distSlop, angleSlop))
	genDonNpl2HParams = (donUpsilonTau, _processArgTuple([3.30, 90, -153,
		135, -45, 3.30, 90, -146, 140, -37.5, 130, 3.40, 108, -166, 125,
		-35, 140], distSlop, angleSlop))
	genDonODists = [2.41, 2.28, 2.28, 3.27, 3.14, 3.14]
	genDonOParams = (donGeneric, _processArgTuple(
					genDonODists, distSlop, angleSlop))
	genDonNDists = [2.36, 2.48, 2.48, 3.30, 3.42, 3.42]
	genDonNParams = (donGeneric, _processArgTuple(
					genDonNDists, distSlop, angleSlop))
	genDonSDists = [2.42, 2.42, 2.42, 3.65, 3.65, 3.65]
	genDonSParams = (donGeneric, _processArgTuple(
					genDonSDists, distSlop, angleSlop))
	genericDonInfo = {
		'O': genDonOParams,
		'N': genDonNParams,
		'S': genDonSParams
	}

	accTrees = {}
	hbonds = []
	hasSulfur = {}
	for model in models:
		replyobj.status("Finding acceptors in model '%s'\n"
						% model.name, blankAfter=0)
		if cacheDA \
		and _Acache.has_key(model) \
		and _Acache[model].has_key((distSlop, angleSlop)):
			accAtoms = []
			accData = []
			for accAtom, data in _Acache[model][(distSlop,
							angleSlop)].items():
				if not accAtom.__destroyed__:
					accAtoms.append(accAtom)
					accData.append(data)
		else:
			accAtoms, accData = _findAcceptors(model, aParams,
					limitedAcceptors, genericAccInfo)
			if cacheDA:
				cache = WeakKeyDictionary()
				for i in range(len(accAtoms)):
					cache[accAtoms[i]] = accData[i]
				if not _Acache.has_key(model):
					_Acache[model] = {}
				_Acache[model][(distSlop, angleSlop)] = cache
		xyz = []
		hasSulfur[model] = False
		for accAtom in accAtoms:
			c = accAtom.xformCoord()
			xyz.append([c.x, c.y, c.z])
			if accAtom.element.number == Element.S:
				hasSulfur[model] = True
		replyobj.status("Building search tree of acceptor atoms\n",
								blankAfter=0)
		accTrees[model] = AdaptiveTree(xyz, accData, 3.0)
	
	if processKey not in processedDonorParams:
		# find max donor distances before they get squared..

		# copy.deepcopy() refuses to copy functions (even as
		# references), so do this instead...
		dParams = []
		for p in donorParams:
			dParams.append(copy.copy(p))

		for di in range(len(dParams)):
			geomType = dParams[di][2]
			argList = dParams[di][4]
			donRad = Element.bondRadius(Element(Element.N))
			if geomType == thetaTau:
				maxDist = max((argList[0], argList[2],
								argList[5]))
			elif geomType == upsilonTau:
				maxDist = max((argList[0], argList[5],
								argList[11]))
			elif geomType == water:
				maxDist = max((argList[1], argList[4],
								argList[8]))
			else:
				maxDist = max(genDonODists
						+ genDonNDists + genDonSDists)
				donRad = Element.bondRadius(Element(Element.S))
			dParams[di].append(maxDist + distSlop + donRad
				+ Element.bondRadius(Element(Element.H)))

		for i in range(len(dParams)):
			dParams[i][4] = _processArgTuple(dParams[i][4],
							distSlop, angleSlop)
		processedDonorParams[processKey] = dParams
	else:
		dParams = processedDonorParams[processKey]
		
	genericWaterParams = _processArgTuple([2.36, 2.36 + OHbondDist, 146],
							distSlop, angleSlop)
	genericThetaTauParams = _processArgTuple([2.48, 132],
							distSlop, angleSlop)
	genericUpsilonTauParams = _processArgTuple([3.42, 90, -161, 125],
							distSlop, angleSlop)
	genericGenericParams = _processArgTuple([2.48, 3.42, 130, 90],
							distSlop, angleSlop)
	for dmi in range(len(models)):
		model = models[dmi]
		replyobj.status("Finding donors in model '%s'\n" % model.name,
								blankAfter=0)
		if cacheDA \
		and _Dcache.has_key(model) \
		and _Dcache[model].has_key((distSlop, angleSlop)):
			donAtoms = []
			donData = []
			for donAtom, data in _Dcache[model][(distSlop,
							angleSlop)].items():
				if not donAtom.__destroyed__:
					donAtoms.append(donAtom)
					donData.append(data)
		else:
			donAtoms, donData = _findDonors(model, dParams,
					limitedDonors, genericDonInfo)
			if cacheDA:
				cache = WeakKeyDictionary()
				for i in range(len(donAtoms)):
					cache[donAtoms[i]] = donData[i]
				if not _Dcache.has_key(model):
					_Dcache[model] = {}
				_Dcache[model][(distSlop, angleSlop)] = cache

		replyobj.status("Matching donors in model '%s' to acceptors\n"
						% model.name, blankAfter=0)
		for i in range(len(donAtoms)):
			donorAtom = donAtoms[i]
			geomType, tauSym, argList, testDist = donData[i]
			donorHyds = hydPositions(donorAtom)
			coord = donorAtom.xformCoord()
			for accModel in models:
				if accModel == model and not intramodel\
				or accModel != model and not intermodel:
					continue
				if accModel.id == model.id \
				   and not interSubmodel \
				   and accModel.subid != model.subid:
					continue
				if hasSulfur[accModel]:
					from commonGeom import SULFUR_COMP
					td = testDist + SULFUR_COMP
				else:
					td = testDist
				accs = accTrees[accModel].searchTree(
					[coord.x, coord.y, coord.z], td)
				if verbose:
					replyobj.message("Found %d possible acceptors for donor %s:\n" % (len(accs), donorAtom.oslIdent()))
					for accData in accs:
						replyobj.message("\t%s\n" % accData[0].oslIdent())
				for accAtom, geomFunc, args in accs:
					if accAtom == donorAtom:
						# e.g. hydroxyl
						if verbose:
							print "skipping: donor == acceptor"
						continue
					# exclude hbonding between
					# differing alt locations of
					# same residue
					if accAtom.altLoc.isalnum() and donorAtom.altLoc.isalnum() and accAtom.residue == donorAtom.residue and accAtom.altLoc != donorAtom.altLoc:
						continue
					try:
						if not apply(geomFunc,
						(donorAtom, donorHyds) + args):
							continue
					except ConnectivityError, v:
						replyobj.message("Skipping possible acceptor with bad geometry: %s\n%s\n\n" % (accAtom.oslIdent(), v))
						badConnectivities += 1
						continue
					if verbose:
						replyobj.message("\t%s satisfies acceptor criteria\n" % accAtom.oslIdent())
					if geomType == upsilonTau:
						donorFunc = donUpsilonTau
						addArgs = genericUpsilonTauParams + [tauSym]
					elif geomType == thetaTau:
						donorFunc = donThetaTau
						addArgs = genericThetaTauParams
					elif geomType == water:
						donorFunc = donWater
						addArgs = genericWaterParams
					else:
						if donorAtom.idatmType in ["Npl", "N2+"]:
							heavys = 0
							for bonded in donorAtom.primaryNeighbors():
								if bonded.element.number > 1:
									heavys += 1
							if heavys > 1:
								info = genDonNpl1HParams
							else:
								info = genDonNpl2HParams
						else:
							info = genericDonInfo[donorAtom.element.name]
						donorFunc, argList = info
						addArgs = genericGenericParams
						if donorFunc == donUpsilonTau:
							# tack on generic
							# tau symmetry
							addArgs = genericUpsilonTauParams + [4]
						elif donorFunc == donThetaTau:
							addArgs = genericThetaTauParams
					try:
						if not apply(donorFunc,
						(donorAtom, donorHyds, accAtom)
						+ tuple(argList + addArgs)):
							continue
					except ConnectivityError, v:
						replyobj.message("Skipping possible donor with bad geometry: %s\n%s\n\n" % (donorAtom.oslIdent(), v))
						badConnectivities += 1
						continue
					except AtomTypeError, v:
						_problem = ("atom type",
							donorAtom, v, None)
						continue
					if verbose:
						replyobj.message("\t%s satisfies donor criteria\n" % donorAtom.oslIdent())
					hbonds.append((donorAtom, accAtom))
예제 #27
0
def doneCommand(name="default"):
	from chimera import replyobj
	_remove(name)
	msg = "Interpolation \"%s\" removed\n" % name
	replyobj.message(msg)
	replyobj.status(msg)
def doneCommand(name="default"):
    from chimera import replyobj
    _remove(name)
    msg = "Interpolation \"%s\" removed\n" % name
    replyobj.message(msg)
    replyobj.status(msg)
예제 #29
0
def readPBinfo(fileName, category=None, clearCategory=1, lineWidth=None,
		drawMode=None, leftModel=None, rightModel=None, defColor=None):
	"""read a file containing pseudobond info and display those bonds

	   'category' defaults to 'fileName'.  'clearCategory' controls
	   whether the pseudobond group should be cleared of pre-existing
	   pseudobonds before reading the file.  'lineWidth' is a floating-
	   point number and controls the width of lines used to draw the
	   pseudobonds.  This only is relevant if 'drawMode' is Wire.
	   'drawMode' controls the depiction style of the pseudobonds.
	   Possible modes are:

	   	Wire (aka chimera.Bond_Wire) -- wireframe
		Stick (aka chimera.Bond_Stick) -- sticks
	
	   'leftModel' and 'rightModel' control what models the endpoints
	   of the pseudobond lie in, if none are specified in the input file.
	   'defColor' is the color assigned to the pseudobond group as a whole,
	   which can be overridden by specific pseudobonds.
	"""
	foundErrors = False
	colorCache = {}

	if not category:
		category = fileName
	
	group = chimera.misc.getPseudoBondGroup(category)
	if lineWidth:
		group.lineWidth = lineWidth
	if drawMode:
		group.drawMode = drawMode

	if clearCategory:
		group.deleteAll()
	
	if defColor:
		if isinstance(defColor, basestring):
			c = chimera.Color.lookup(defColor)
			if not c:
				replyobj.message(
					"Cannot find color '%s'\n" % defColor)
				foundErrors = True
		else:
			c = defColor
		group.color = c

	from OpenSave import osOpen
	bondFile = osOpen(fileName)
	lineNum = 0
	for line in bondFile.readlines():
		line = line.strip()
		lineNum = lineNum + 1

		if not line:
			# blank line
			continue
		
		try:
			spec1, spec2, color = line.split(None, 2)
		except:
			label = color = None
			try:
				spec1, spec2 = line.split()
			except ValueError:
				replyobj.message("Line %d does not have at"
					" least two atom specifiers.")
				foundErrors = True
				continue
		if color:
			# try to distinguish between color name and label
			try:
				color, label = color.split(None, 1)
			except:
				label = None
			if color[0] != "#":
				while (label and not colors.has_key(color)):
					try:
						c, label = label.split(None, 1)
					except:
						color = " ".join([color, label])
						label = None
					else:
						color = " ".join([color, c])
						
		atom1 = _processSpec(spec1, leftModel)
		if not atom1:
			replyobj.message(
				"Left atom spec of line %d of file doesn't"
						" select exactly one atom."
						"  Skipping.\n" % lineNum)
			foundErrors = True
			continue

		atom2 = _processSpec(spec2, leftModel)
		if not atom2:
			replyobj.message(
				"Right atom spec of line %d of file doesn't"
						" select exactly one atom."
						"  Skipping.\n" % lineNum)
			foundErrors = True
			continue

		if color:
			if color[0] == '#':
				fieldLen = int((len(color) - 1) / 3)
				if 3 * fieldLen + 1 != len(color):
					replyobj.message("Bad Tk color '%s'"
						" on line %d of file.\n"
						% (color, lineNum))
					foundErrors = True
				elif colorCache.has_key(color):
					color = colorCache[color]
				else:
					r = color[1:1+fieldLen]
					g = color[1+fieldLen:1+2*fieldLen]
					b = color[1+2*fieldLen:]
					r = int(r, 16)
					g = int(g, 16)
					b = int(b, 16)
					maxVal = int('f' * fieldLen, 16)
					maxVal = float(maxVal)
					c = chimera.MaterialColor(r/maxVal,
							g/maxVal, b/maxVal)
					colorCache[color] = c
					color = c
			else:
				try:
					color = getColorByName(color)
				except KeyError:
					replyobj.message(
						"Unknown color '%s' on line %d"
						" of file.\n" % (color,lineNum))
					foundErrors = True
					color = None
		
		pb = group.newPseudoBond(atom1, atom2)
		if color:
			pb.color = color
		if label:
			pb.label = label
	bondFile.close()

	if foundErrors:
		chimera.replyobj.error(
				"Errors encountered while reading file.\n"
				"Check reply log for details.\n")
예제 #30
0
	def showURLContent(self, title, url):
		from chimera import replyobj
		data = self.getURLContent(url)
		replyobj.message("%s\n-----\n%s-----\n" % (title, data))
예제 #31
0
def readPBinfo(fileName,
               category=None,
               clearCategory=1,
               lineWidth=None,
               drawMode=None,
               leftModel=None,
               rightModel=None,
               defColor=None):
    """read a file containing pseudobond info and display those bonds

	   'category' defaults to 'fileName'.  'clearCategory' controls
	   whether the pseudobond group should be cleared of pre-existing
	   pseudobonds before reading the file.  'lineWidth' is a floating-
	   point number and controls the width of lines used to draw the
	   pseudobonds.  This only is relevant if 'drawMode' is Wire.
	   'drawMode' controls the depiction style of the pseudobonds.
	   Possible modes are:

	   	Wire (aka chimera.Bond_Wire) -- wireframe
		Stick (aka chimera.Bond_Stick) -- sticks
	
	   'leftModel' and 'rightModel' control what models the endpoints
	   of the pseudobond lie in, if none are specified in the input file.
	   'defColor' is the color assigned to the pseudobond group as a whole,
	   which can be overridden by specific pseudobonds.
	"""
    foundErrors = False
    colorCache = {}

    if not category:
        category = fileName

    group = chimera.misc.getPseudoBondGroup(category)
    if lineWidth:
        group.lineWidth = lineWidth
    if drawMode:
        group.drawMode = drawMode

    if clearCategory:
        group.deleteAll()

    if defColor:
        if isinstance(defColor, basestring):
            c = chimera.Color.lookup(defColor)
            if not c:
                replyobj.message("Cannot find color '%s'\n" % defColor)
                foundErrors = True
        else:
            c = defColor
        group.color = c

    from OpenSave import osOpen
    bondFile = osOpen(fileName)
    lineNum = 0
    for line in bondFile.readlines():
        line = line.strip()
        lineNum = lineNum + 1

        if not line:
            # blank line
            continue

        try:
            spec1, spec2, color = line.split(None, 2)
        except:
            label = color = None
            try:
                spec1, spec2 = line.split()
            except ValueError:
                replyobj.message("Line %d does not have at"
                                 " least two atom specifiers.")
                foundErrors = True
                continue
        if color:
            # try to distinguish between color name and label
            try:
                color, label = color.split(None, 1)
            except:
                label = None
            if color[0] != "#":
                while (label and not colors.has_key(color)):
                    try:
                        c, label = label.split(None, 1)
                    except:
                        color = " ".join([color, label])
                        label = None
                    else:
                        color = " ".join([color, c])

        atom1 = _processSpec(spec1, leftModel)
        if not atom1:
            replyobj.message("Left atom spec of line %d of file doesn't"
                             " select exactly one atom."
                             "  Skipping.\n" % lineNum)
            foundErrors = True
            continue

        atom2 = _processSpec(spec2, leftModel)
        if not atom2:
            replyobj.message("Right atom spec of line %d of file doesn't"
                             " select exactly one atom."
                             "  Skipping.\n" % lineNum)
            foundErrors = True
            continue

        if color:
            if color[0] == '#':
                fieldLen = int((len(color) - 1) / 3)
                if 3 * fieldLen + 1 != len(color):
                    replyobj.message("Bad Tk color '%s'"
                                     " on line %d of file.\n" %
                                     (color, lineNum))
                    foundErrors = True
                elif colorCache.has_key(color):
                    color = colorCache[color]
                else:
                    r = color[1:1 + fieldLen]
                    g = color[1 + fieldLen:1 + 2 * fieldLen]
                    b = color[1 + 2 * fieldLen:]
                    r = int(r, 16)
                    g = int(g, 16)
                    b = int(b, 16)
                    maxVal = int('f' * fieldLen, 16)
                    maxVal = float(maxVal)
                    c = chimera.MaterialColor(r / maxVal, g / maxVal,
                                              b / maxVal)
                    colorCache[color] = c
                    color = c
            else:
                try:
                    color = getColorByName(color)
                except KeyError:
                    replyobj.message("Unknown color '%s' on line %d"
                                     " of file.\n" % (color, lineNum))
                    foundErrors = True
                    color = None

        pb = group.newPseudoBond(atom1, atom2)
        if color:
            pb.color = color
        if label:
            pb.label = label
    bondFile.close()

    if foundErrors:
        chimera.replyobj.error("Errors encountered while reading file.\n"
                               "Check reply log for details.\n")
예제 #32
0
 def showURLContent(self, title, url):
     from chimera import replyobj
     data = self.getURLContent(url)
     replyobj.message("%s\n-----\n%s-----\n" % (title, data))