Ejemplo n.º 1
0
def process_molecule_mae(file_header, mol, suspend_undo):
    global already_processed
    global undo_each_molecule
    tot = []
    tot.extend(file_header)
    tot.extend(mol)
    molstr = string.join(tot,'')

    nameorig, mdl = read_mae_model(molstr)
    name = nameorig.strip()
    if name in already_processed:
        return True
    already_processed = set(already_processed | set([name]))
    tmpname = "_temp_%s" % name
    cmd.delete(tmpname)

    try:
        cmd.load_model(mdl, tmpname)
        natoms = cmd.count_atoms(tmpname)
    except:
        return False
    if undo_each_molecule:
        cmd.push_undo( "( %s )" % name, just_coordinates=0)
        cmd.set("suspend_undo", 1, updates=0)
    cmd.remove(name)
    cmd.create(name, tmpname, copy_properties=True)
    cmd.set_title(name, -1, "")

    cmd.delete(tmpname)
    if undo_each_molecule:
        cmd.set("suspend_undo", suspend_undo, updates=0)
        cmd.push_undo("", just_coordinates=0, finish_undo=1)
    return True
Ejemplo n.º 2
0
def load_json(file_name, object='', state=0):
    from json import load
    # print('loading ' + file_name)

    if state < -1:
        print('incorrect state')
        return

    with open(file_name, 'r') as fp:
        try:
            molecule = load(fp)
            model = gen_model(molecule)

        except ValueError:
            print('the file seems to be not of JSON type')

        except LookupError:
            print('the file is formatted incorrectly')

        except Exception as e:
            print(str(e.__class__) + ' while creating model')

        if object:
            object_name = object
        else:
            object_name = os.path.basename(file_name).rsplit(
                '.', 1)[0]  # names may have dots

        cmd.load_model(model, object_name, state)
Ejemplo n.º 3
0
def _do_it(path):
    fh = RMF.open_rmf_file_read_only(path)
    mf = RMF.Molecule(fh)
    cf = RMF.ChainFactory(fh)

    res = RMF.get_resolutions(fh.get_root_node(), RMF.PARTICLE, .1)
    if len(res) == 1:
        res = [-1]
    fh.set_current_frame(RMF.FrameID(0))
    diameter = RMF.get_diameter(fh.get_root_node())
    mydata = MyData(fh, diameter)
    for f in fh.get_frames():
        created = {}
        fh.set_current_frame(f)
        for r in res:
            _create_molecules(
                fh.get_root_node(),
                mf,
                cf,
                mydata,
                r,
                created)
            if len(created) == 0:
                # fall back
                _create_molecule(fh.get_root_node(), mydata, r, created)
        for c in created:
            cmd.load_model(created[c][1], c, f.get_index() + 1)
Ejemplo n.º 4
0
def mini(total_steps=500,
            gradient=0.001,
            interval=100,
            object='rt',
            fix_flag=None,
            rest_flag=None,
            solvation=None,
            finish=None):

    global state
    if not state:
        print(" realtime.mini: please run setup first...")
    else:
        model = state.model
        print(" realtime.mini: %d atoms total\n" % model.nAtom)
        try:
            while total_steps>0:
                total_steps = total_steps - interval
                state.minimize(max_iter=interval,
                                    fix_flag=fix_flag,
                                    rest_flag=rest_flag,
                                    solvation=solvation)
                cmd.delete(object)
                cmd.load_model(state.model,object,1)
                cmd.refresh()
                if finish is not None:
                    finish[0](*finish[1], **finish[2])
        except:
            cmd.load_model(state.model,'ref')
            traceback.print_exc()
        print(" realtime.mini: complete.")
Ejemplo n.º 5
0
def mini(total_steps=500,
            gradient=0.001,
            interval=100,
            object='rt',
            fix_flag=None,
            rest_flag=None,
            solvation=None,
            finish=None):

    global state
    if not state:
        print " realtime.mini: please run setup first..."
    else:
        model = state.model
        print " realtime.mini: %d atoms total\n" % model.nAtom
        try:
            while total_steps>0:
                total_steps = total_steps - interval
                state.minimize(max_iter=interval,
                                    fix_flag=fix_flag,
                                    rest_flag=rest_flag,
                                    solvation=solvation)
                cmd.delete(object)
                cmd.load_model(state.model,object,1)
                cmd.refresh()
                if finish!=None:
                    apply(finish[0],finish[1],finish[2])
        except:
            cmd.load_model(state.model,'ref')
            traceback.print_exc()
        print " realtime.mini: complete."
Ejemplo n.º 6
0
	def revert(self):
		v = cmd.get_view()
		cmd.remove(self.rdes.obj+" and not chain A")
		m = cmd.get_model(self.rdes.obj)
		n = self.oldcrd
		if not n:
			cmd.create("tmp12345",self.rnat.sel())
			cmd.align("tmp12345",self.rdes.sel())
			n = cmd.get_model("tmp12345").atom
			cmd.delete("tmp12345")
		di,ni = 0,0
		while m.atom[di].resi != str(self.rdes.resi): di += 1
		dj = di
		while m.atom[dj].resi == str(self.rdes.resi): dj += 1
		if self.oldcrd: self.oldcrd = None
		else:           self.oldcrd = m.atom[di:dj]
		m.atom = m.atom[:di] + n + m.atom[dj:]
		for i in range(di,di+len(n)):
			m.atom[i].resi  = str(self.rdes.resi)
			m.atom[i].chain = str(self.rdes.chain)
		cmd.load_model(m,self.rdes.obj,1)
		cmd.save("tmp.pdb",self.rdes.obj)
		cmd.delete(self.rdes.obj)
		cmd.load("tmp.pdb",self.rdes.obj,1)
		cmd.show('car',self.rdes.obj)
		cmd.show('lines')		
		redopent(self.rdes.obj)
		cmd.set_view(v)
		print "revert removing "+"".join(self.aas)+" from aas!"
		self.aas = [getaa('A',self.rdes.resi,self.manager.d.obj)]
Ejemplo n.º 7
0
def create_spheres(name, spheres, links, frame):

	cmd.delete(name)
	model = Indexed()
	for i in (range(len(spheres) / 4)):
		ai = i * 4
		r = spheres[ai + 3]
		cluster = int(name[7:10])
		if r <> 0.5:
			a=Atom()
			a.name = "X" + str(i)
			a.resi = str(cluster)
			a.vdw = spheres[ai + 3]
			a.coord = [spheres[ai], spheres[ai + 1], spheres[ai + 2]]
			model.atom.append(a)

	for i in (range(len(links) / 2)):
		li = i * 2
		a1 = links[li]
		a2 = links[li + 1]
		create_bond(model, a1, a2)

	cmd.load_model(model, name,frame)
	cmd.hide("lines", name)
	cmd.show("spheres", name)
Ejemplo n.º 8
0
def jsoner(sel):
	lens=[]
	states=[]
	q1=cmd.get_model(sel)
	lens.append(len(q1.atom))
	states.append(1)
	proc = Popen("goreduce", shell=True, stdin=PIPE, stdout=PIPE)
	options=json.dumps({"SelNames":[sel],"AtomsPerSel":lens,"StatesPerSel":states})  #, "IntOptions":[[5, 11]] })
	proc.stdin.write(options+"\n")
	for i in q1.atom:
		atom,coords=gochem.Atom2gcRef(i)
		proc.stdin.write(atom+"\n")
		proc.stdin.write(coords+"\n")
	proc.stdin.close()
#	if  proc.wait() != 1:
#		print "There were some errors"
#	for j in proc.stderr:
#		print(json.loads(j))
#	proc.stderr.close()	
#	for i in proc.stdout:
#		print json.loads(i)
	info = gochem.get_info(proc)
	mod=gochem.get_model(proc,info,0)

	cmd.load_model(mod,sel+"_Htmp",discrete=1,zoom=1)
	modR=cmd.get_pdbstr(sel+"_Htmp")
	cmd.read_pdbstr(modR,sel+"_H")
	cmd.delete(sel+"_Htmp")
	print "Jumalauta y wea"
Ejemplo n.º 9
0
def extend_peptide(model):
    objname = '__tmp{}'.format(random.randint(0, 100000))
    minresi = min([a.resi_number for a in model.atom])
    maxresi = max([a.resi_number for a in model.atom])

    def is_beta_residue(model, r):
        resn = getAtom(model, resi_number=r, name='N').resn
        return resn.startswith('B2') or resn.startswith('B3')

    # first planarize the atoms around C and N in the peptide bonds.
    for r in range(minresi, maxresi + 1):
        # now align the oxygens: CA, C, O and N must be planar
        planarize_peptide_bond(model, (r, 'C'), (r, 'CA'), (r + 1, 'N'),
                               (r, 'O'))
        if is_beta_residue(model, r):
            # align the hydrogens: N, CB, C and H must be planar
            planarize_peptide_bond(model, (r, 'N'), (r, 'CB'), (r - 1, 'C'),
                                   (r, 'H'))
            # try it with CB1
            planarize_peptide_bond(model, (r, 'N'), (r, 'CB1'), (r - 1, 'C'),
                                   (r, 'H'))
        else:
            planarize_peptide_bond(model, (r, 'N'), (r, 'CA'), (r - 1, 'C'),
                                   (r, 'H'))
    cmd.delete(objname)
    cmd.load_model(model, objname)
    # set all torsions to straight
    for r in range(minresi, maxresi + 1):
        # planarize the peptide bond
        # print('Setting dihedrals of residue #{}'.format(r))
        set_dihedral(objname, ('O', r - 1), ('C', r - 1), ('N', r), ('H', r),
                     180)
        if is_beta_residue(model, r):
            # the "phi" torsion angle
            # print('This is a beta residue')
            set_dihedral(objname, ('H', r), ('N', r), ('CB+CB1', r), ('CA', r),
                         0)
            # the "theta" torsion angle
            set_dihedral(objname, ('N', r), ('CB+CB1', r), ('CA', r), ('C', r),
                         180)
            # the "psi" torsion angle
            set_dihedral(objname, ('CB+CB1', r), ('CA', r), ('C', r), ('O', r),
                         0)
        else:
            #            print('This is an alpha residue')
            # the "phi" dihedral
            set_dihedral(objname, ('H', r), ('N', r), ('CA', r), ('C', r), 0)
            # the "psi" dihedral
            set_dihedral(objname, ('N', r), ('CA', r), ('C', r), ('O', r), 0)
        # fix the hydrogens
        for atom in ['CA', 'CB', 'CB1']:
            if cmd.count_atoms('model {} and resi {} and name {}'.format(
                    objname, r, atom)) == 1:
                cmd.h_fix('model {} and resi {} and name {}'.format(
                    objname, r, atom))
        cmd.unpick()
    model = cmd.get_model(objname)
    cmd.delete(objname)
    return model
