def cmdCombine(mols,
               name="combination",
               newChainIDs=True,
               log=True,
               close=False,
               modelId=None,
               refMol=None):
    from chimera.misc import oslModelCmp
    mols.sort(lambda m1, m2: oslModelCmp(m1.oslIdent(), m2.oslIdent()))

    from Midas import MidasError
    if not mols:
        raise MidasError("No molecules specified")
    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)
예제 #2
0
def aniso(targets=None, color=None, smoothing=3, scale=1.0,
		showEllipsoid=True, transparency=None,
		axisFactor=None, axisColor=None, axisThickness=0.01,
		ellipseFactor=None, ellipseColor=None, ellipseThickness=0.02):
	from Midas import MidasError
	if targets is None:
		targets = openModels.list(modelTypes=[Molecule])
	if smoothing < 1:
		raise MidasError("'smoothing' must be at least 1")
	if transparency is not None:
		try:
			transparency /= 100.0
			if transparency < 0.0 or transparency > 1.0:
				raise TypeError("out of range")
		except TypeError:
			raise MidasError(
				"transparency must be a number between zero and one")
	numShown = mgr().showAniso(targets, color=color,
		smoothing=smoothing, scale=scale,
		showEllipsoid=showEllipsoid, ellipsoidTransparency=transparency,
		axisFactor=axisFactor, axisColor=axisColor, axisThickness=axisThickness,
		ellipseColor=ellipseColor, ellipseFactor=ellipseFactor,
		ellipseThickness=ellipseThickness)
	if not numShown:
		raise MidasError("No atoms chosen or none had anisotropic"
							" information")
예제 #3
0
def typefaceLookup(label):
    try:
        return FONT_TYPEFACE_VALUES[FONT_TYPEFACE_LABELS.index(label)]
    except ValueError:
        from Midas import MidasError
        raise MidasError("No known font typeface '%s'; choices are: %s" %
                         (label, ", ".join(FONT_TYPEFACE_LABELS)))
def revMainchainCmd(cmdName, args):
    # We are going to implement ~mainchain as a synonym for "display",
    # so we import runCommand which simplifies doing that.
    from chimera import runCommand
    from Midas import MidasError
    if args:
        # Raising MidasError will cause the error message
        # to show up in the status line as red text
        raise MidasError("~mainchain takes no arguments")
    # runCommand takes any legal command-line command and executes it.
    runCommand("display")
예제 #5
0
def useBestRotamers(
        resType,
        targets,
        criteria=defaultCriteria,
        lib="Dunbrack",
        preserve=False,
        # clash options
        overlapCutoff=defaults[CLASH_THRESHOLD],
        hbondAllowance=defaults[HBOND_ALLOWANCE],
        scoreMethod=defaults[CLASH_METHOD],
        ignoreOtherModels=False,
        # H-bond options
        relax=True,
        distSlop=recDistSlop,
        angleSlop=recAngleSlop,
        # density options
        density=None,
        log=True):
    """implementation of "swapaa" command.  'targets' is a list of Residues."""
    from Midas import midas_text, MidasError
    lib = lib.capitalize()
    rotamers = {}
    toClose = []
    for res in targets:
        if resType == "same":
            rType = res.type
        else:
            rType = resType.upper()
        try:
            bbdep, rots = getRotamers(res, resType=rType, lib=lib, log=log)
        except NoResidueRotamersError:
            from SwapRes import swap, BackboneError
            if log:
                replyobj.info("Swapping %s to %s\n" % (res, rType))
            try:
                swap(res, rType, bfactor=None)
            except BackboneError, v:
                raise MidasError(str(v))
            continue
        except ImportError:
            raise MidasError("No rotamer library named '%s'" % lib)
