Ejemplo n.º 1
0
def cal_SASA(input_pdb, output_prefix):

    print "pdb inputs    = " + input_pdb
    print "output prefix = " + output_prefix

    model = openModels.open(input_pdb)
    runCommand("surf :all")
    out = open(output_prefix + "sasa.txt", "w")
    x = '---------------------------------------------------------------------------------\n'
    print "list " + str(list(model))
    for m in openModels.list(modelTypes=[Molecule]):
        msas = 0
        for r in m.residues:
            try:
                sas = r.areaSAS
            except AttributeError:
                continue
            msas = msas + sas
            out.write('%s,%f\n' % (r, sas))
        out.write(x)
        out.write('%s,%f\n' % (m, msas))
        out.write('\n')
    out.close()
    runCommand("del")
    print msas
    return msas
Ejemplo n.º 2
0
def main(mask='*.zip', output_directory='.'):
    try:
        os.mkdir(output_directory)
    except:
        pass
    tan_color = chimera.colorTable.getColorByName('tan')
    files = sorted(glob(mask), reverse=True)
    # distances = []
    # print('Presorting...')
    # for i, zip_file in enumerate(files):
    #     centers = []
    #     for molecule in parse_zip(zip_file):
    #         centers.append(center_of_mass(molecule.atoms))
    #     distances.append(chimera.Point(*centers[0]).distance(chimera.Point(*centers[1])))
    #     chimera.closeSession()

    # distance_sorted = [f for (d, f) in sorted(zip(distances, files), reverse=True)]
    for i, zip_file in enumerate(files):
        print('{}/{} Rendering {}...'.format(i + 1, len(files), zip_file))
        molecules = list(parse_zip(zip_file))
        protein = sorted(molecules, key=lambda m: m.numAtoms)[-1]
        protein.color = tan_color
        if not i:
            chimera.runCommand('focus')
        render(counter=i, output_dir=output_directory)
        chimera.closeSession()
def main():
  print sys.argv
  if len(sys.argv) != 3: # if no input
     print "ERROR: Wrong number of inputs"
     print "syntax: chimera --nogui --script \"chimera_move_pdb.py pdbinput output_prefix\""
     print len(sys.argv)
     return


  input_pdb     = sys.argv[1]
  output_prefix = sys.argv[2]

  print "pdb input = " + input_pdb 
  print "output prefix = "+ output_prefix
  model = openModels.open(input_pdb) 

  #prep(model)
  start = 0.0
  #list = [start]
  for i in range(10):
      start = start + 0.03
      #list.append(start)
      runCommand("move x 0.03 ")
      print output_prefix+"."+str(start)+".pdb"
      runCommand("write 0 "+output_prefix+"."+str(start)+".pdb")
Ejemplo n.º 4
0
    def recordAnimation(self,
                        startFrame=None,
                        endFrame=None,
                        step=1,
                        recordArgs="",
                        encodeArgs=""):
        if startFrame is None:
            startFrame = self.startFrame
        if endFrame is None:
            endFrame = self.endFrame

        if self.recording:
            self.status("Already recording an animation", color="red")
            return

        self.stopMovieCallback()

        self.currentFrame.set(startFrame)
        self.recordEnd = endFrame
        self.recordStep = step
        self.encodeArgs = encodeArgs
        self.LoadFrame()
        self.recording = True
        from chimera import runCommand
        self.status("Recording animation...", blankAfter=0)
        runCommand("movie record " + recordArgs)
        chimera.triggers.addHandler("post-frame", self._startAnimation, None)
Ejemplo n.º 5
0
	def recordAnimation(self, startFrame=None, endFrame=None,
				step=1, recordArgs="", encodeArgs=""):
		if startFrame is None:
			startFrame = self.startFrame
		if endFrame is None:
			endFrame = self.endFrame

		if self.recording:
			self.status("Already recording an animation",
								color="red")
			return

		self.stopMovieCallback()

		self.currentFrame.set(startFrame)
		self.recordEnd = endFrame
		self.recordStep = step
		self.encodeArgs = encodeArgs
		self.LoadFrame()
		self.recording = True
		from chimera import runCommand
		self.status("Recording animation...", blankAfter=0)
		runCommand("movie record " + recordArgs)
		chimera.triggers.addHandler("post-frame", self._startAnimation,
								None)
Ejemplo n.º 6
0
	def abortRecording(self):
		if not self.recording:
			return
		from chimera import runCommand
		self.recording = False
		runCommand("movie stop; movie reset")
		self.status("Animation recording aborted")
def plotPosition(coordinates_file):
    with open(coordinates_file, 'r') as cf:
        names = {}
        points = []
        reference = cf.readline().strip()
        for line in cf:
            name = line.split()[0]
            coordinates = line.split()[1:]
            if name not in names:
                names[name] = len(names)
            points.append((coordinates, names[name], name))

        color_map = cm.jet
        categories = len(names)
        if categories == 1:
            categories += 1

        for point in points:
            sphere_shape(radius=0.5,
                         divisions=10,
                         center=", ".join(point[0]),
                         color=[
                             i * j for i, j in zip(
                                 color_map(point[1] * (color_map.N - 1) /
                                           (categories - 1)), [1, 1, 1, 0.3])
                         ],
                         modelId=point[1],
                         modelName=point[2])

        print "open %s" % reference
        chimera.runCommand("open %s" % reference)