Ejemplo n.º 10
0
def addHydrogens(model):
    objname = '__tmp{}'.format(random.randint(0, 100000))
    cmd.delete(objname)
    cmd.load_model(model, objname)
    cmd.h_add('model {}'.format(objname))
    model = cmd.get_model(objname)
    cmd.delete(objname)
    return model
Ejemplo n.º 11
0
def mirror(sel, nname):
    cmd.delete(nname)
    a = [Vec(x.coord) for x in cmd.get_model(sel).atom]
    #print max(d), argmax(d), cmd.get_model("179L").atom[argmax(d)].resi
    #print min(d)
    cmd.create(nname, sel)
    m = cmd.get_model(sel)
    for j in range(len(m.atom)):
        m.atom[j].coord[0] *= -1
    cmd.load_model(m, nname, 1)
Ejemplo n.º 12
0
 def update(self, configuration=None):
     try:
         cmd.set("suspend_updates", "1")
         self._setCoordinates(configuration)
         cmd.load_model(self.model, self.name, 1)
     except:
         cmd.set("suspend_updates", "0")
         traceback.print_exc()
     cmd.set("suspend_updates", "0")
     cmd.refresh()
Ejemplo n.º 13
0
 def update(self, configuration=None):
     try:
         cmd.set("suspend_updates","1")
         self._setCoordinates(configuration)
         cmd.load_model(self.model, self.name, 1)
     except:
         cmd.set("suspend_updates","0")
         traceback.print_exc()
     cmd.set("suspend_updates","0")
     cmd.refresh()
Ejemplo n.º 14
0
def mirror(sel, nname="mirror", crd=0):
    cmd.delete(nname)
    a = [Vec(x.coord) for x in cmd.get_model(sel).atom]
    # print max(d), argmax(d), cmd.get_model("179L").atom[argmax(d)].resi
    # print min(d)
    cmd.create(nname, sel)
    m = cmd.get_model(sel)
    for j in range(len(m.atom)):
        m.atom[j].coord[crd] *= -1
    cmd.load_model(m, nname, 1)
Ejemplo n.º 15
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     cmd.delete('model {}'.format(self._modelname))
     cmd.load_model(self._model, self._modelname)
     # read back model for control
     self._model = cmd.get_model('model {}'.format(self._modelname))
     logger.debug('Putting back model {}, containing {} atoms:'.format(
         self._modelname, len(self._model.atom)))
     for at in self._model.atom:
         logger.debug('   Name: {}\tResi: {}\tResn:{}'.format(
             at.name, at.resi_number, at.resn))
     self._model = None
Ejemplo n.º 16
0
 def movie(self, configurations):
     n = 1
     cmd.feedback("disable", "executive", "actions")
     auto_zoom = cmd.get("auto_zoom")
     cmd.set("auto_zoom", 0)
     for conf in configurations:
         self._setCoordinates(conf)
         cmd.load_model(self.model, self.name, n)
         n = n + 1
     cmd.set("auto_zoom", auto_zoom)
     cmd.feedback("enable", "executive", "actions")
     cmd.mplay()
Ejemplo n.º 17
0
def check(obj='check'):
    global state
    global model

    if not state:
        if not model:
            print(" realtime.reload: please run setup first.")
        else:
            cmd.load_model(model,obj,1)
    else:
        model = state.model
        cmd.load_model(model,obj,1)
Ejemplo n.º 18
0
def check(obj="check"):
    global state
    global model

    if not state:
        if not model:
            print " realtime.reload: please run setup first."
        else:
            cmd.load_model(model, obj, 1)
    else:
        model = state.model
        cmd.load_model(model, obj, 1)
Ejemplo n.º 19
0
 def movie(self, configurations):
     n = 1
     cmd.feedback("disable","executive","actions")
     auto_zoom = cmd.get("auto_zoom")
     cmd.set("auto_zoom", 0)
     for conf in configurations:
         self._setCoordinates(conf)
         cmd.load_model(self.model, self.name, n)
         n = n + 1
     cmd.set("auto_zoom", auto_zoom)
     cmd.feedback("enable","executive","actions")
     cmd.mplay()
Ejemplo n.º 20
0
def inversion(sel, nname="inv"):
    cmd.delete(nname)
    a = [Vec(x.coord) for x in cmd.get_model(sel).atom]
    # print max(d), argmax(d), cmd.get_model("179L").atom[argmax(d)].resi
    # print min(d)
    cmd.create(nname, sel)
    m = cmd.get_model(sel)
    for j in range(len(m.atom)):
        m.atom[j].coord[0] *= -1
        m.atom[j].coord[1] *= -1
        m.atom[j].coord[2] *= -1
    cmd.load_model(m, nname, 1)
Ejemplo n.º 21
0
def LoadNew(model, name, template=None, PDBstr=False, state=0, discrete=0):
    if PDBstr:
        tmpname = name + "_tmp"
        cmd.load_model(model, tmpname, discrete=discrete, zoom=1)
        modR = cmd.get_pdbstr(tmpname)
        cmd.read_pdbstr(modR, name)
        cmd.delete(tmpname)
        return
    if template:
        model.bond = template.bond
    else:
        add_bonds(model)
    cmd.load_model(model, name, state=state, discrete=discrete)
Ejemplo n.º 22
0
def genAV(obstacles, attachment, linker_length=20.0, linker_diameter=2.0, dye_radius=3.5, disc_step=0.9, name=None, state=1, stripsc=True, allowed_sphere_radius=0.0, smoothSurf=True):

  source = np.array(cmd.get_model(attachment, state).get_coord_list())
  if (source.shape[0]!=1):
    print('attachment selection must contain exactly one atom, selected: {}'.format(source.shape[0]))
    return
  source=source.reshape(3)

  srcAt = cmd.get_model(attachment, state).atom[0]
  srcModelName = cmd.get_names('objects',0,attachment)[0]

  obstacles = '(' + obstacles + ') and not (' + attachment + ')'
  if stripsc and isAA(srcAt.resn):
    obstacles += ' and not (' + srcModelName
    if len(srcAt.chain)>0:
      obstacles += ' and chain ' + srcAt.chain
    obstacles+=' and resi '+srcAt.resi+' and sidechain'+')'
  if allowed_sphere_radius > 0.0:
    obstacles+=' and not (({}) around {})'.format(attachment, allowed_sphere_radius)

  xyzRT=np.zeros((1,4))
  nAtoms=cmd.count_atoms(obstacles)
  if nAtoms>0:
    atoms=cmd.get_model(obstacles, state).atom
    nAtoms=len(atoms)
    xyzRT=np.zeros((nAtoms,4))
    for i,at in enumerate(atoms):
      xyzRT[i]=[at.coord[0],at.coord[1],at.coord[2],at.vdw]

  av1=ll.dyeDensityAV1(xyzRT.T,source,linker_length, linker_diameter, dye_radius, disc_step)
  m=avToModel(av1)
  if len(m.atom)==0:
    print('Failed: Empty AV. Is attachment position buried?')
    return
  if name is None:
    name = srcModelName + '_'
    if len(srcAt.chain)>0:
      name += srcAt.chain + '-'
    name +=  srcAt.resi + '-' + srcAt.name
  cmd.load_model(m, name)

  if smoothSurf:
    surfName=name+'_surf'
    mapName=name+'_map'
    gRes=cmd.get('gaussian_resolution')
    cmd.set('gaussian_resolution',3.0)
    cmd.map_new(mapName,'gaussian', 1.0, name, 6)
    cmd.isosurface(surfName,mapName,0.9)
    cmd.set('gaussian_resolution',gRes)
    cmd.disable(name)
