[docs]defwrite(self,selection,frame=None):"""Write selection at current trajectory frame to file. Parameters ---------- selection : AtomGroup group of atoms to be written frame : int (optional) Move the trajectory to frame `frame`; by default, write the current frame. """u=selection.universeifframeisnotNone:u.trajectory[frame]# advance to frameelse:try:frame=u.trajectory.ts.frameexceptAttributeError:frame=0# should catch cases when we are analyzing a single PDB (?)atoms=selection.atoms# make sure to use atoms (Issue 46)coor=atoms.positions# can write from selection == Universe (Issue 49)n_atoms=len(atoms)# Detect which format string we're using to output (EXT or not)# *len refers to how to truncate various things,# depending on output format!ifn_atoms>99999:at_fmt=self.fmt['ATOM_EXT']serial_len=10resid_len=8totres_len=10else:at_fmt=self.fmt['ATOM']serial_len=5resid_len=4totres_len=5# Check for attributes, use defaults for missing onesattrs={}missing_topology=[]forattr,defaultin(('resnames',itertools.cycle(('UNK',))),# Resids *must* be an array because we index it later('resids',np.ones(n_atoms,dtype=np.int)),('names',itertools.cycle(('X',))),('tempfactors',itertools.cycle((0.0,))),):try:attrs[attr]=getattr(atoms,attr)except(NoDataError,AttributeError):attrs[attr]=defaultmissing_topology.append(attr)# ChainIDs - Try ChainIDs first, fall back to Segidstry:attrs['chainIDs']=atoms.chainIDsexcept(NoDataError,AttributeError):# try looking for segids insteadtry:attrs['chainIDs']=atoms.segidsexcept(NoDataError,AttributeError):attrs['chainIDs']=itertools.cycle(('',))missing_topology.append(attr)ifmissing_topology:warnings.warn("Supplied AtomGroup was missing the following attributes: ""{miss}. These will be written with default values. """.format(miss=', '.join(missing_topology)))withutil.openany(self.filename,'w')ascrd:# Write Titlecrd.write(self.fmt['TITLE'].format(frame=frame,where=u.trajectory.filename))crd.write("*\n")# Write NUMATOMSifn_atoms>99999:crd.write(self.fmt['NUMATOMS_EXT'].format(n_atoms))else:crd.write(self.fmt['NUMATOMS'].format(n_atoms))# Write all atomscurrent_resid=1resids=attrs['resids']fori,pos,resname,name,chainID,resid,tempfactorinzip(range(n_atoms),coor,attrs['resnames'],attrs['names'],attrs['chainIDs'],attrs['resids'],attrs['tempfactors']):ifnoti==0andresids[i]!=resids[i-1]:current_resid+=1# Truncate numbersserial=util.ltruncate_int(i+1,serial_len)resid=util.ltruncate_int(resid,resid_len)current_resid=util.ltruncate_int(current_resid,totres_len)crd.write(at_fmt.format(serial=serial,totRes=current_resid,resname=resname,name=name,pos=pos,chainID=chainID,resSeq=resid,tempfactor=tempfactor))