Ejemplo n.º 8
0
def mutate_nt(pam_idx, base):
    """Mutate a base pair at pam_idx to base
    Args:
        pam_idx: the index of the PAM nucleotide to be modified
        base: what the nt at pam_idx will be changed to
    """
    position_idx = {
        0: "5.d",
        1: "6.d",
        2: "7.d",
        3: "8.d"
    }  # Nucleotides we want to mutate are located at positions 5,6,7 in chain D (PAM,NGG) and 8,7,6 in chain C (target strand, NCC).
    position_pairs = {
        "5.d": "8.c",
        "6.d": "7.c",
        "7.d": "6.c",
        "8.d": "5.c"
    }  # Create a dictionary mapping corresponding positions to each other.
    base_pairs = {
        'a': 't',
        'c': 'g',
        'g': 'c',
        't': 'a'
    }  # Create dictionary mapping valid base pairs to each other.

    pos = position_idx[pam_idx]
    complement_base = base_pairs[base]
    complement_pos = position_pairs[pos]
    runCommand("swapna " + base + " : " + pos)
    runCommand("swapna " + complement_base + " : " + complement_pos)
Ejemplo n.º 9
0
    def openVolume(self):
        try:
            while True:
                if self.vol_conn.poll():

                    msg = self.vol_conn.recv()
                    if msg == "open_volume":
                        data = self.vol_conn.recv()  # objects are serialized by default
                        grid = Array_Grid_Data(data)
                        self.volume = volume_from_grid_data(grid)

                    elif msg == "voxel_size":
                        self.voxelSize = self.vol_conn.recv()
                        cmd = "volume #0 voxelSize %s" % self.voxelSize
                        runCommand(cmd)

                    elif msg == "command_list":
                        commandList = self.vol_conn.recv()
                        for command in commandList:
                            runCommand(command)

                    elif msg == "end":  # if you don't break cicle volume is never shown
                        break

                else:
                    sleep(0.01)
        except EOFError:
            print("Lost connection to client")
Ejemplo n.º 10
0
 def abortRecording(self):
     if not self.recording:
         return
     from chimera import runCommand
     self.recording = False
     runCommand("movie stop; movie reset")
     self.status("Animation recording aborted")
Ejemplo n.º 11
0
	def myRunCommand(*args):
		from Midas import MidasError
		try:
			runCommand(*args)
		except MidasError, v:
			from chimera import replyobj
			replyobj.status(str(v), color="red")
Ejemplo n.º 12
0
def set_center_of_rotation():
    'Set center of rotation to center of selected atoms or use center of models mode if no atoms are selected'
    from chimera import selection
    if selection.currentEmpty():
        chimera.runCommand('~cofr')
    else:
        chimera.runCommand('cofr sel')
Ejemplo n.º 13
0
def surface_selected_atoms():
    'Show MSMS molecular surface enclosing just the selected atoms'
    global surface_category_number
    category_name = 'c%d' % surface_category_number
    chimera.runCommand('surfcat %s sel' % category_name)
    surface_category_number += 1
    chimera.runCommand('surface %s' % category_name)
Ejemplo n.º 14
0
    def openVolume(self):
        try:
            while True:
                if self.vol_conn.poll():
                    
                    msg = self.vol_conn.recv()
                    if msg == 'open_volume':
                        data = self.vol_conn.recv()#objects are serialized by default
                        grid = Array_Grid_Data(data)
                        self.volume = volume_from_grid_data(grid)
                        
                    elif msg == 'voxel_size':
                        self.voxelSize = self.vol_conn.recv()
                        cmd = "volume #0 voxelSize %s"%self.voxelSize
                        runCommand(cmd)


                    elif msg == 'command_list':
                        commandList = self.vol_conn.recv()
                        for command in commandList:
                            runCommand(command)

                    elif msg == 'end':#if you don't break cicle volume is never shown
                        break

                else:
                    sleep(0.01)
        except EOFError:
            print ('Lost connection to client')
Ejemplo n.º 15
0
def create_dm(pdbname, outputname):
    # create density map
    chan = chimera.openModels.open(pdbname)[0]
    chimera.runCommand('molmap #0 %s modelId 1' % str(RESOULTION))
    dm = chimera.specifier.evalSpec('#1').models()[0]
    chan.destroy()

    # rotate and save
    translation = [0, 0, 0]
    rot_phi = euler_xform([ANGLE_RES, 0, 0], translation)
    rot_theta = euler_xform([0, ANGLE_RES, 0], translation)
    rot_psi = euler_xform([0, 0, ANGLE_RES], translation)
    for theta in range(0, 181, ANGLE_RES):
        for phi in range(0, 360, ANGLE_RES):
            for psi in range(0, 360, ANGLE_RES):
                dm.openState.localXform(rot_psi)
                angle_str = ''.join(
                    ['_' + str(angle) for angle in [phi, theta, psi]])
                np.save(outputname + angle_str, dm.matrix())
            dm.openState.localXform(rot_psi)
            dm.openState.localXform(rot_phi)
        dm.openState.localXform(rot_phi)
        dm.openState.localXform(rot_theta)

    dm.close()
Ejemplo n.º 16
0
def main():
    print sys.argv
    if len(sys.argv) != 3:  # if no input
        print "ERROR: Wrong number of inputs"
        print "syntax: chimera --nogui --script \"chimera_dockprep.py pdbinput output_prefix\""
        print len(sys.argv)
        return

    #models = openModels.list(modelTypes=[chimera.Molecule])

    input_pdb = sys.argv[1]
    output_prefix = sys.argv[2]

    print "pdb input = " + input_pdb
    print "output prefix = " + output_prefix

    #runCommand("open " + input_pdb)
    #models = chimera.openModels.list(modelTypes=[chimera.Molecule])
    #model = models
    model = openModels.open(input_pdb)
    #runCommand("del @H,H?,H??,H???") # remove all hydrogens

    writeMol2(model, output_prefix + "before_dockprep.mol2")

    prep(model)

    runCommand("write 0 " + output_prefix + ".pdb")
    writeMol2(model, output_prefix + ".mol2")

    runCommand("del HC")  # remove all non-polar hydrogens
    runCommand("write 0 " + output_prefix + "_polarH.pdb")
    runCommand("del @H,H?,H??,H???")  # remove all hydrogens
    runCommand("write 0 " + output_prefix + "_noH.pdb")
 def runChimCommand(self, cmd):
         if self.chimlog is not None:
                 f = open(self.chimlog, "a")
                 f.write(str(cmd)+"\n")
                 f.close()
                 #nogui_message(cmd.strip()+"\n")
         chimera.runCommand(cmd)