Ejemplo n.º 23
0
def load_crd(filename, object=''):
    """
        Load a fDynamo coordinates file (.crd)

        Parameters
        ----------
        filename : str
            file path
        object : str, optional
            name of the object (def: filename prefix)
    """

    if not object:
        object = "".join(os.path.basename(filename).rpartition('.')[:-2])

    # read file as list of strings
    with open(filename, "rt") as f:
        crd_file = f.readlines()
        # remove comment lines, trailing comments and space split
        crd_file = [
            line.split("!")[0].split() for line in crd_file
            if line.strip() and not line.startswith("!")
        ]

    # reversed dictionary of atomic numbers to elements
    atomic_number_inv = {n: elem for elem, n in atomic_number.items()}

    # create new model and append crd's atoms
    model = Indexed()
    a = Atom()
    a.hetatm = False
    for line in crd_file:
        if line[0].lower() == "subsystem":
            a.segi = str(line[2])
        elif line[0].lower() == "residue":
            a.resi_number = int(line[1])
            a.resn = str(line[2])
        elif len(line) != 6:
            continue
        else:
            a.name = str(line[1])
            a.symbol = atomic_number_inv[int(line[2])]
            a.coord = (float(line[3]), float(line[4]), float(line[5]))
            model.add_atom(deepcopy(a))
    model.update_index()
    cmd.load_model(model, object)
    cmd.rebond(object)
    cmd.dss(object)

    print(f" pyDYNAMON: \"{filename}\" loaded as \"{object}\"")
Ejemplo n.º 24
0
def meancoords(sel1, sel2, n="mix", w=0.5):
    cmd.delete(n)
    a = [Vec(x.coord) for x in cmd.get_model(sel1).atom]
    b = [Vec(x.coord) for x in cmd.get_model(sel2).atom]
    d = [(a[i] - b[i]).length() for i in range(len(a))]
    #print max(d), argmax(d), cmd.get_model("179L").atom[argmax(d)].resi
    #print min(d)
    cmd.create(n, sel1)
    m = cmd.get_model(sel1)
    for j in range(len(m.atom)):
        m.atom[j].coord[0] = w * b[j].x + (1.0 - w) * a[j].x
        m.atom[j].coord[1] = w * b[j].y + (1.0 - w) * a[j].y
        m.atom[j].coord[2] = w * b[j].z + (1.0 - w) * a[j].z
    cmd.load_model(m, n, 1)
Ejemplo n.º 25
0
def meancoords(sel1, sel2, n="mix", w=0.5):
    cmd.delete(n)
    a = [Vec(x.coord) for x in cmd.get_model(sel1).atom]
    b = [Vec(x.coord) for x in cmd.get_model(sel2).atom]
    d = [(a[i] - b[i]).length() for i in range(len(a))]
    # print max(d), argmax(d), cmd.get_model("179L").atom[argmax(d)].resi
    # print min(d)
    cmd.create(n, sel1)
    m = cmd.get_model(sel1)
    for j in range(len(m.atom)):
        m.atom[j].coord[0] = w * b[j].x + (1.0 - w) * a[j].x
        m.atom[j].coord[1] = w * b[j].y + (1.0 - w) * a[j].y
        m.atom[j].coord[2] = w * b[j].z + (1.0 - w) * a[j].z
    cmd.load_model(m, n, 1)
Ejemplo n.º 26
0
def goQM(selside="sele",selbb="",qmprogram="MOPAC2012",method="Cheap", calctype="Optimization",dielectric="-1", charge=0,multiplicity=1, alphacut=True,dryrun=False):
	lens=[]
	states=[]
	q1=[]
	side=False
	print selside ##################3
	if selside and not " " in selside:
		side=True
		m=cmd.get_model(selside)
		q1.append(m)
		lens.append(len(q1[0].atom))
		states.append(1)
	bb=selbb.split(",")
	for i in bb:
		if i=="":
			continue
		q1.append(cmd.get_model(i))
		lens.append(len(q1[-1].atom))
		states.append(1)
	if side:
		bb.insert(0,selside)
	proc = Popen("goqm", shell=True, stdin=PIPE,stdout=PIPE)
	options=json.dumps({"SelNames":bb,"AtomsPerSel":lens,"StatesPerSel":states,"IntOptions":[[int(charge),int(multiplicity)]],"FloatOptions":[[float(dielectric)]],"StringOptions":[[qmprogram,method, calctype]],"BoolOptions":[[side,alphacut,dryrun]]})
	print options ######
	print "side", side
	proc.stdin.write(options+"\n")
	for j in q1:
		for i in j.atom:
			atom,coords=gochem.Atom2gcRef(i)
			proc.stdin.write(atom+"\n")
			proc.stdin.write(coords+"\n")
	proc.stdin.close()
	if  proc.wait() != 0:
		print "There were some errors"
	if dryrun:
		return  #in a dry run there is nothing to receive. The input files should be in the current directory.
	info=gochem.get_info(proc)
	energy=info["Energies"][0]
	print "Final energy: ", energy, " kcal/mol"
	if calctype=="Optimization":
		for k,v in enumerate(q1):
			if k==0 and side:
				exclude=["CA","HA","HA2","HA3", "O","N","H","C"]
				idexclude=[]
			else:
				idexclude=[v.atom[0].resi,v.atom[-1].resi]
				exclude=["CTZ","NTZ","HCZ","HNZ"]
			mod=gochem.get_coords(proc,v,exclude,idexclude,False,info,k)
			cmd.load_model(mod,bb[k]+"_H",discrete=1,zoom=1)
Ejemplo n.º 27
0
def cap(object):
    from pymol import cmd
    
    model = cmd.get_model(object)
    # guarantee identical ordering
    cmd.delete(object)
    cmd.load_model(model,object)
    n_list = cmd.identify("(n;n &!(n;c a;2.0))")
    c_list = cmd.identify("(n;c &!(n;n a;2.0))")
    print n_list
    print c_list
    for a in n_list:
        newat = copy.deepcopy(model.atom[a])
        newat.coord = [
            newat.coord[0] + random.random(),
            newat.coord[1] + random.random(),
            newat.coord[2] + random.random(),
            ]
        newat.symbol = 'H'
        newat.name = 'HN'
        newat.numeric_type = 43
        bond = Bond()
        bond.order = 1
        bond.stereo = 0
        bond.index = [ a, model.nAtom ]
        print "adding",newat.name,bond.index
        model.add_atom(newat)
        model.add_bond(bond)
    for a in c_list:
        newat = copy.deepcopy(model.atom[a])
        newat.coord = [
            newat.coord[0] + random.random(),
            newat.coord[1] + random.random(),
            newat.coord[2] + random.random(),
            ]
        newat.symbol = 'H'
        newat.name = 'HC'
        newat.numeric_type = 41
        bond = Bond()
        bond.order = 1
        bond.stereo = 0
        bond.index = [ a, model.nAtom ]
        print "adding",newat.name,bond.index
        model.add_atom(newat)
        model.add_bond(bond)
    # reload
    cmd.delete(object)
    cmd.load_model(model,object)
    cmd.sort(object)
Ejemplo n.º 28
0
def avg(sel1, sel2, sel3, sel4):
    cmd.delete("avg")
    cmd.create("avg", sel1)
    m1 = cmd.get_model(sel1).atom
    m2 = cmd.get_model(sel2).atom
    m3 = cmd.get_model(sel3).atom
    m4 = cmd.get_model(sel4).atom
    m = cmd.get_model("avg")
    for i in range(len(m1)):
        m.atom[i].coord[0] = (m1[i].coord[0] + m2[i].coord[0] +
                              m3[i].coord[0] + m4[i].coord[0]) / 4.0
        m.atom[i].coord[1] = (m1[i].coord[1] + m2[i].coord[1] +
                              m3[i].coord[1] + m4[i].coord[1]) / 4.0
        m.atom[i].coord[2] = (m1[i].coord[2] + m2[i].coord[2] +
                              m3[i].coord[2] + m4[i].coord[2]) / 4.0
    cmd.load_model(m, "avg", 1)
Ejemplo n.º 29
0
    def make_channel(model, i, name=None):

        for a in range(len(model.atom) - 1):
            bd = Bond()
            bd.index = [a, a + 1]
            model.bond.append(bd)

        if name is None:
            name = "Tunnel" + str(i)

        cmd.load_model(model, name, state=1)
        cmd.set("sphere_mode", "0", name)
        cmd.set("sphere_color", "red", name)

        cmd.show("spheres", name)
        cmd.group("Tunnels", name)

        return Indexed()
Ejemplo n.º 30
0
    def test(self):
        from chempy import Atom, Bond, models

        m = models.Indexed()

        for i in range(2):
            a = Atom()
            a.coord = [float(i), 0., 0.]
            m.add_atom(a)

        b = Bond()
        b.index = [0, 1]
        b.order = 0
        m.add_bond(b)

        cmd.load_model(m, 'foo')

        cmd.set('valence')
        cmd.show('sticks')
Ejemplo n.º 31
0
def test_random():
    '''
    This is a simple test function which drops most coordinates from a
    polypeptide and tries to reposition them with simple_unknowns().

    Works fine to position hydrogens, fails to position other atoms.
    '''
    import random
    from pymol import cmd
    from chempy.champ import assign
    cmd.fab('ACDEFGHIKLMNPQRSTVWY', 'm0')
    assign.amber99()
    for i in xrange(100):
        m = cmd.get_model('m0').convert_to_connected()
        for a in m.atom:
            if random.random() < 0.8:
                del a.coord
        simple_unknowns(m)
        cmd.load_model(m.convert_to_indexed(), 'm' + str(i + 1))