예제 #6
0
def func(cmdFile):
	from Midas.midas_text import processCommandFile
	import os.path
	dirName, fileName = os.path.split(cmdFile)
	if dirName:
		if not os.path.exists(dirName):
			from Midas import MidasError
			raise MidasError(
				"No such folder/directory: %s" % dirName)
		import os
		cwd = os.getcwd()
		try:
			os.chdir(dirName)
			processCommandFile(fileName)
		finally:
			os.chdir(cwd)
	else:
		processCommandFile(cmdFile)
	return []
예제 #7
0
def cmdMatch(refSel, matchSel, pairing=defaults[CHAIN_PAIRING],
		alg=defaults[SEQUENCE_ALGORITHM],
		ssFraction=defaults[SS_MIXTURE], matrix=defaults[MATRIX],
		gapOpen=defaults[GAP_OPEN], hgap=defaults[HELIX_OPEN],
		sgap=defaults[STRAND_OPEN], ogap=defaults[OTHER_OPEN],
		iterate=defaults[ITER_CUTOFF], gapExtend=defaults[GAP_EXTEND],
		showAlignment=False, computeSS=defaults[COMPUTE_SS],
		matHH=defaultSSMatrix[('H', 'H')],
		matSS=defaultSSMatrix[('S', 'S')],
		matOO=defaultSSMatrix[('O', 'O')],
		matHS=defaultSSMatrix[('H', 'S')],
		matHO=defaultSSMatrix[('H', 'O')],
		matSO=defaultSSMatrix[('S', 'O')]):
	"""wrapper for command-line command (friendlier args)"""
	from Midas import MidasError
	if matrix not in SmithWaterman.matrices:
		raise MidasError("No such matrix name: %s" % str(matrix))
	try:
		gapOpen + 1
		gapExtend + 1
		hgap + 1
		sgap + 1
		ogap + 1
	except TypeError:
		raise MidasError("Gap open/extend penalties must be numeric")
	if pairing == CP_SPECIFIC_SPECIFIC:
		matches = matchSel.chains()
	elif pairing == CP_SPECIFIC_BEST:
		matches = matchSel.molecules()
	if pairing == CP_SPECIFIC_SPECIFIC or pairing == CP_SPECIFIC_BEST:
		refs = refSel.chains()
		if not refs:
			raise MidasError("No reference chains specified")
		if pairing == CP_SPECIFIC_BEST and len(refs) > 1:
			raise MidasError("Specify a single reference"
								" chain only")
	else:
		refMols = refSel.molecules()
		if not refMols:
			raise MidasError("No reference model specified")
		if len(refMols) > 1:
			raise MidasError("Specify a single reference"
								" model only")
		refs = refMols
		matches = matchSel.molecules()
	if not matches:
		raise MidasError("No molecules/chains to match specified")
	for ref in refs:
		if ref in matches:
			matches.remove(ref)
	if not matches:
		raise MidasError("Must use different reference and match"
								" structures")
	if pairing == CP_SPECIFIC_SPECIFIC:
		if len(refs) != len(matches):
			raise MidasError("Different number of reference/match"
					" chains (%d ref, %d match)" %
					(len(refs), len(matches)))
		matchItems = zip(refs, matches)
	else:
		matchItems = (refs[0], matches)
	ssMatrix = {}
	ssMatrix[('H', 'H')] = float(matHH)
	ssMatrix[('S', 'S')] = float(matSS)
	ssMatrix[('O', 'O')] = float(matOO)
	ssMatrix[('H', 'S')] = ssMatrix[('S', 'H')] = float(matHS)
	ssMatrix[('H', 'O')] = ssMatrix[('O', 'H')] = float(matHO)
	ssMatrix[('S', 'O')] = ssMatrix[('O', 'S')] = float(matSO)
	if type(iterate) == bool and not iterate:
		iterate = None
	try:
		match(pairing, matchItems, matrix, alg, gapOpen, gapExtend,
			ssFraction=ssFraction, ssMatrix=ssMatrix,
			iterate=iterate, showAlignment=showAlignment,
			gapOpenHelix=hgap, gapOpenStrand=sgap,
			gapOpenOther=ogap, computeSS=computeSS)
	except UserError, v:
		raise MidasError, v