Ejemplo n.º 18
0
def color_map(resolution):
    import chimera
    from chimera import runCommand
    maxres = 3.93
    minres = 6.7371428571428575
    a = (resolution - maxres) / (minres - maxres)
    r, g, b = 1 - a, 0.0, a
    runCommand('color %0.2f,%0.2f,%0.2f,1.0 #1' % (r, g, b))
Ejemplo n.º 19
0
  def Cancel(self):

    from chimera import runCommand
    from Midas import MidasError
    try:
      runCommand('movie reset')
    except MidasError:
      pass      # Suppress error when user already reset movie by other means.
    self.Close()
Ejemplo n.º 20
0
    def Cancel(self):

        from chimera import runCommand
        from Midas import MidasError
        try:
            runCommand('movie reset')
        except MidasError:
            pass  # Suppress error when user already reset movie by other means.
        self.Close()
Ejemplo n.º 21
0
 def run_command(self, *args, **kwargs):
     """
     Get the contents of the CLI field and run them in Chimera.
     """
     command = self.gui.clifield.get()
     try:
         chimera.runCommand(command)
     except Midas.MidasError as e:
         print e
         self.gui.error(e.__str__())
Ejemplo n.º 22
0
def main():
    print sys.argv
    if len(sys.argv) != 3:  # if no input
        print "ERROR: Wrong number of inputs"
        print "syntax: /nfs/software/chimera/current/bin/chimera --nogui --script 'chimera_rmsd.py temp.txt \"#0:107-115@N,CA,C,O #1:107-115@N,CA,C,O\" '"
        print len(sys.argv)
        return

    #models = openModels.list(modelTypes=[chimera.Molecule])

    input_list_file = sys.argv[1]
    #output_prefix   = sys.argv[2]
    seltion_rmsd = sys.argv[2]
    print "pdb inputs    = " + input_list_file
    #print "output prefix = " + output_prefix
    print "seltion_rmsd = " + seltion_rmsd

    fileh = open(input_list_file)
    lines = fileh.readlines()
    N = len(lines)
    print "there are N systems:" + str(N)

    fileh.close()

    #seltion_align = "#0:1-115@N,CA,C,O #1:107-115@N,CA,C,O"
    #seltion_rmsd  = "#0:107-115@N,CA,C,O #1:107-115@N,CA,C,O"

    #calulate alignment.
    # this will already be aligned.
    #templete = lines[0]
    #runCommand("open "+ templete)
    #for pdb_file in lines:
    #    runCommand("open "+ pdb_file)
    #    runCommand(ma

    #seltion = "#0:111@N,CA,C,O #1:111@N,CA,C,O"
    #seltion = "#0:108@N,CA,C,O #1:108@N,CA,C,O"

    for i in range(0, N):
        pdb_file1 = lines[i].strip('\n')
        runCommand("open " + pdb_file1)
        #for pdb_file2 in lines:
        for j in range(i + 1, N):
            pdb_file2 = lines[j].strip('\n')
            print '\n########\n files:  ' + pdb_file1 + "   " + pdb_file2 + '\n########\n'
            #sys.stdout = open(output_prefix+"_"+str(i)+"_"+str(i)+".txt", 'w')
            runCommand("open " + pdb_file2)
            runCommand("rmsd " + seltion_rmsd)
            #print "rmsd_Text", rmsd_Text
            runCommand("del #1")
            #runCommand("write 0 "+output_prefix+"_polarH.pdb")
            #sys.stdout.close()

        runCommand("del #0")
Ejemplo n.º 23
0
  def finish_recording(self):

    self.recording = False

    if self.play_handler:
      self.stop_playing()
    
    from chimera import runCommand
    runCommand('movie stop')

    self.save_movie_cb()
Ejemplo n.º 24
0
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")
def generate_pam_variant_chimera(pam, input_pdb, output_dir):
    """Generate a new PDB file
    Args:
        pam: new PAM sequence to be listed in name
        template_pdb_basename: original fine basename
        output_dir: output directory
    """
    template_pdb_basename = os.path.basename(input_pdb)
    new_pdb_path = os.path.join(output_dir, template_pdb_basename[:-4] + "." + pam + ".pdb")
    runCommand("write 0 " + new_pdb_path)
    runCommand("close all")
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")
Ejemplo n.º 27
0
def generate_pam_variant_chimera(pam, input_pdb, output_dir):
    """Generate a new PDB file
    Args:
        pam: new PAM sequence to be listed in name
        template_pdb_basename: original fine basename
        output_dir: output directory
    """
    template_pdb_basename = os.path.basename(input_pdb)
    new_pdb_path = os.path.join(
        output_dir, template_pdb_basename[:-4] + "." + pam + ".pdb")
    runCommand("write 0 " + new_pdb_path)
    runCommand("close all")
Ejemplo n.º 28
0
	def run(self):
		if self._mi is None:
			from chimera import UserError
			raise UserError("Please finish adding hydrogens and "
					"charges before trying to minimize")
		import chimera
		self._mi.setFixed(self.freeze)
		self._mi.loadMMTKCoordinates()
		chimera.runCommand("wait 1")
		self._mi.minimize(nsteps=self.nsteps, stepsize=self.stepsize,
					interval=self.interval,
					action=self.updateCoords)