Ejemplo n.º 32
0
def swell():
    a = [Vec(x.coord) for x in cmd.get_model("177L").atom]
    b = [Vec(x.coord) for x in cmd.get_model("179L").atom]
    d = [(a[i] - b[i]).length() for i in range(len(a))]
    # print max(d), argmax(d), cmd.get_model("179L").atom[argmax(d)].resi
    # print min(d)
    for i in range(0, 101):
        cmd.create("mix%03i" % i, "177L")
        m = cmd.get_model("177L")
        r = float(i) / 100.0
        print "mixing", r
        for j in range(len(m.atom)):
            # for k in range(len(m.atom)):
            #   d = (a[j]-a[k]).length() - (b[j]-b[k]).length()
            # print j, m.atom[j].coord
            m.atom[j].coord[0] = r * b[j].x + (1.0 - r) * a[j].x
            m.atom[j].coord[1] = r * b[j].y + (1.0 - r) * a[j].y
            m.atom[j].coord[2] = r * b[j].z + (1.0 - r) * a[j].z
            # print j, m.atom[j].coord
        cmd.load_model(m, "mix%03i" % i, 1)
        cmd.save("177L_179L_raw_mix%03i.pdb" % i, "mix%03i" % i)
Ejemplo n.º 33
0
def swell():
    a = [Vec(x.coord) for x in cmd.get_model("177L").atom]
    b = [Vec(x.coord) for x in cmd.get_model("179L").atom]
    d = [(a[i] - b[i]).length() for i in range(len(a))]
    #print max(d), argmax(d), cmd.get_model("179L").atom[argmax(d)].resi
    #print min(d)
    for i in range(0, 101):
        cmd.create("mix%03i" % i, "177L")
        m = cmd.get_model("177L")
        r = float(i) / 100.0
        print "mixing", r
        for j in range(len(m.atom)):
            # for k in range(len(m.atom)):
            # 	d = (a[j]-a[k]).length() - (b[j]-b[k]).length()
            # print j,m.atom[j].coord
            m.atom[j].coord[0] = r * b[j].x + (1.0 - r) * a[j].x
            m.atom[j].coord[1] = r * b[j].y + (1.0 - r) * a[j].y
            m.atom[j].coord[2] = r * b[j].z + (1.0 - r) * a[j].z
            # print j,m.atom[j].coord
        cmd.load_model(m, "mix%03i" % i, 1)
        cmd.save("177L_179L_raw_mix%03i.pdb" % i, "mix%03i" % i)
Ejemplo n.º 34
0
def gotraj(sel, filename="unlikelytobearealname.exe", skip=1, extension=None):
    if sel == "help":
        print("gotraj selection traj_filename skip\n")
        print(
            "The trajectory file will be loaded on the selection, in a new object"
        )
        print(
            "A frame will be read every skip frames (default=1, all frames are read)"
        )
        return
    ed = {
        "crd": "amber",
        "trj": "amber",
        "xyz": "xyz",
        "xtc": "xtc",
        "dcd": "dcd",
        "pdb": "pdb",
        "xtc": "xtc"
    }
    proc = Popen("gotraj", shell=True, stdin=PIPE, stdout=PIPE)
    if filename == "unlikelytobearealname.exe":
        raise "usage: gotraj selection traj_file_name\n (you must give the name of the trajectory to be read)"
    if not extension:
        ext = filename.split(".")[-1]
        extension = ed[
            ext]  #if this doesn't work you get a well deserved exception
    if extension == "xtc":
        print("this extension is probably not supported!"
              )  #you'll get a crash later
    opt = gochem.Options()
    opt.AddStringOptions([filename, extension])
    opt.AddIntOptions([int(skip)])
    gochem.SendgoChem(proc, selnames=[sel], options=opt, sort=True)
    info = gochem.get_info(proc)
    mod, states = gochem.get_model(proc, info, 0)
    gochem.LoadNew(mod, sel + "_Traj")
    while states.GetState(mod):
        cmd.load_model(
            mod, sel + "_Traj"
        )  #we don't want to re-calculate bonds, so we call this function instead.
Ejemplo n.º 35
0
def mini(total_step=100, gradient=0.001, interval=100, obj="rt"):

    global state

    if not state:
        print " realtime.mini: please run setup first."
    else:
        state.echo = 0

        model = state.model

        print " realtime.mini: %d atoms total\n" % model.nAtom

        xtra_kw = []

        xtra_kw.extend(keyword.get_inactive(model, 3))
        xtra_kw.extend(keyword.get_restrain_positions(model, 2, 0, 10))
        xtra_kw.extend(keyword.get_restrain_positions(model, 5, 0.5, 1))
        xtra_kw.extend(keyword.get_inactive(model, 6))

        state.keywords["chg-cutoff"] = 10.0
        state.keywords["vdw-cutoff"] = 7.00
        state.keywords["lights"] = ""
        state.keywords["restrainterm"] = ""

        iter = total_step / interval
        for x in range(0, iter):
            state.minimize(gradient=gradient, max_iter=interval, kw=xtra_kw)
            cmd.delete(obj)
            cmd.load_model(model, obj, 1)
            cmd.refresh()
            if not len(state.summary):
                break
            for a in state.summary:
                print a
            if state.summary[-1][7] == "SmallGrad":
                break
        io.pkl.toFile(model, "realtime.pkl")
        print " realtime.mini: terminated after %d steps." % state.counter
Ejemplo n.º 36
0
def mini(total_step=100, gradient=0.001, interval=100, obj='rt'):

    global state

    if not state:
        print(" realtime.mini: please run setup first.")
    else:
        state.echo = 0

        model = state.model

        print(" realtime.mini: %d atoms total\n" % model.nAtom)

        xtra_kw = []

        xtra_kw.extend(keyword.get_inactive(model, 3))
        xtra_kw.extend(keyword.get_restrain_positions(model, 2, 0, 10))
        xtra_kw.extend(keyword.get_restrain_positions(model, 5, 0.5, 1))
        xtra_kw.extend(keyword.get_inactive(model, 6))

        state.keywords['chg-cutoff'] = 10.0
        state.keywords['vdw-cutoff'] = 7.00
        state.keywords['lights'] = ''
        state.keywords['restrainterm'] = ''

        iter = total_step / interval
        for x in range(0, iter):
            state.minimize(gradient=gradient, max_iter=interval, kw=xtra_kw)
            cmd.delete(obj)
            cmd.load_model(model, obj, 1)
            cmd.refresh()
            if not len(state.summary):
                break
            for a in state.summary:
                print(a)
            if state.summary[-1][7] == 'SmallGrad':
                break
        io.pkl.toFile(model, "realtime.pkl")
        print(" realtime.mini: terminated after %d steps." % state.counter)
Ejemplo n.º 37
0
def dyna(steps, iter=1):

    global state

    if not state:
        print " realtime.dyna: please run setup first."
    else:
        state.echo = 0

        model = state.model

        print " realtime.dyna: %d atoms total\n" % model.nAtom

        xtra_kw = []

        xtra_kw.extend(keyword.get_inactive(model, 3))
        xtra_kw.extend(keyword.get_restrain_positions(model, 2, 0, 10))
        xtra_kw.extend(keyword.get_restrain_positions(model, 5, 0.5, 1))
        xtra_kw.extend(keyword.get_inactive(model, 6))

        state.keywords["chg-cutoff"] = 10.0
        state.keywords["vdw-cutoff"] = 7.00
        state.keywords["lights"] = ""
        state.keywords["restrainterm"] = ""

        for x in range(0, iter):
            state.dynamics(steps=steps, timestep=1, kw=xtra_kw)
            if not len(state.summary):
                break
            for a in state.summary:
                print a
            cmd.load_model(model, "dyna")
            cmd.ending()
            cmd.refresh()
        io.pkl.toFile("realtime.pkl")
        print " realtime.dyna: terminated after %d steps." % state.counter
Ejemplo n.º 38
0
def dyna(steps, iter=1):

    global state

    if not state:
        print(" realtime.dyna: please run setup first.")
    else:
        state.echo = 0

        model = state.model

        print(" realtime.dyna: %d atoms total\n" % model.nAtom)

        xtra_kw = []

        xtra_kw.extend(keyword.get_inactive(model, 3))
        xtra_kw.extend(keyword.get_restrain_positions(model, 2, 0, 10))
        xtra_kw.extend(keyword.get_restrain_positions(model, 5, 0.5, 1))
        xtra_kw.extend(keyword.get_inactive(model, 6))

        state.keywords['chg-cutoff'] = 10.0
        state.keywords['vdw-cutoff'] = 7.00
        state.keywords['lights'] = ''
        state.keywords['restrainterm'] = ''

        for x in range(0, iter):
            state.dynamics(steps=steps, timestep=1, kw=xtra_kw)
            if not len(state.summary):
                break
            for a in state.summary:
                print(a)
            cmd.load_model(model, 'dyna')
            cmd.ending()
            cmd.refresh()
        io.pkl.toFile("realtime.pkl")
        print(" realtime.dyna: terminated after %d steps." % state.counter)