예제 #8
0
def processLabel2DCmd(action,
                      labelID,
                      text=None,
                      color=None,
                      size=None,
                      style=None,
                      typeface=None,
                      xpos=None,
                      ypos=None,
                      visibility=None,
                      frames=None):

    from Midas import MidasError

    if type(xpos) == list or type(ypos) == list:
        raise MidasError("Multiple occurances of 'xpos' or 'ypos' keywords")

    try:
        if xpos: xpos + 0
        if ypos: ypos + 0
    except:
        raise MidasError("xpos/ypos values must be numeric")

    global _ilabelModel
    if not _ilabelModel:
        IlabelModel()
    model = _ilabelModel

    if text is not None:
        # text might have evaluated as an integer or something
        text = unicode(text)

        # backslash interpretation...
        if '\\' in text:
            if '"' not in text:
                text = eval('"' + text + '"')
            elif "'" not in text:
                text = eval("'" + text + "'")

    if action == "create":
        ## get the position
        if xpos == None:
            xpos = .5
        if ypos == None:
            ypos = .5

        if not color:
            color = chimera.Color.lookup('white')

        if not size:
            size = 24

        if not style:
            style = "normal"

        if not typeface:
            typeface = "sans serif"

        ## make a new label
        try:
            label = model.newLabel((xpos, ypos), labelID)
        except RuntimeError, what:
            raise MidasError, what

        ## set it's content
        label.set(text or '')

        ## color and size the characters
        changeLabelAttrs(label, size, color, styleLookup(style),
                         typefaceLookup(typeface))

        if visibility == "hide":
            label.shown = False
예제 #9
0
        except ImportError:
            raise MidasError("No rotamer library named '%s'" % lib)
        if preserve:
            rots = pruneByChis(rots, res, log=log)
        rotamers[res] = rots
        toClose.extend(rots)

    # this implementation allows tie-breaking criteria to be skipped if
    # there are no ties
    for char in criteria:
        if char == "d":
            # density
            if density == None:
                if criteria is defaultCriteria:
                    continue
                raise MidasError("Density criteria requested"
                                 " but no density model specified")
            from VolumeViewer.volume import Volume
            if isinstance(density, list):
                density = [d for d in density if isinstance(d, Volume)]
            else:
                density = [density]
            if not density:
                raise MidasError("No volume models in"
                                 " specified model numbers")
            if len(density) > 1:
                raise MidasError("Multiple volume models in"
                                 " specified model numbers")
            allRots = []
            for res, rots in rotamers.values():
                chimera.openModels.add(rots, sameAs=res.molecule, hidden=True)
                allRots.extend(rots)