Ejemplo n.º 29
0
 def html(*models):
     if models:
         for m in chimera.openModels.list():
             m.display = False
         chimera.selection.clearCurrent()
         for model in models:
             model.display = True
             chimera.selection.addCurrent(model)
             chimera.runCommand('focus sel')
     chimera.viewer.windowSize = 800, 600
     path = 'chimera_scene_export.html'
     Midas.export(filename=path, format='WebGL')
     return IFrame(path, *[x + 20 for x in chimera.viewer.windowSize])
Ejemplo n.º 30
0
 def _endRecording(self, *args):
     from Midas import MidasError
     try:
         from chimera import runCommand
         runCommand("movie stop")
         self.status("Compiling frames into animation", blankAfter=5)
         runCommand("movie encode " + self.encodeArgs)
     except:
         self.status("Error stopping/encoding movie", color="red")
         from chimera.replyobj import reportException
         reportException("Error stopping/encoding movie")
     from chimera.triggerSet import ONESHOT
     return ONESHOT
Ejemplo n.º 31
0
 def run(self):
     if self._mi is None:
         from chimera import UserError
         raise UserError("Please finish adding hydrogens and "
                         "charges before trying to minimize")
     import chimera
     self._mi.setFixed(self.freeze)
     self._mi.loadMMTKCoordinates()
     chimera.runCommand("wait 1")
     self._mi.minimize(nsteps=self.nsteps,
                       stepsize=self.stepsize,
                       interval=self.interval,
                       action=self.updateCoords)
Ejemplo n.º 32
0
  def Apply(self):

    path, format = self.getPathsAndTypes()[0]
    
    from MovieRecorder import RecorderGUI
    for fmt, f in RecorderGUI.command_formats.items():
      if f[0] == format:
        break
    from CGLtk.Hybrid import float_variable_value
    bit_rate = float_variable_value(self.bit_rate, self.default_bit_rate)

    from chimera import runCommand
    runCommand('movie encode mformat %s bitrate %f output "%s"'
               % (fmt, bit_rate, path))
Ejemplo n.º 33
0
def clean_canvas(molecule):
    chimera.runCommand('delete solvent')
    for element in ('CA', 'NA'):
        chimera.runCommand('sel @/element={}'.format(element))
        if len(chimera.selection.currentAtoms()) > 1:
            chimera.runCommand('del @/element={}'.format(element))
    chimera.runCommand('delete @/element=NA')
Ejemplo n.º 34
0
    def Apply(self):

        path, format = self.getPathsAndTypes()[0]

        from MovieRecorder import RecorderGUI
        for fmt, f in RecorderGUI.command_formats.items():
            if f[0] == format:
                break
        from CGLtk.Hybrid import float_variable_value
        bit_rate = float_variable_value(self.bit_rate, self.default_bit_rate)

        from chimera import runCommand
        runCommand('movie encode mformat %s bitrate %f output "%s"' %
                   (fmt, bit_rate, path))
Ejemplo n.º 35
0
def runAlign():
	# -----------------------------------------------------------------------------
	### set files
	#maindir = '/ami/data16/appion/09mar04b/models/emanmodel28'
	default_settings.set('limit_voxel_count', False)
	maindir = '/home/vossman/Documents/papers/initmodel/initmodels-figure'
	map1_path = os.path.join(maindir, 'reconemdb.mrc')

	map1 = open_volume_file(map1_path)[0]
	map1.set_parameters(surface_levels = [1.0])
	mrcfiles = glob.glob(os.path.join(maindir, '*.mrc'))
	aligndir = os.path.join(maindir, 'align/')
	if not os.path.isdir(aligndir):
		os.mkdir(aligndir)
	N = len(mrcfiles)
	random.shuffle(mrcfiles)
	for i,mrcfile in enumerate(mrcfiles):
		if os.path.basename(mrcfile)[:5] == "align":
			continue
		new_path = os.path.join(aligndir, 'align'+os.path.basename(mrcfile))
		if os.path.isfile(new_path):
			print "----------", os.path.basename(mrcfile)
			continue
		print ("\n==============================\n", 
			os.path.basename(mrcfile), 
			"\n==============================\n")
		map2 = open_volume_file(mrcfile)[0]
		map2.set_parameters(surface_levels = [1.0])
		new_path = os.path.join(aligndir, 'align'+os.path.basename(mrcfile))
		fit_map_in_map(map1, map2, map1_threshold=1.0)
		runCommand('vop #1 resample onGrid #0 modelId %d'%(i+N))
		runCommand('volume #%d save %s'%(i+N, new_path))
		map2.close()
		runCommand('close #1')
		runCommand('close #%d'%(i+N))
Ejemplo n.º 36
0
 def chimera_smiles_btn_cb(self, *args, **kwargs):
     molecules = self.bk_selected_molecules()
     if not molecules:
         return
     from bkchem.oasa_bridge import mol_to_smiles
     cmd = self.gui.ui_cmdline.getvalue()
     for m in molecules:
         smiles = mol_to_smiles(m)
         cmol = chimera.openModels.open(smiles, type='SMILES')[0]
         self.imported_molecules.append(cmol)
         if cmd:
             try:
                 chimera.runCommand(cmd.replace('#$', cmol.oslIdent()))
             except chimera.UserError as e:
                 self.gui.status(str(e), color='red', blankAfter=3)
Ejemplo n.º 37
0
	def _endRecording(self, *args):
		from Midas import MidasError
		try:
			from chimera import runCommand
			runCommand("movie stop")
			self.status("Compiling frames into animation",
								blankAfter=5)
			runCommand("movie encode " + self.encodeArgs)
		except:
			self.status("Error stopping/encoding movie",
								color="red")
			from chimera.replyobj import reportException
			reportException("Error stopping/encoding movie")
		from chimera.triggerSet import ONESHOT
		return ONESHOT