Ejemplo n.º 39
0
def sidechaincenters(object='scc', selection='all', method='bahar1996', name='PS1'):
    '''
DESCRIPTION

    Creates an object with sidechain representing pseudoatoms for each residue
    in selection.

    Two methods are available:
    (1) Sidechain interaction centers as defined by Bahar and Jernigan 1996
        http://www.ncbi.nlm.nih.gov/pubmed/9080182
    (2) Sidechain centroids, the pseudoatom is the centroid of all atoms except
        hydrogens and backbone atoms (N, C and O).

NOTE

    With method "bahar1996", if a residue has all relevant sidechain center
    atoms missing (for example a MET without SD), it will be missing in the
    created pseudoatom object.

    With method "centroid", if you want to exclude C-alpha atoms from
    sidechains, modify the selection like in this example:

    sidechaincenters newobject, all and (not name CA or resn GLY), method=2

USAGE

    sidechaincenters object [, selection [, method ]]

ARGUMENTS

    object = string: name of object to create

    selection = string: atoms to consider {default: (all)}

    method = string: bahar1996 or centroid {default: bahar1996}

    name = string: atom name of pseudoatoms {default: PS1}

SEE ALSO

    pseudoatom
    '''
    from chempy import Atom, cpv, models

    atmap = dict()
    if method in ['bahar1996', '1', 1]:
        modelAll = cmd.get_model('(%s) and resn %s' % (selection, '+'.join(sidechaincenteratoms)))
        for at in modelAll.atom:
            if at.name in sidechaincenteratoms[at.resn]:
                atmap.setdefault((at.segi, at.chain, at.resn, at.resi), []).append(at)
    elif method in ['centroid', '2', 2]:
        modelAll = cmd.get_model('(%s) and polymer and not (hydro or name C+N+O)' % selection)
        for at in modelAll.atom:
            atmap.setdefault((at.segi, at.chain, at.resn, at.resi), []).append(at)
    else:
        print('Error: unknown method:', method)
        raise CmdException

    model = models.Indexed()
    for centeratoms in atmap.values():
        center = cpv.get_null()
        for at in centeratoms:
            center = cpv.add(center, at.coord)
        center = cpv.scale(center, 1./len(centeratoms))
        atom = Atom()
        atom.coord = center
        atom.index = model.nAtom + 1
        atom.name = name
        for key in ['resn','chain','resi','resi_number','hetatm','ss','segi']:
            atom.__dict__[key] = at.__dict__[key]
        model.add_atom(atom)
    model.update_index()
    if object in cmd.get_object_list():
        cmd.delete(object)
    cmd.load_model(model, object)
    return model
Ejemplo n.º 40
0
 def testLoadModel(self):
     cmd.fragment('gly')
     m = cmd.get_model()
     cmd.delete('*')
     cmd.load_model(m, 'm1')
     self.assertEqual(7, cmd.count_atoms())
Ejemplo n.º 41
0
    def execute(self, result):

	if result == defaults["compute_command"]:
            if self.testBinary() == 0:
              return
            self.showCrisscross()
            #input
            sel1index = self.listbox1.curselection()[0]
            sel1text = self.listbox1.get(sel1index)
            self.whichModelSelect = sel1text;
            print 'selected ' + self.whichModelSelect
            sel=cmd.get_model(self.whichModelSelect)
            cnt=0
            for a in sel.atom:
               cnt+=1
            print cnt

            if cnt == 0:
                error_dialog = Pmw.MessageDialog(self.parent,title = 'Error',
                                   message_text = 'ERROR: No molecule loaded.',)
                junk = error_dialog.activate()
                return
            outdir = self.binlocation.getvalue()
            if os.path.isfile(outdir):
               error_dialog = Pmw.MessageDialog(self.parent,title = 'Error',
                                   message_text = 'ERROR: Output directory is file.',)
               junk = error_dialog.activate()
               return
            elif not os.path.exists(outdir):
               self.CreateDirectory(outdir)
            self.stdamString = string.join(self.stdam_list, "+")
            # jen to zaskrtnute
            generatedString = ""
            for key in self.s:
              if self.s[key].get() == 1:
                # pak pouzit do vyberu:
                if key == "AA":
                  generatedString = generatedString + "+" + self.stdamString
                else:
                  generatedString = generatedString + "+" + key

            generatedString = generatedString[1:]
            print "Checked: " + generatedString

            mmodel = cmd.get_model(self.whichModelSelect)
            print self.whichModelSelect + " asize: " + str(len(mmodel.atom))
            newmodel = Indexed()
            for matom in mmodel.atom:
              if generatedString.find(matom.resn) > -1:
                #print matom.resn
                newmodel.atom.append(matom)
            cmd.load_model(newmodel,"tmpCaverModel")
            #cmd.label("example","name")
            #fix outdir slashes
            outdir = outdir.replace("\\","/")
            if (outdir.endswith("/")):
				outdir = outdir[:-1]
            input = "%s/out.pdb" % (outdir)
            #cmd.save(input, self.whichModelSelect) # to by ulozilo cely model whichModelSelect.
            cmd.save(input, "tmpCaverModel")
            cmd.delete("tmpCaverModel")
            cesta = os.getcwd()
            # set ignore waters to false -- the model is already filtered by input model and aminos
            self.varremovewater.set(0)
            if WINDOWZ:
              #commandXYZ = "java %s -jar \"%s/modules/Caver2_1_%s/Caver2_1.jar\" \"%s\" %f %f %f %s \"%s\" %d %d %d %s" % (JOPTS, self.pymollocation.getvalue(), VERS, input, float(self.xlocvar.get()), float(self.ylocvar.get()), float(self.zlocvar.get()), self.tunnels.getvalue(), outdir, self.varremovewater.get(), 0,self.methodvar.get(), "tun_" + self.whichModelSelect)
              commandXYZ = "java %s -jar \"%s\Caver2_1.jar\" \"%s\" %f %f %f %s \"%s\" %d %d %d %s" % (JOPTS, self.pymollocation.getvalue(),input, float(self.xlocvar.get()), float(self.ylocvar.get()), float(self.zlocvar.get()), self.tunnels.getvalue(), outdir, self.varremovewater.get(),0,self.methodvar.get(), "tun_" + self.whichModelSelect)
            else:
              commandXYZ = "java %s -jar \"%s/Caver2_1.jar\" \"%s\" %f %f %f %s \"%s\" %d %d %d %s" % (JOPTS, self.pymollocation.getvalue(),input, float(self.xlocvar.get()), float(self.ylocvar.get()), float(self.zlocvar.get()), self.tunnels.getvalue(), outdir, self.varremovewater.get(),0,self.methodvar.get(), "tun_" + self.whichModelSelect)
            tunnels = int(self.tunnels.getvalue())
            # ted vymazat v output dir vsechny soubory s path_*.py os.path.isfile(string)
            for i in range(tunnels):
              tunpy = "%s/path_%i.py" % (outdir,i)
              if (os.path.isfile(tunpy)):
                os.remove(tunpy);
            print commandXYZ
            os.system(commandXYZ)
            for i in range(tunnels):
               pathpy = "%s/path_%i.py" % (outdir, i)
               if os.access(pathpy,os.F_OK):
                  view = cmd.get_view()
                  execfile(pathpy)
                  cmd.set_view(view)
                  if i != 0:
                     cmd.disable("tunnel%i" % i);
               else:
                  if i == 0:
                    error_dialog = Pmw.MessageDialog(self.parent,title = 'Error',
                                       message_text = 'Error: No tunnel was found, the starting point is probably outside of the molecule.',)

                    junk = error_dialog.activate()
                    break
                  else:
                    messa = "No more tunnels than %i were found" % (i)
                    error_dialog = Pmw.MessageDialog(self.parent,title = 'Info',
                                       message_text = messa,)
                    junk = error_dialog.activate()
                    break
	    #pass
	    #self.deleteTemporaryFiles()
	else:
            #
            # Doing it this way takes care of clicking on the x in the top of the
            # window, which as result set to None.
            #
            if __name__ == '__main__':
                #
                # dies with traceback, but who cares
                #
                self.parent.destroy()
            else:
                #self.dialog.deactivate(result)
                global CAVER_BINARY_LOCATION
                CAVER_BINARY_LOCATION = self.binlocation.getvalue()
                self.dialog.withdraw()
Ejemplo n.º 42
0
def add_missing_atoms(selection='all', cycles=200, quiet=1):
    '''
DESCRIPTION

    Mutate those residues to themselves which have missing atoms

SEE ALSO

    stub2ala
    '''
    from collections import defaultdict
    from chempy import fragments

    cycles, quiet = int(cycles), int(quiet)

    reference = {
        'ALA': set(['CB']),
        'ARG': set(['CB', 'CG', 'NE', 'CZ', 'NH1', 'NH2', 'CD']),
        'ASN': set(['CB', 'CG', 'OD1', 'ND2']),
        'ASP': set(['CB', 'CG', 'OD1', 'OD2']),
        'CYS': set(['CB', 'SG']),
        'GLN': set(['CB', 'CG', 'CD', 'NE2', 'OE1']),
        'GLU': set(['CB', 'CG', 'OE2', 'CD', 'OE1']),
        'GLY': set([]),
        'HIS': set(['CE1', 'CB', 'CG', 'CD2', 'ND1', 'NE2']),
        'ILE': set(['CB', 'CD1', 'CG1', 'CG2']),
        'LEU': set(['CB', 'CG', 'CD1', 'CD2']),
        'LYS': set(['CB', 'CG', 'NZ', 'CE', 'CD']),
        'MET': set(['CB', 'CG', 'CE', 'SD']),
        'PHE': set(['CE1', 'CB', 'CG', 'CZ', 'CD1', 'CD2', 'CE2']),
        'PRO': set(['CB', 'CG', 'CD']),
        'SER': set(['OG', 'CB']),
        'THR': set(['CB', 'OG1', 'CG2']),
        'TRP': set(['CZ2', 'CB', 'CG', 'CH2', 'CE3', 'CD1', 'CD2', 'CZ3', 'NE1', 'CE2']),
        'TYR': set(['CE1', 'OH', 'CB', 'CG', 'CZ', 'CD1', 'CD2', 'CE2']),
        'VAL': set(['CB', 'CG1', 'CG2']),
    }

    namedsele = cmd.get_unused_name('_')
    cmd.select(namedsele, selection, 0)

    namelists = defaultdict(list)
    cmd.iterate('(%s) and polymer' % namedsele,
            'namelists[model,segi,chain,resn,resi,resv].append(name)',
            space=locals())

    sele_dict = defaultdict(list)
    tmp_name = cmd.get_unused_name('_')

    for key, namelist in namelists.items():
        resn = key[3]
        if resn not in reference:
            if not quiet:
                print(' Unknown residue:', resn)
            continue
        if not reference[resn].issubset(namelist):
            try:
                frag = fragments.get(resn.lower())
                for a in frag.atom:
                    a.segi = key[1]
                    a.chain = key[2]
                    a.resi = key[4]
                    a.resi_number = key[5]
                cmd.load_model(frag, tmp_name, 1, zoom=0)

                skey = '/%s/%s/%s/%s`%s' % key[:5]
                cmd.remove(skey + ' and not name N+C+O+OXT+CA')
                cmd.align(tmp_name, skey + ' and name N+C+CA', cycles=0)
                cmd.remove(tmp_name + ' and (name N+C+O+CA or hydro)')
                cmd.fuse('name CB and ' + tmp_name, 'name CA and ' + skey, move=0)
                if resn == 'PRO':
                    cmd.bond(skey + '/N', skey + '/CD')
                cmd.unpick()
                cmd.delete(tmp_name)

                sele_dict[key[0]].append(skey)

                if not quiet:
                    print(' Mutated ', skey)
            except:
                print(' Mutating', skey, 'failed')

    for model in sele_dict:
        cmd.sort(model)
        sculpt_relax(' '.join(sele_dict[model]), 0, 0, model, cycles)

    cmd.delete(namedsele)