예제 #10
0
def cmdDetectClash(testAtoms,
                   overlapCutoff=defaults[CLASH_THRESHOLD],
                   hbondAllowance=defaults[HBOND_ALLOWANCE],
                   test="others",
                   setAttrs=defaults[ACTION_ATTR],
                   selectClashes=defaults[ACTION_SELECT],
                   colorClashes=defaults[ACTION_COLOR],
                   clashColor=defColors[CLASH_COLOR],
                   nonclashColor=defColors[NONCLASH_COLOR],
                   makePseudobonds=defaults[ACTION_PSEUDOBONDS],
                   pbColor=defColors[PB_COLOR],
                   lineWidth=defaults[PB_WIDTH],
                   bondSeparation=defaults[BOND_SEPARATION],
                   saveFile=None,
                   namingStyle=None,
                   ignoreIntraRes=defaults[IGNORE_INTRA_RES],
                   interSubmodel=False,
                   log=defaults[ACTION_REPLYLOG],
                   summary=True,
                   continuous=False):
    global _continuousID
    from Midas import MidasError
    if continuous:
        if setAttrs or saveFile != None or log:
            raise MidasError("log/setAttrs/saveFile not allowed"
                             " with continuous detection")
        if _continuousID == None:
            from inspect import getargvalues, currentframe
            argNames, fArgs, fKw, frameDict = getargvalues(currentframe())
            callData = [frameDict[an] for an in argNames]

            def preCB(trigName, myData, changes):
                if 'transformation change' in changes.reasons:
                    return _motionCB(myData)

            _continuousID = chimera.triggers.addHandler(
                'OpenState', preCB, callData)
    elif _continuousID != None:
        chimera.triggers.deleteHandler('OpenState', _continuousID)
        _continuousID = None
    if isinstance(test, basestring):
        if test.startswith("other"):
            test = "others"
        elif test not in ('self', 'model'):
            # atom spec
            from chimera.specifier import evalSpec
            try:
                test = evalSpec(test).atoms()
            except:
                raise MidasError("Could not parse atom spec '%s'" % test)
    clashes = detectClash(testAtoms,
                          test=test,
                          hbondAllowance=hbondAllowance,
                          clashThreshold=overlapCutoff,
                          bondSeparation=bondSeparation,
                          intraRes=not ignoreIntraRes,
                          interSubmodel=interSubmodel)
    if selectClashes:
        chimera.selection.setCurrent(clashes.keys())
    if test == "self":
        outputGrouping = set()
    else:
        outputGrouping = testAtoms
    info = (overlapCutoff, hbondAllowance, bondSeparation, ignoreIntraRes,
            clashes, outputGrouping)
    if log:
        import sys
        # put a separator in the Reply Log
        print >> sys.stdout, ""
        _fileOutput(sys.stdout, info, namingStyle=namingStyle)
    if saveFile == '-':
        from FindHBond.MolInfoDialog import SaveMolInfoDialog
        SaveMolInfoDialog(info,
                          _fileOutput,
                          initialfile="overlaps",
                          title="Choose Overlap Info Save File",
                          historyID="Overlap info")
    elif saveFile is not None:
        _fileOutput(saveFile, info, namingStyle=namingStyle)
    if summary == True:

        def _summary(msg):
            from chimera import replyobj
            replyobj.status(msg + '\n')
            replyobj.info(msg + '\n')

        summary = _summary
    if summary:
        if clashes:
            total = 0
            for clashList in clashes.values():
                total += len(clashList)
            summary("%d contacts" % (total / 2))
        else:
            summary("No contacts")
    if not (setAttrs or colorClashes or makePseudobonds):
        nukeGroup()
        return clashes
    if test in ("others", "model"):
        atoms = [
            a for m in chimera.openModels.list(modelTypes=[chimera.Molecule])
            for a in m.atoms
        ]
    else:
        atoms = testAtoms
    if setAttrs:
        # delete the attribute in _all_ atoms...
        for m in chimera.openModels.list(modelTypes=[chimera.Molecule]):
            for a in m.atoms:
                if hasattr(a, attrName):
                    delattr(a, attrName)
        for a in atoms:
            if a in clashes:
                clashVals = clashes[a].values()
                clashVals.sort()
                setattr(a, attrName, clashVals[-1])
    if colorClashes:
        for a in atoms:
            a.surfaceColor = None
            if a in clashes:
                a.color = clashColor
            else:
                a.color = nonclashColor
    if makePseudobonds:
        from chimera.misc import getPseudoBondGroup
        pbg = getPseudoBondGroup(groupName)
        pbg.deleteAll()
        pbg.lineWidth = lineWidth
        pbg.color = pbColor
        seen = set()
        for a in atoms:
            if a not in clashes:
                continue
            seen.add(a)
            for clasher in clashes[a].keys():
                if clasher in seen:
                    continue
                pbg.newPseudoBond(a, clasher)
    else:
        nukeGroup()
    return clashes