def mutate_nt(pam_idx, base):
    """Mutate a base pair at pam_idx to base
    Args:
        pam_idx: the index of the PAM nucleotide to be modified
        base: what the nt at pam_idx will be changed to
    """
    position_idx = { 0 : "5.d", 1 : "6.d", 2 : "7.d", 3 : "8.d"} # Nucleotides we want to mutate are located at positions 5,6,7 in chain D (PAM,NGG) and 8,7,6 in chain C (target strand, NCC).
    position_pairs = { "5.d" : "8.c", "6.d" : "7.c", "7.d" : "6.c", "8.d" : "5.c"} # Create a dictionary mapping corresponding positions to each other.
    base_pairs = {'a' : 't', 'c' : 'g', 'g' : 'c', 't' : 'a'} # Create dictionary mapping valid base pairs to each other.

    pos = position_idx[pam_idx]
    complement_base = base_pairs[base]
    complement_pos = position_pairs[pos]
    runCommand("swapna " + base + " : " + pos )
    runCommand("swapna " + complement_base + " : " + complement_pos)
Ejemplo n.º 39
0
def main():
    if len(sys.argv) != 3:  # if no input
        print "ERORR"
        return
    input_mol2 = sys.argv[1]
    output_dms = sys.argv[2]

    runCommand("open " + input_mol2)

    # generate surface using 'surf' command
    runCommand("surf")
    # get the surf object
    surf = openModels.list(modelTypes=[MSMSModel])[0]
    # write DMS
    writeDMS(surf, output_dms)
    return
Ejemplo n.º 40
0
	def _runCommand(self, cmd):
		import sys
		if not chimera.nogui:
			print "CMD", cmd.rstrip()
		sys.stdout.flush()
		try:
			from Midas import MidasError
			from chimera.oslParser import OSLSyntaxError
			from chimera import replyobj
			try:
				chimera.runCommand(cmd)
			except (MidasError, OSLSyntaxError), v:
				replyobj.error(str(v) + '\n')
		finally:
			if not chimera.nogui:
				print "\nEND"
			sys.stdout.flush()
Ejemplo n.º 41
0
def placeFragment(fragment, resName, model="scratch", position=None):
	"""place a Fragment (see Fragment.py)

	   'resName' is the name of the new residue that will contain the
	   fragment.  (It will be in the 'het' chain.)

	   'model' can either be a chimera.Molecule instance or a string.
	   If the latter, then a new model is created with the string as
	   its .name attribute.

	   'position' can either be a chimera.Point or None.  If None, then
	   the fragment is positioned at the center of the view.
	"""

	if isinstance(model, basestring):
		model = _newModel(model)
	r = _newResidue(model, resName)
	needFocus = False
	if position is None:
		if len(chimera.openModels.list()) == 1:
			needFocus = True
		xf = model.openState.xform
		position = xf.inverse().apply(
				Point(*chimera.viewer.camera.center))
	# find fragment center
	x = y = z = 0.0
	for element, xyz in fragment.atoms:
		x += xyz[0]
		y += xyz[1]
		z += xyz[2]
	numAtoms = len(fragment.atoms)
	fragCenter = Point(x / numAtoms, y / numAtoms, z / numAtoms)
	correction = position - fragCenter

	from chimera.molEdit import addAtom, genAtomName
	atoms = []
	for element, xyz in fragment.atoms:
		atoms.append(addAtom(genAtomName(element, r), Element(element),
						r, Point(*xyz) + correction))
	for indices, depict in fragment.bonds:
		r.molecule.newBond(atoms[indices[0]], atoms[indices[1]])
	if needFocus:
		chimera.runCommand("focus")
	return r
Ejemplo n.º 42
0
 def focus_binding_site(self, binding_site):
     resname, chain, resid = binding_site.split(':')
     try:
         spec = ':{}.{}'.format(resid,
                                chain) if chain else ':{}'.format(resid)
         chimera.runCommand('show {} zr < 5'.format(spec))
         chimera.runCommand('focus {} zr < 5'.format(spec))
     except MidasError:
         spec = ':{}'.format(resname)
         chimera.runCommand('show {} zr < 5'.format(spec))
         chimera.runCommand('focus {} zr < 5'.format(spec))
Ejemplo n.º 43
0
def placeFragment(fragment, resName, model="scratch", position=None):
    """place a Fragment (see Fragment.py)

	   'resName' is the name of the new residue that will contain the
	   fragment.  (It will be in the 'het' chain.)

	   'model' can either be a chimera.Molecule instance or a string.
	   If the latter, then a new model is created with the string as
	   its .name attribute.

	   'position' can either be a chimera.Point or None.  If None, then
	   the fragment is positioned at the center of the view.
	"""

    if isinstance(model, basestring):
        model = _newModel(model)
    r = _newResidue(model, resName)
    needFocus = False
    if position is None:
        if len(chimera.openModels.list()) == 1:
            needFocus = True
        xf = model.openState.xform
        position = xf.inverse().apply(Point(*chimera.viewer.camera.center))
    # find fragment center
    x = y = z = 0.0
    for element, xyz in fragment.atoms:
        x += xyz[0]
        y += xyz[1]
        z += xyz[2]
    numAtoms = len(fragment.atoms)
    fragCenter = Point(x / numAtoms, y / numAtoms, z / numAtoms)
    correction = position - fragCenter

    from chimera.molEdit import addAtom, genAtomName
    atoms = []
    for element, xyz in fragment.atoms:
        atoms.append(
            addAtom(genAtomName(element, r), Element(element), r,
                    Point(*xyz) + correction))
    for indices, depict in fragment.bonds:
        r.molecule.newBond(atoms[indices[0]], atoms[indices[1]])
    if needFocus:
        chimera.runCommand("focus")
    return r