Ejemplo n.º 43
0
# turn off some of the chatter about reloading the object...

cmd.feedback("disable","executive","actions")

# now loop, updating the coordinates and reloading the model into
# state 1 of the "demo" object

m = cmd.get_model()
while 1:
   time.sleep(0.05)
   try:
      cmd.set("suspend_updates","1") # only necessary if multithreading...
      for a in m.atom:
         a.coord[0]+=(random()-0.5)*0.1
         a.coord[1]+=(random()-0.5)*0.1
         a.coord[2]+=(random()-0.5)*0.1
      cmd.load_model(m,"demo",1)
   except:
      cmd.set("suspend_updates","0") # only necessary if multithreading...
      traceback.print_exc()
   cmd.refresh()

# Summary: this is portable, safe, but inefficient.  For real-time visualization
# of coordinate changes, there is a way to do this by passing in an opaque
# C data structure...

# Cheers, [email protected]



Ejemplo n.º 44
0
    def get_zmat_ext_freeze_torsion(self,flag=3):
        # requires PYMOL to read dihedrals from structure
        # requires list of dihedrals from tinker.amber
        #
        from pymol import cmd
        from .tinker.amber import Topology      

        cmd.load_model(self.model,'_gamess1')
        model = self.model

        # get mapping of model ordering to zmat ordering
        m2z = {}
        z2m = {}
        c = 1 # GAMESS is one-based
        for a in self.get_zmat_ordering():
            m2z[a] = c
            z2m[c] = a
            c = c + 1

        # get all torsions in the molecule

        topo = Topology(self.model)

        # find those where flag is set in all atoms

        mask = 2 ** flag

        frozen_list = []

        for a in list(topo.torsion.keys()):
            if (model.atom[a[0]].flags&
                 model.atom[a[1]].flags&
                 model.atom[a[2]].flags&
                 model.atom[a[3]].flags)&mask:
                frozen_list.append(a)

        print(" freeze-torsion: %d torsions will be frozen."%len(frozen_list))

        irzmat = []
        ifzmat = []
        fvalue = []
        if len(frozen_list):

            for frozen in frozen_list:
                # find additional torsions which need to be removed

                remove = []

                for a in list(topo.torsion.keys()):
                    if (((a[1]==frozen[1])and(a[2]==frozen[2])) or
                         ((a[2]==frozen[1])and(a[1]==frozen[2]))):
                        if a!=frozen:
                            remove.append(a)

                # convert to internal coordinate ordering

                frozen_z = (m2z[frozen[0]],m2z[frozen[1]],
                                m2z[frozen[2]],m2z[frozen[3]])

                remove_z = []
                for a in remove:
                    remove_z.append(m2z[a[0]],m2z[a[1]],m2z[a[2]],m2z[a[3]])

                # now reorder atoms in torsions to reflect z_matrix ordering
                # (not sure this is necessary)

                if frozen_z[0]>frozen_z[3]:
                    frozen_z = (frozen_z[3],frozen_z[2],frozen_z[1],frozen_z[0])
                tmp_z = []
                for a in remove_z:
                    if a[0]>a[3]:
                        tmp_z.append((a[3],a[2],a[1],a[0]))
                    else:
                        tmp_z.append(a)
                remove_z = tmp_z

                # get value of the fixed torsion

                fixed = (z2m[frozen_z[0]],z2m[frozen_z[1]],
                            z2m[frozen_z[2]],z2m[frozen_z[3]])

                dihe = cmd.get_dihedral("(_gamess1 and id %d)"%fixed[0],
                                      "(_gamess1 and id %d)"%fixed[1],
                                      "(_gamess1 and id %d)"%fixed[2],
                                      "(_gamess1 and id %d)"%fixed[3])

                # write out report for user edification

                print(" freeze-torsion: fixing freeze-torsion:")
                print(" freeze-torsion: %d-%d-%d-%d (pymol), %d-%d-%d-%d (gamess)"%(
                    fixed[0],fixed[1],fixed[2],fixed[3],
                    frozen_z[0],frozen_z[1],frozen_z[2],frozen_z[3]))
                print(" freeze-torsion: at %5.3f"%dihe)
                print(" freeze-torsion: removing redundant torsions:")
                for a in remove_z[1:]:
                    print(" freeze-torsion: %d-%d-%d-%d (pymol), %d-%d-%d-%d (gamess)"%(
                        z2m[a[0]],z2m[a[1]],z2m[a[2]],z2m[a[3]],
                        a[0],a[1],a[2],a[3]))

                # add parameters for this torsion into the list

                ifzmat.append((3,frozen_z[0],frozen_z[1],frozen_z[2],frozen_z[3]))
                fvalue.append(dihe)

                if len(remove_z):
                    for a in remove_z[1:]:
                        irzmat.append((3,a[0],a[1],a[2],a[3]))

        # generate restrained dihedral information

        zmat_ext = []
        if len(ifzmat):
            zmat_ext.append(" IFZMAT(1)=\n")
            comma = ""
            for a in ifzmat:
                zmat_ext.append(comma+"%d,%d,%d,%d,%d\n"%a)
                comma = ","
        if len(fvalue):
            zmat_ext.append(" FVALUE(1)=\n")
            comma = ""
            for a in fvalue:
                zmat_ext.append(comma+"%1.7f\n"%a)
                comma = ","
        if len(irzmat):
            zmat_ext.append(" IRZMAT(1)=\n")
            comma = ""
            for a in irzmat:
                zmat_ext.append(comma+"%d,%d,%d,%d,%d\n"%a)
                comma = ","

        cmd.delete("_gamess1") # important
        if len(zmat_ext):
            return zmat_ext
        else:
            return None
Ejemplo n.º 45
0
 def testLoadModel(self):
     cmd.fragment('gly')
     m = cmd.get_model()
     cmd.delete('*')
     cmd.load_model(m, 'm1')
     self.assertEqual(7, cmd.count_atoms())
Ejemplo n.º 46
0
model = Indexed()

# append the atoms onto it

for a in atoms:
    new_atom = Atom()
    new_atom.symbol = a[0]  # elemental symbol
    new_atom.name = a[1]  # atom name
    new_atom.resi = a[2]  # residue identifier
    new_atom.resn = a[3]  # residue name
    model.atom.append(new_atom)
# (note that there are a bunch of other fields we're not using -- and none are required)

# add coordinates onto the atoms

for a in model.atom:  # now assign coordinates
    a.coord = coords.pop(0)

# now specify the bonds

for a in bonds:
    new_bond = Bond()
    new_bond.index = [a[0], a[1]]  # atom indices (zero-based)
    new_bond.order = a[2]  # bond order
    model.bond.append(new_bond)

# finally, load the model into PyMOL

cmd.load_model(model, "example")
Ejemplo n.º 47
0
def sidechaincenters(object='scc',
                     selection='all',
                     method='bahar1996',
                     name='PS1'):
    '''
DESCRIPTION

    Creates an object with sidechain representing pseudoatoms for each residue
    in selection.

    Two methods are available:
    (1) Sidechain interaction centers as defined by Bahar and Jernigan 1996
        http://www.ncbi.nlm.nih.gov/pubmed/9080182
    (2) Sidechain centroids, the pseudoatom is the centroid of all atoms except
        hydrogens and backbone atoms (N, C and O).

NOTE

    With method "bahar1996", if a residue has all relevant sidechain center
    atoms missing (for example a MET without SD), it will be missing in the
    created pseudoatom object.

    With method "centroid", if you want to exclude C-alpha atoms from
    sidechains, modify the selection like in this example:

    sidechaincenters newobject, all and (not name CA or resn GLY), method=2

USAGE

    sidechaincenters object [, selection [, method ]]

ARGUMENTS

    object = string: name of object to create

    selection = string: atoms to consider {default: (all)}

    method = string: bahar1996 or centroid {default: bahar1996}

    name = string: atom name of pseudoatoms {default: PS1}

SEE ALSO

    pseudoatom
    '''
    from chempy import Atom, cpv, models

    atmap = dict()
    if method in ['bahar1996', '1', 1]:
        modelAll = cmd.get_model('(%s) and resn %s' %
                                 (selection, '+'.join(sidechaincenteratoms)))
        for at in modelAll.atom:
            if at.name in sidechaincenteratoms[at.resn]:
                atmap.setdefault((at.segi, at.chain, at.resn, at.resi),
                                 []).append(at)
    elif method in ['centroid', '2', 2]:
        modelAll = cmd.get_model(
            '(%s) and polymer and not (hydro or name C+N+O)' % selection)
        for at in modelAll.atom:
            atmap.setdefault((at.segi, at.chain, at.resn, at.resi),
                             []).append(at)
    else:
        print('Error: unknown method:', method)
        raise CmdException

    model = models.Indexed()
    for centeratoms in atmap.values():
        center = cpv.get_null()
        for at in centeratoms:
            center = cpv.add(center, at.coord)
        center = cpv.scale(center, 1. / len(centeratoms))
        atom = Atom()
        atom.coord = center
        atom.index = model.nAtom + 1
        atom.name = name
        for key in [
                'resn', 'chain', 'resi', 'resi_number', 'hetatm', 'ss', 'segi'
        ]:
            atom.__dict__[key] = at.__dict__[key]
        model.add_atom(atom)
    model.update_index()
    if object in cmd.get_object_list():
        cmd.delete(object)
    cmd.load_model(model, object)
    return model