Ejemplo n.º 44
0
    def answer(self, msg):
        """execute a single command and return values"""
        ChimeraServer.answer(msg)
        if msg == "hk_icosahedron_lattice":
            from IcosahedralCage import cages

            h, k, radius, shellRadius, spheRadius, sym, sphere, color = self.vol_conn.recv()
            ###
            # get vertexes of canonical triangle (20 per icosahedron)
            # get triangles defined by h k for canonical triangle
            corners, triangles, t_hex_edges = cages.hk_triangle(h, k)

            # get vertex for icosahedron
            # get vertex for each face
            from Icosahedron import icosahedron_geometry

            ivarray, itarray = icosahedron_geometry(sym)

            tlist = []
            # for a single face
            # map triangles to a single face in the given orientation
            for i0, i1, i2 in itarray:
                face = ivarray[i0], ivarray[i1], ivarray[i2]
                tmap = cages.triangle_map(corners, face)
                tlist.extend(cages.map_triangles(tmap, triangles))
                break  #!!!!!!!!!!!!!!!!!!!!!!!!!
            va, ta = cages.surface_geometry(tlist, tolerance=1e-5)

            from numpy import multiply

            multiply(va, shellRadius, va)  # Scale to requested radius            for point in va:
            for point in va:
                command = "shape sphere radius %s center %s,%s,%s color %s " % (
                    spheRadius,
                    point[0],
                    point[1],
                    point[2],
                    color,
                )
                runCommand(command)
            self.vol_conn.send("axis")
            self.vol_conn.send(va)  # send serialized motion
Ejemplo n.º 45
0
	def test():
		import chimera
		import AddH

		m0, m1 = chimera.openModels.open("testdata/1dmo.pdb")
		#m0, m1 = chimera.openModels.open("/mol/pdb/mt/pdb1mtx.ent")[:2]
		minimize = True
		if minimize:
			AddH.simpleAddHydrogens([m0, m1])

		m0.color = chimera.Color.lookup("red")
		m1.color = chimera.Color.lookup("green")
		chimera.runCommand("~disp ; ribbon; ribrepr sharp")

		mm = MolecularMotion(m0, minimize=minimize)
		mm.interpolate(m1)
		mm.interpolate(m0)

		from util import runMovie
		runMovie(mm.trajectory())
Ejemplo n.º 46
0
 def openVolume(self):
     try:
         while True:
             if self.remote_conn.poll():
                 
                 msg = self.remote_conn.recv()
                 #print msg
                 if msg == 'open_volume':
                     data = self.remote_conn.recv()
                     print data
                     grid = Array_Grid_Data(data)
                     self.volume = volume_from_grid_data(grid)
                     #runCommand("volume #0 step 1")
                     
                 elif msg == 'voxelSize':
                     voxelSize = self.remote_conn.recv()
                     cmd = "volume #0 voxelSize %s"%voxelSize
                     runCommand(cmd)
                     runCommand("focus")
                 
                 elif msg == 'draw_angular_distribution':
                     angulardist = self.remote_conn.recv()
                     for command in angulardist:
                         runCommand(command)
                 
                 elif msg == 'end':    
                     break
                 else:
                     sleep(0.01)
     except EOFError:
         print 'Lost connection to client'
Ejemplo n.º 47
0
 def disp2D(self):
     # print 1
     self.fig1 = Figure(figsize=(4,4))    
     self.ax1 = self.fig1.add_subplot(111)
     pt = geo.proj_sphere(self.ax.elev,self.ax.azim,self.p)
     pt1 = geo.proj_sphere(self.ax.elev,self.ax.azim,self.p1)
     #print self.ax.azim, self.ax.elev
     # aa = pt[:,0]
     #print aa.ndim
     #print aa.shape
     self.ax1.scatter(pt[:,0],pt[:,1],marker = 'o',c="goldenrod")
     self.ax1.scatter(pt1[:,0],pt1[:,1],marker = '+',c="red")
     self.canvas1 = FigureCanvasTkAgg(self.fig1, master=self.frame)
     self.canvas1.get_tk_widget().grid(column=0,row=1)
     #self.canvas2 = Tkinter.Canvas(self.frame,width=4,height=4)
     #self.canvas2.configure(cursor="crosshair")
     #self.canvas2.grid(column=0,row=1)
     #self.canvas2.bind("<Button-1>", self.point)
     cid1 = self.canvas1.mpl_connect('button_press_event', self.onclick1)
     chimera.runCommand('turn x %f'%self.ax.azim)
     print 'elev = %f, azim=%f,'%(self.ax.elev,self.ax.azim)
     return
Ejemplo n.º 48
0
  def record(self, fmin, fmax, fstep, f_changed_cb, roundtrip, save_movie_cb):

    if self.recording:
      return

    self.f = self.fmin = fmin
    self.fmax = fmax
    self.fstep = fstep
    self.f_changed_cb = f_changed_cb
    self.save_movie_cb = save_movie_cb
    
    self.recording = True

    from math import ceil
    steps = int(ceil((fmax - fmin) / fstep))
    if roundtrip:
      steps *= 2

    from chimera import runCommand
    runCommand('movie record')

    self.play(fmin, fmin, fmax, fstep, f_changed_cb, 1, steps)
Ejemplo n.º 49
0
 def main(self):
     # prepare figure, frame, canvas
     self.fig = plt.figure(figsize=(4,4))
     self.frame = Tkinter.Frame(self)
     self.frame.grid(padx=10,pady=10)
     self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame)
     self.canvas.get_tk_widget().grid(column=0,row=0)
     # define 3D interactive plot
     self.ax = Axes3D(self.fig)
     # display 3D model on chimera's main window
     opened = chimera.openModels.open('class2_run10k_ct24_it031_class001.mrc')
     tt=chimera.runCommand('volume #0 level 0.02 color pink')
     # button widget to show the chosen angle
     self.btn = Tkinter.Button(self,text=u'Chosen angle',command=self.disp2D)        
     self.btn.grid(column=0,row=2,sticky='EW')
     cid = self.fig.canvas.mpl_connect('button_press_event', self.onclick)
     # button widget for computing chronos and topos
     self.btn = Tkinter.Button(self,text=u'Calculate Topos and Chronos now',command=self.disp2D)        
     self.btn.grid(column=0,row=3,sticky='EW')
     cid = self.fig.canvas.mpl_connect('button_press_event', self.onclick)
     # generate some fake data points
     ss = 100
     tt = 50
     phi = np.ones((ss,1))
     theta = np.ones((ss,1))
     for i in range(phi.shape[0]):
         phi[i] = random.uniform(0,2*np.pi)
         theta[i] = random.uniform(0,np.pi)
     phi1 = np.array([[0],[np.pi/2],[np.pi/20]])
     theta1 = np.array([[0],[np.pi/2],[np.pi/20]])
     phi1 = npm.repmat(phi1,tt,1)
     theta1 = npm.repmat(theta1,tt,1)
     self.p = geo.euler_to_vect(theta, phi)
     self.p1 = geo.euler_to_vect(theta1, phi1)
     self.points=[]
     # display data points on the unit sphere
     self.ax.view_init(elev=0, azim=90)
     t = self.ax.scatter(self.p[:,0], self.p[:,1], self.p[:,2],  marker='o', s=10, c="goldenrod", alpha=0.6)
     t = self.ax.scatter(self.p1[:,0],self.p1[:,1],self.p1[:,2], marker='+', s=10, c="red", alpha=0.6)
     # display data points that are in the front view
     self.disp2D()
     #
     self.canvas2 = Tkinter.Canvas(self.frame,bg="white", width=4,height=4)
     self.canvas2.configure(cursor="crosshair")
     self.canvas2.grid(column=0,row=1)
     self.canvas2.bind('<Button-1>', self.point)
Ejemplo n.º 50
0
    def answer(self, msg):
        # print msg
        if msg == "open_volume":
            data = self.vol_conn.recv()  # objects are serialized by default
            # print data
            grid = Array_Grid_Data(data)
            self.volume = volume_from_grid_data(grid)
            self.centerVolume()

        elif msg == "voxel_size":
            self.voxelSize = self.vol_conn.recv()
            cmd = "volume #0 voxelSize %s" % self.voxelSize
            # print cmd
            runCommand(cmd)
            runCommand("focus")
            # end debug

        elif msg == "command_list":
            commandList = self.vol_conn.recv()
            for command in commandList:
                runCommand(command)
Ejemplo n.º 51
0
def makeAllMeshes(proID, jobID, peptideLen=40, pocketDist=5.0):

    global curResID
    global curProID
    global meshDir
    global pocketMap
    global resCount
    global curJobID
    
    #Insure input is a 4 character protein ID
    proID = proID[0:4]

    #Create a new directory for the protein
    meshDir = proID + 'Mesh'
    curProID = proID
    curJobID = jobID
   # os.mkdir(meshDir)
   # os.system("chmod 777 " + meshDir)  
    
    try:
        #Fetch protein from the PDB
        runCommand('open '+ proID)

        #Initial prep for pocket search
        runCommand('delete solvent')
        runCommand('delete :HOH')

        #Open protein model
        model = openModels.list(modelTypes=[Molecule])[0]
        RES_LIST = model.residues
        resCount = len(RES_LIST)

        #Pocket finding procedure
        chains = []
        counts = []
        index = 0
        print 'Counting Chain Lengths................'
        for res in RES_LIST:
            curChain = str(res.id.chainId)
            if len(chains) == 0:
                chains.append(curChain)
                counts.append(1)
            if curChain != chains[index]:
                index = index + 1
                chains.append(curChain)
                counts.append(1)
            else:
                counts[index] = counts[index] + 1
        
        print 'Finding Peptide Ligand Pockets................'
        for i, chain in enumerate(chains):
            if counts[i] < peptideLen:                           #Less than X amino acids = peptide
                runCommand('~select')
                runCommand('select ligand & :.' + chain)                #Check if actually ligand
                runCommand('select selected zr<' + str(pocketDist))     #Select pocket
                runCommand('~select :/isHet zr<' + str(pocketDist))     #De-select ligand
                runCommand('~select ligand')
                residues = selection.currentResidues()   #Store pocket in memory
                for res in residues:                      
                    if res in pocketMap:
                        pocketMap[res].append('|' + chain) 
                    else:
                        pocketMap[res] = [chain]
        print 'Finding non-Peptide Ligand Pockets................'
        for res in RES_LIST:

            if res.isHet:                                #Check if "heterogenous residue" which includes ligands
                 curResID = str(res.id)
                 runCommand('~select')
                 runCommand('select :' + curResID + ' & ligand')          #Check if actually ligand
                 runCommand('select selected zr<' + str(pocketDist))      #Select pocket
                 runCommand('~select :' + curResID)
                 residues = selection.currentResidues()                   #Store pocket in memory
                 for pocketRes in residues:
                     if pocketRes in pocketMap:
                        pocketMap[pocketRes].append('|' + res.type + '-' + curResID) 
                     else:
                        pocketMap[pocketRes] = [res.type + '-' + curResID] 

        print 'Dock Prep................'
        
        prep(openModels.list(modelTypes=[Molecule]))
        runCommand('delete ligand')
        print '\nRunning Delphi................'
        runCommand('~select')
        runCommand('write format pdb 0 '+ proID + curJobID + '.pdb')  #Write delphi-ready protein with hydrogens
        
        #Create delphi parameter file
        f = open('./param_' + curJobID, 'w')
        f.write('in(pdb,file="'+ proID + curJobID + '.pdb")\n')       #Input/Output files
        f.write('in(siz,file="amber.siz")\n')
        f.write('in(crg,file="amber.crg")\n')
        f.write('out(phi,file="'+ proID + curJobID + '.phi")\n')
        f.write('indi=2\n')                                 #Interior dielectric constant 
        f.write('exdi=80.0\n')                              #Exterior dielectric constant (water)
        f.write('prbrad=1.4\n')
        f.write('salt=0.15\n')                              #Salt concentration and radius
        f.write('ionrad=2.0\n')                             
      #  f.write('nonit=20\n')                               #Non-linear iterations
        f.close()
        os.system("./DELPHI_2004_LINUX_v2/delphi_static param_" + curJobID)      #Run delphi

       # print '\nExporting Mesh................'
        runCommand('select #0')
        runCommand('surface')
        #runCommand('export format X3D ./' + proID + '.x3d') # Prints raw X3D file. 
        
        print '\nOpening Delphi Data................'
        runCommand('open '+ proID + curJobID + '.phi')
        runCommand('scolor #0 volume #1 cmap -1,red:0,white:1,blue;')
        
        print '\nRemoving Temp Files................'
        os.remove("./" + proID + curJobID + '.pdb')
        os.remove("./" + proID + curJobID + '.phi')
        os.remove('./param_' + curJobID)
        print '\nDONE: ' + proID
    except:
        f = open("./" + 'ErrorLog' + curJobID + '.txt', 'w')
        f.write(proID + ' error: ' + str(sys.exc_info()[0]) + str(sys.exc_info()[1]) + '\n')
        f.close()
        raise