Ejemplo n.º 48
0
 def show(self):
     auto_zoom = cmd.get("auto_zoom")
     cmd.set("auto_zoom", 0)
     cmd.load_model(self.model, self.name)
     cmd.set("auto_zoom", auto_zoom)
Ejemplo n.º 49
0
def delaunay(selection='enabled', name=None, cutoff=10.0, as_cgo=0,
        qdelaunay_exe='qdelaunay', state=-1, quiet=1):
    '''
DESCRIPTION

    Full-atom Delaunay Tessalator

    Creates either a molecular object with delaunay edges as bonds, or a CGO
    object with edge colors according to edge length.

USAGE

    delaunay [ selection [, name [, cutoff=10.0 [, as_cgo=0 ]]]]

SEE ALSO

    PyDeT plugin: http://pymolwiki.org/index.php/PyDet
    '''
    from chempy import cpv, Bond
    if name is None:
        name = cmd.get_unused_name('delaunay')
    cutoff = float(cutoff)
    as_cgo = int(as_cgo)
    state, quiet = int(state), int(quiet)
    if state < 1:
        state = cmd.get_state()
    model = cmd.get_model(selection, state)
    regions_iter = qdelaunay((a.coord for a in model.atom), 3, len(model.atom),
            qdelaunay_exe=qdelaunay_exe)
    edges = set(tuple(sorted([region[i-1], region[i]]))
            for region in regions_iter for i in range(len(region)))

    edgelist=[]
    r = []

    minco = 9999
    maxco = 0

    for edge in edges:
        ii, jj = edge
        a = model.atom[ii]
        b = model.atom[jj]
        co = cpv.distance(a.coord, b.coord)
        if cutoff > 0.0 and co > cutoff:
            continue
        if as_cgo:
            minco=min(co,minco)
            maxco=max(co,maxco)
            edgelist.append(a.coord + b.coord + [co])
        else:
            bnd = Bond()
            bnd.index = [ii, jj]
            model.add_bond(bnd)
        r.append((a,b,co))

    if not as_cgo:
        cmd.load_model(model, name, 1)
        return r

    from pymol.cgo import CYLINDER

    difco = maxco-minco
    obj = []
    mm = lambda x: max(min(x, 1.0), 0.0)
    for e in edgelist:
        co = ((e[6]-minco)/difco)**(0.75)
        color = [mm(1-2*co), mm(1-abs(2*co-1)), mm(2*co-1)]
        obj.extend([CYLINDER] + e[0:6] + [0.05] + color + color)

    cmd.load_cgo(obj, name)
    return r
Ejemplo n.º 50
0
# create a model instance

model = Indexed()

# append the atoms onto it 

for x in range(-63,63,1):
   for y in range(-63,63,1):
      new_atom = Atom()
      new_atom.symbol = 'O'
      new_atom.coord = [ x*2, y*2, 30 * math.cos(math.sqrt(x*x+y*y)/60.0) ]
      model.atom.append(new_atom)


cmd.load_model(model,"membrane")
cmd.hide("everything","membrane")
cmd.show("spheres","membrane")
cmd.color("lightblue","membrane")

cmd.set_view( (\
     0.736728907,   -0.144400939,    0.660589039,\
     0.675238073,    0.208899528,   -0.707400322,\
    -0.035847016,    0.967217624,    0.251406968,\
     0.000008686,    0.000009686, -332.961212158,\
    -2.366872311,   -1.122793436,   23.127344131,\
    11.627288818,  654.294433594,    0.000000000 ))


# uncomment this if you programmable shaders
# cmd.set("sphere_mode",5)
Ejemplo n.º 51
0
 def show(self):
     auto_zoom = cmd.get("auto_zoom")
     cmd.set("auto_zoom", 0)
     cmd.load_model(self.model, self.name)
     cmd.set("auto_zoom", auto_zoom)
Ejemplo n.º 52
0
def load_3d(filename, object=''):
    '''
DESCRIPTION

    Load a survex 3d cave survey as "molecule"

    http://survex.com
    http://trac.survex.com/browser/trunk/doc/3dformat.htm
    '''
    from chempy import Atom, Bond, models
    from struct import unpack

    if object == '':
        object = os.path.splitext(os.path.basename(filename))[0]

    f = open(filename, 'rb')

    line = f.readline() # File ID
    if not line.startswith('Survex 3D Image File'):
        print " Error: not a Survex 3D File"
        raise CmdException

    line = f.readline() # File format version
    assert line[0] == 'v'
    ff_version = int(line[1:])

    line = unicode(f.readline(), 'latin1') # Survex title
    line = f.readline() # Timestamp

    class Station:
        def __init__(self):
            self.labels = []
            self.adjacent = []
            self.lrud = None
            self.flag = 0
        def connect(self, other):
            self.adjacent.append(other)
        def is_surface(self):
            return self.flag & 0x01
        def is_underground(self):
            return self.flag & 0x02
        def is_entrance(self):
            return self.flag & 0x04
        def is_exported(self):
            return self.flag & 0x08
        def is_fixed(self):
            return self.flag & 0x10

    class Survey(dict):
        def __init__(self):
            self.prev = None
            self.curr_label = ''
            self.labelmap = {}
        def get(self, xyz):
            return dict.setdefault(self, tuple(xyz), Station())
        def line(self, xyz):
            s = self.get(xyz)
            self.prev.connect(s)
            self.prev = s
        def move(self, xyz):
            s = self.get(xyz)
            self.prev = s
        def label(self, xyz, flag=0):
            s = self.get(xyz)
            s.labels.append(self.curr_label)
            self.labelmap[s.labels[-1]] = s
            if flag > 0:
                s.flag = flag
        def lrud(self, lrud):
            s = self.labelmap[self.curr_label]
            s.lrud = lrud

    survey = Survey()

    def read_xyz():
        return unpack('<iii', f.read(12))

    def read_len():
        len = read_byte()
        if len == 0xfe:
            len += unpack('<H', f.read(2))[0]
        elif len == 0xff:
            len += unpack('<I', f.read(4))[0]
        return len

    def read_label():
        len = read_len()
        if len > 0:
            survey.curr_label += skip_bytes(len)

    def skip_bytes(n):
        return f.read(n)

    def read_byte():
        byte = f.read(1)
        if len(byte) != 1:
            return -1
        return ord(byte)

    while 1:
        byte = read_byte()
        if byte == -1:
            break
        
        if byte == 0x00:
            # STOP
            survey.curr_label = ''
        elif byte <= 0x0e:
            # TRIM
            # FIXME: according to doc, trim 16 bytes, but img.c does 17!
            (i,n) = (-17,0)
            while n < byte:
                i -= 1
                if survey.curr_label[i] == '.': n += 1
            survey.curr_label = survey.curr_label[:i + 1]
        elif byte <= 0x0f:
            # MOVE
            xyz = read_xyz()
            survey.move(xyz)
        elif byte <= 0x1f:
            # TRIM
            survey.curr_label = survey.curr_label[:15 - byte]
        elif byte <= 0x20:
            # DATE
            if ff_version < 7:
                skip_bytes(4)
            else:
                skip_bytes(2)
        elif byte <= 0x21:
            # DATE
            if ff_version < 7:
                skip_bytes(8)
            else:
                skip_bytes(3)
        elif byte <= 0x22:
            # Error info
            skip_bytes(5 * 4)
        elif byte <= 0x23:
            # DATE
            skip_bytes(4)
        elif byte <= 0x24:
            # DATE
            continue
        elif byte <= 0x2f:
            # Reserved
            continue
        elif byte <= 0x31:
            # XSECT
            read_label()
            lrud = unpack('<hhhh', f.read(8))
            survey.lrud(lrud)
        elif byte <= 0x33:
            # XSECT
            read_label()
            lrud = unpack('<iiii', f.read(16))
            survey.lrud(lrud)
        elif byte <= 0x3f:
            # Reserved
            continue
        elif byte <= 0x7f:
            # LABEL
            read_label()
            xyz = read_xyz()
            survey.label(xyz, byte & 0x3f)
        elif byte <= 0xbf:
            # LINE
            read_label()
            xyz = read_xyz()
            survey.line(xyz)
        elif byte <= 0xff:
            # Reserved
            continue

    model = models.Indexed()
    for (xyz,s) in survey.iteritems():
        l0, _, l1 = s.labels[0].rpartition('.')
        resi, name = l1[:5], l1[5:]
        segi, chain, resn = l0[-8:-4], l0[-4:-3], l0[-3:]
        atom = Atom()
        atom.coord = [i/100.0 for i in xyz]
        atom.segi = segi
        atom.chain = chain
        atom.resn = resn
        atom.name = name
        atom.resi = resi
        atom.b = atom.coord[2]
        atom.label = s.labels[0]
        if s.lrud is not None:
            atom.vdw = sum(s.lrud)/400.0
        model.add_atom(atom)

    s2i = dict((s,i) for (i,s) in enumerate(survey.itervalues()))
    for (s,i) in s2i.iteritems():
        for o in s.adjacent:
            bnd = Bond()
            bnd.index = [i, s2i[o]]
            model.add_bond(bnd)

    cmd.load_model(model, object, 1)
    cmd.show_as('lines', object)
    cmd.spectrum('b', 'rainbow', object)