Ejemplo n.º 52
0
import optparse
parser = optparse.OptionParser()
parser.add_option('--pqr_in', default=None, help='Input PQR file')
parser.add_option('--mol2_out', default=None, help='Output mol2 file')
(args, options) = parser.parse_args()

import os
if not os.path.exists(args.pqr_in):
  raise Exception(args.pqr_in+' does not exist')

print 'Converting '+args.pqr_in+' to '+args.mol2_out

import chimera
chimera.openModels.open(args.pqr_in)

# Molecular surface
chimera.runCommand("addh")
chimera.runCommand("addcharge")
chimera.runCommand("write format mol2 0 "+args.mol2_out)
Ejemplo n.º 53
0
	def updateCoords(self, mi):
		import chimera
		assert(self._mi is mi)
		self._mi.saveMMTKCoordinates()
		chimera.runCommand("wait 1")
Ejemplo n.º 54
0
# Issue this command inside Chimera
# 2dlabels create timer text "0 ns" color white ypos .9 xpos .9 size 50

# Issue this per-frame script
from chimera import runCommand
runCommand("2dlabels change timer text '%.1f ns'" % (mdInfo['frame']*0.02))
Ejemplo n.º 55
0
from chimera import runCommand
from chimera import openModels, Molecule
from os import chdir, listdir
import chimera
from WriteMol2 import writeMol2
import sys

        
file = open("com.txt")
for line in file:
	if line.find("centroid has center") != -1:
		#print "OPENED:%s" % line
		word = line.split()
		#print word
		x = float(word[3])
		y = float(word[4])
		z = float(word[5]) + 16
center = Point(x, y, z)
runCommand("open " + sys.argv[1])
model0 = openModels.list(id=0, modelTypes=[Molecule])[0]
c = BuildStructure.placeHelium('com', model=model0, position=center)
runCommand("select He")
runCommand("namesel helium")
runCommand("select helium za>10")
runCommand("del sel")
runCommand("del helium")
writeMol2(chimera.openModels.list(modelTypes=[chimera.Molecule]), sys.argv[1][:-4] + ".mol2")
runCommand("close all")


Ejemplo n.º 56
0
# run with 
## chimera --nogui olfr1392_1u19_noH.pdb writedms.py
## chimera --nogui pdb:3D7F_withoutLigand writedms.py 
# chimera --nogui Q9I8C1_27_noH.pdb writedms.py 
# where this py file is named writedms.py
# it would run chimera without gui on the file 3D7F_withoutLigand.pdb  
# and it would output to a file called 3D7F_without_ligand.dms

from chimera import runCommand, openModels, MSMSModel
# generate surface using 'surf' command
runCommand("surf")
# get the surf object
surf = openModels.list(modelTypes=[MSMSModel])[0]
# write DMS
from WriteDMS import writeDMS
#writeDMS(surf, "3D7F_rec_noH.dms")
#writeDMS(surf, "olfr1392_1u19_noH.dms")
#writeDMS(surf, "Q9I8C1_27_aligned_noH.dms")
writeDMS(surf, "rec.dms")

Ejemplo n.º 57
0
import optparse
parser = optparse.OptionParser()
parser.add_option('--pdb_in', default=None, help='Input PDB file')
parser.add_option('--dms_out', default=None, help='Output dms file')
(args, options) = parser.parse_args()

import os
if not os.path.exists(args.pdb_in):
  raise Exception(args.pdb_in+' does not exist')

print 'Processing '+args.pdb_in

import chimera
chimera.openModels.open(args.pdb_in)

# Molecular surface
from chimera import runCommand, openModels, MSMSModel
chimera.runCommand("surf") # generate surface using 'surf' command
surf = openModels.list(modelTypes=[MSMSModel])[0] # get the surf object
from WriteDMS import writeDMS
writeDMS(surf, args.dms_out) # write DMS