Ejemplo n.º 53
0
def peptide_rebuild(name, selection='all', cycles=1000, state=1, quiet=1):
    '''
DESCRIPTION

    Rebuild the peptide from selection. All atoms which are present in
    selection will be kept fixed, while atoms missing in selection are
    placed by sculpting.

USAGE

    peptide_rebuild name [, selection [, cycles [, state ]]]

SEE ALSO

    stub2ala, add_missing_atoms, peptide_rebuild_modeller
    '''
    from chempy import fragments, feedback, models

    cycles, state, quiet = int(cycles), int(state), int(quiet)

    # suppress feedback for model merging
    feedback['actions'] = False

    # work with named selection
    namedsele = cmd.get_unused_name('_')
    cmd.select(namedsele, selection, 0)

    identifiers = []
    cmd.iterate(namedsele + ' and polymer and guide and alt +A',
            'identifiers.append([segi,chain,resi,resv,resn])', space=locals())

    model = models.Indexed()
    for (segi,chain,resi,resv,resn) in identifiers:
        try:
            fname = resn.lower() if resn != 'MSE' else 'met'
            frag = fragments.get(fname)
        except IOError:
            print(' Warning: unknown residue:', resn)
            continue

        for a in frag.atom:
            a.segi = segi
            a.chain = chain
            a.resi = resi
            a.resi_number = resv
            a.resn = resn

        model.merge(frag)

    if not quiet:
        print(' Loading model...')

    cmd.load_model(model, name, 1, zoom=0)
    if cmd.get_setting_boolean('auto_remove_hydrogens'):
        cmd.remove(name + ' and hydro')

    cmd.protect(name + ' in ' + namedsele)
    cmd.sculpt_activate(name)
    cmd.update(name, namedsele, 1, state)
    cmd.delete(namedsele)

    if not quiet:
        print(' Sculpting...')

    cmd.set('sculpt_field_mask', 0x003, name) # bonds and angles only
    cmd.sculpt_iterate(name, 1, int(cycles / 4))

    cmd.set('sculpt_field_mask', 0x09F, name) # local + torsions
    cmd.sculpt_iterate(name, 1, int(cycles / 4))

    cmd.set('sculpt_field_mask', 0x0FF, name) # ... + vdw
    cmd.sculpt_iterate(name, 1, int(cycles / 2))

    cmd.sculpt_deactivate(name)
    cmd.deprotect(name)
    cmd.unset('sculpt_field_mask', name)

    if not quiet:
        print(' Connecting peptide...')

    pairs = cmd.find_pairs(name + ' and name C', name + ' and name N', 1, 1, 2.0)
    for pair in pairs:
        cmd.bond(*pair)
    cmd.h_fix(name)

    if not quiet:
        print(' peptide_rebuild: done')
Ejemplo n.º 54
0
# let's dress it up a little bit 

cmd.show("sticks","demo")

cmd.show("spheres","resi 10")

cmd.color("yellow","resi 5 and element C")

# now loop, updating the coordinates and appending the model
# onto 99 subsequent frames...

m = cmd.get_model()
for a in range(1,100):
   for a in m.atom:
      a.coord[0]+=(random()-0.5)*0.1
      a.coord[1]+=(random()-0.5)*0.1
      a.coord[2]+=(random()-0.5)*0.1
   cmd.load_model(m,"demo") # NOTE: no state number provided -> appends

# now define the movie with short pauses at beginning and and

cmd.mset("1 x15 1 -100 100 x15")

# now play the movie...

cmd.mplay()

# by default, PyMOL plays ~30 fps.
# "set movie_delay=0" to see maximum speed...

def load_3d(filename, object=''):
	'''
DESCRIPTION

    Load a survex 3d cave survey as "molecule"

    http://survex.com
	'''
	from chempy import Atom, Bond, models

	if object == '':
		import os
		object = os.path.splitext(os.path.basename(filename))[0]

	f = open(filename, 'rb')

	line = f.readline() # File ID
	if not line.startswith('Survex 3D Image File'):
		print " Error: not a Survex 3D File"
		raise CmdException

	line = f.readline() # File format version
	assert line[0] == 'v'
	ff_version = int(line[1:])

	line = unicode(f.readline(), 'latin1') # Survex title
	line = f.readline() # Timestamp

	class Station(tuple):
		def __new__(cls, xyz):
			return tuple.__new__(cls, xyz)
		def __init__(self, xyz):
			self.labels = []
			self.adjacent = []
		def connect(self, other):
			self.adjacent.append(other)

	class Survey(dict):
		def __init__(self):
			self.prev = None
			self.curr_label = ''
		def get(self, xyz):
			s = Station(xyz)
			return dict.setdefault(self, s, s)
		def line(self, xyz):
			s = self.get(xyz)
			self.prev.connect(s)
			self.prev = s
		def move(self, xyz):
			s = self.get(xyz)
			self.prev = s
		def label(self, xyz):
			s = survey.get(xyz)
			s.labels.append(self.curr_label)
		def __repr__(self):
			return 'Survey(' + repr(self.keys())[1:-1] + ')'

	survey = Survey()

	def read_xyz():
		x = read_int(4, 1)
		y = read_int(4, 1)
		z = read_int(4, 1)
		return [ x, y, z ]

	def read_int(len, sign):
		int = 0
		for i in range(len):
			int |= read_byte() << (8 * i)
		if sign and (int >> (8 * len - 1)):
			int -= (1 << 8 * len)
		return int

	def read_len():
		len = read_byte()
		if len == 0xfe:
			len += read_int(2, 0)
		elif len == 0xff:
			len = read_int(4, 0)
		return len

	def read_label():
		len = read_len()
		if len > 0:
			survey.curr_label += skip_bytes(len)

	def skip_bytes(n):
		return f.read(n)

	def read_byte():
		byte = f.read(1)
		if len(byte) != 1:
			return -1
		return ord(byte)

	while 1:
		byte = read_byte()
		if byte == -1:
			break
		
		if byte == 0x00:
			# STOP
			survey.curr_label = ''
		elif byte <= 0x0e:
			# TRIM
			(i,n) = (-16,0)
			while n < byte:
				i -= 1
				if survey.curr_label[i] == '.': n += 1
			survey.curr_label = survey.curr_label[:i + 1]
		elif byte <= 0x0f:
			# MOVE
			xyz = read_xyz()
			survey.move(xyz)
		elif byte <= 0x1f:
			# TRIM
			survey.curr_label = survey.curr_label[:15 - byte]
		elif byte <= 0x20:
			# DATE
			if ff_version < 7:
				skip_bytes(4)
			else:
				skip_bytes(2)
		elif byte <= 0x21:
			# DATE
			if ff_version < 7:
				skip_bytes(8)
			else:
				skip_bytes(3)
		elif byte <= 0x22:
			# Error info
			skip_bytes(5 * 4)
		elif byte <= 0x23:
			# DATE
			skip_bytes(4)
		elif byte <= 0x24:
			# DATE
			continue
		elif byte <= 0x2f:
			# Reserved
			continue
		elif byte <= 0x31:
			# XSECT
			read_label()
			skip_bytes(4 * 2)
		elif byte <= 0x33:
			# XSECT
			read_label()
			skip_bytes(4 * 4)
		elif byte <= 0x3f:
			# Reserved
			continue
		elif byte <= 0x7f:
			# LABEL
			read_label()
			xyz = read_xyz()
			survey.label(xyz)
		elif byte <= 0xbf:
			# LINE
			read_label()
			xyz = read_xyz()
			survey.line(xyz)
		elif byte <= 0xff:
			# Reserved
			continue

	model = models.Indexed()
	for s in survey:
		l0, _, l1 = s.labels[0].rpartition('.')
		resi, name = l1[:5], l1[5:]
#		segi, chain, resn = l0[:4],l0[-4:-3], l0[-3:]
		segi, chain, resn = l0[-8:-4], l0[-4:-3], l0[-3:]
		atom = Atom()
		atom.coord = [i/100.0 for i in s]
		atom.segi = segi
		atom.chain = chain
		atom.resn = resn
		atom.name = name
		atom.resi = resi
		atom.b = atom.coord[2]
		model.add_atom(atom)

	s2i = dict((s,i) for (i,s) in enumerate(survey))
	for s in survey:
		for o in s.adjacent:
			bnd = Bond()
			bnd.index = [s2i[s], s2i[o]]
			model.add_bond(bnd)

	cmd.load_model(model, object, 1)
	cmd.show_as('lines', object)
	cmd.spectrum('b', 'rainbow', object)