def __init__(self, PERMISSIVE=True, get_header=False, structure_builder=None, QUIET=False): """ The PDB parser call a number of standard methods in an aggregated StructureBuilder object. Normally this object is instanciated by the PDBParser object itself, but if the user provides his own StructureBuilder object, the latter is used instead. Arguments: o PERMISSIVE - Evaluated as a Boolean. If false, exceptions in constructing the SMCRA data structure are fatal. If true (DEFAULT), the exceptions are caught, but some residues or atoms will be missing. THESE EXCEPTIONS ARE DUE TO PROBLEMS IN THE PDB FILE!. o structure_builder - an optional user implemented StructureBuilder class. o QUIET - Evaluated as a Boolean. If true, warnings issued in constructing the SMCRA data will be supressed. If false (DEFAULT), they will be shown. These warnings might be indicative of problems in the PDB file! """ if structure_builder != None: self.structure_builder = structure_builder else: self.structure_builder = StructureBuilder() self.header = None self.trailer = None self.line_counter = 0 self.PERMISSIVE = bool(PERMISSIVE) self.QUIET = bool(QUIET)
def __init__(self, PERMISSIVE=True, get_header=False, structure_builder=None, QUIET=False): """ The PDB parser call a number of standard methods in an aggregated StructureBuilder object. Normally this object is instanciated by the PDBParser object itself, but if the user provides his own StructureBuilder object, the latter is used instead. Arguments: o PERMISSIVE - Evaluated as a Boolean. If false, exceptions in constructing the SMCRA data structure are fatal. If true (DEFAULT), the exceptions are caught, but some residues or atoms will be missing. THESE EXCEPTIONS ARE DUE TO PROBLEMS IN THE PDB FILE!. o structure_builder - an optional user implemented StructureBuilder class. o QUIET - Evaluated as a Boolean. If true, warnings issued in constructing the SMCRA data will be supressed. If false (DEFAULT), they will be shown. These warnings might be indicative of problems in the PDB file! """ if structure_builder!=None: self.structure_builder=structure_builder else: self.structure_builder=StructureBuilder() self.header=None self.trailer=None self.line_counter=0 self.PERMISSIVE=bool(PERMISSIVE) self.QUIET=bool(QUIET)
def __init__(self, PERMISSIVE=1, get_header=0, structure_builder=None): """ The PDB parser call a number of standard methods in an aggregated StructureBuilder object. Normally this object is instanciated by the PDBParser object itself, but if the user provides his own StructureBuilder object, the latter is used instead. Arguments: o PERMISSIVE - int, if this is 0 exceptions in constructing the SMCRA data structure are fatal. If 1 (DEFAULT), the exceptions are caught, but some residues or atoms will be missing. THESE EXCEPTIONS ARE DUE TO PROBLEMS IN THE PDB FILE!. o structure_builder - an optional user implemented StructureBuilder class. """ if structure_builder!=None: self.structure_builder=structure_builder else: self.structure_builder=StructureBuilder() self.header=None self.trailer=None self.line_counter=0 self.PERMISSIVE=PERMISSIVE
class PDBParser(object): """ Parse a PDB file and return a Structure object. """ def __init__(self, PERMISSIVE=True, get_header=False, structure_builder=None, QUIET=False): """ The PDB parser call a number of standard methods in an aggregated StructureBuilder object. Normally this object is instanciated by the PDBParser object itself, but if the user provides his own StructureBuilder object, the latter is used instead. Arguments: o PERMISSIVE - Evaluated as a Boolean. If false, exceptions in constructing the SMCRA data structure are fatal. If true (DEFAULT), the exceptions are caught, but some residues or atoms will be missing. THESE EXCEPTIONS ARE DUE TO PROBLEMS IN THE PDB FILE!. o structure_builder - an optional user implemented StructureBuilder class. o QUIET - Evaluated as a Boolean. If true, warnings issued in constructing the SMCRA data will be supressed. If false (DEFAULT), they will be shown. These warnings might be indicative of problems in the PDB file! """ if structure_builder != None: self.structure_builder = structure_builder else: self.structure_builder = StructureBuilder() self.header = None self.trailer = None self.line_counter = 0 self.PERMISSIVE = bool(PERMISSIVE) self.QUIET = bool(QUIET) # Public methods def get_structure(self, id, file): """Return the structure. Arguments: o id - string, the id that will be used for the structure o file - name of the PDB file OR an open filehandle """ if self.QUIET: warning_list = warnings.filters[:] warnings.filterwarnings('ignore', category=PDBConstructionWarning) self.header = None self.trailer = None # Make a StructureBuilder instance (pass id of structure as parameter) self.structure_builder.init_structure(id) handle_close = False if isinstance(file, basestring): file = open(file) handle_close = True self._parse(file.readlines()) self.structure_builder.set_header(self.header) # Return the Structure instance structure = self.structure_builder.get_structure() if handle_close: file.close() if self.QUIET: warnings.filters = warning_list return structure def get_header(self): "Return the header." return self.header def get_trailer(self): "Return the trailer." return self.trailer # Private methods def _parse(self, header_coords_trailer): "Parse the PDB file." # Extract the header; return the rest of the file self.header, coords_trailer = self._get_header(header_coords_trailer) # Parse the atomic data; return the PDB file trailer self.trailer = self._parse_coordinates(coords_trailer) def _get_header(self, header_coords_trailer): "Get the header of the PDB file, return the rest." structure_builder = self.structure_builder i = 0 for i in range(0, len(header_coords_trailer)): structure_builder.set_line_counter(i + 1) line = header_coords_trailer[i] record_type = line[0:6] if (record_type == 'ATOM ' or record_type == 'HETATM' or record_type == 'MODEL '): break header = header_coords_trailer[0:i] # Return the rest of the coords+trailer for further processing self.line_counter = i coords_trailer = header_coords_trailer[i:] header_dict = _parse_pdb_header_list(header) return header_dict, coords_trailer def _parse_coordinates(self, coords_trailer): "Parse the atomic data in the PDB file." local_line_counter = 0 structure_builder = self.structure_builder current_model_id = 0 # Flag we have an open model model_open = 0 current_chain_id = None current_segid = None current_residue_id = None current_resname = None for i in range(0, len(coords_trailer)): line = coords_trailer[i] record_type = line[0:6] global_line_counter = self.line_counter + local_line_counter + 1 structure_builder.set_line_counter(global_line_counter) if (record_type == 'ATOM ' or record_type == 'HETATM'): # Initialize the Model - there was no explicit MODEL record if not model_open: structure_builder.init_model(current_model_id) current_model_id += 1 model_open = 1 fullname = line[12:16] # get rid of whitespace in atom names split_list = fullname.split() if len(split_list) != 1: # atom name has internal spaces, e.g. " N B ", so # we do not strip spaces name = fullname else: # atom name is like " CA ", so we can strip spaces name = split_list[0] altloc = line[16:17] resname = line[17:20] chainid = line[21:22] try: serial_number = int(line[6:11]) except: serial_number = 0 resseq = int(line[22:26].split()[0]) # sequence identifier icode = line[26:27] # insertion code if record_type == 'HETATM': # hetero atom flag if resname == "HOH" or resname == "WAT": hetero_flag = "W" else: hetero_flag = "H" else: hetero_flag = " " residue_id = (hetero_flag, resseq, icode) # atomic coordinates try: x = float(line[30:38]) y = float(line[38:46]) z = float(line[46:54]) except: #Should we allow parsing to continue in permissive mode? #If so what coordindates should we default to? Easier to abort! raise PDBConstructionException(\ "Invalid or missing coordinate(s) at line %i." \ % global_line_counter) coord = numpy.array((x, y, z), 'f') # occupancy & B factor try: occupancy = float(line[54:60]) except: self._handle_PDB_exception("Invalid or missing occupancy", global_line_counter) occupancy = 0.0 #Is one or zero a good default? try: bfactor = float(line[60:66]) except: self._handle_PDB_exception("Invalid or missing B factor", global_line_counter) bfactor = 0.0 #The PDB use a default of zero if the data is missing segid = line[72:76] element = line[76:78].strip() if current_segid != segid: current_segid = segid structure_builder.init_seg(current_segid) if current_chain_id != chainid: current_chain_id = chainid structure_builder.init_chain(current_chain_id) current_residue_id = residue_id current_resname = resname try: structure_builder.init_residue(resname, hetero_flag, resseq, icode) except PDBConstructionException, message: self._handle_PDB_exception(message, global_line_counter) elif current_residue_id != residue_id or current_resname != resname: current_residue_id = residue_id current_resname = resname try: structure_builder.init_residue(resname, hetero_flag, resseq, icode) except PDBConstructionException, message: self._handle_PDB_exception(message, global_line_counter) # init atom try: structure_builder.init_atom(name, coord, bfactor, occupancy, altloc, fullname, serial_number, element) except PDBConstructionException, message: self._handle_PDB_exception(message, global_line_counter)
class PDBParser: """ Parse a PDB file and return a Structure object. """ def __init__(self, PERMISSIVE=1, get_header=0, structure_builder=None): """ The PDB parser call a number of standard methods in an aggregated StructureBuilder object. Normally this object is instanciated by the PDBParser object itself, but if the user provides his own StructureBuilder object, the latter is used instead. Arguments: o PERMISSIVE - int, if this is 0 exceptions in constructing the SMCRA data structure are fatal. If 1 (DEFAULT), the exceptions are caught, but some residues or atoms will be missing. THESE EXCEPTIONS ARE DUE TO PROBLEMS IN THE PDB FILE!. o structure_builder - an optional user implemented StructureBuilder class. """ if structure_builder!=None: self.structure_builder=structure_builder else: self.structure_builder=StructureBuilder() self.header=None self.trailer=None self.line_counter=0 self.PERMISSIVE=PERMISSIVE # Public methods def get_structure(self, id, file): """Return the structure. Arguments: o id - string, the id that will be used for the structure o file - name of the PDB file OR an open filehandle """ self.header=None self.trailer=None # Make a StructureBuilder instance (pass id of structure as parameter) self.structure_builder.init_structure(id) if isinstance(file, basestring): file=open(file) self._parse(file.readlines()) self.structure_builder.set_header(self.header) # Return the Structure instance return self.structure_builder.get_structure() def get_header(self): "Return the header." return self.header def get_trailer(self): "Return the trailer." return self.trailer # Private methods def _parse(self, header_coords_trailer): "Parse the PDB file." # Extract the header; return the rest of the file self.header, coords_trailer=self._get_header(header_coords_trailer) # Parse the atomic data; return the PDB file trailer self.trailer=self._parse_coordinates(coords_trailer) def _get_header(self, header_coords_trailer): "Get the header of the PDB file, return the rest." structure_builder=self.structure_builder for i in range(0, len(header_coords_trailer)): structure_builder.set_line_counter(i+1) line=header_coords_trailer[i] record_type=line[0:6] if(record_type=='ATOM ' or record_type=='HETATM' or record_type=='MODEL '): break header=header_coords_trailer[0:i] # Return the rest of the coords+trailer for further processing self.line_counter=i coords_trailer=header_coords_trailer[i:] header_dict=_parse_pdb_header_list(header) return header_dict, coords_trailer def _parse_coordinates(self, coords_trailer): "Parse the atomic data in the PDB file." local_line_counter=0 structure_builder=self.structure_builder current_model_id=0 # Flag we have an open model model_open=0 current_chain_id=None current_segid=None current_residue_id=None current_resname=None for i in range(0, len(coords_trailer)): line=coords_trailer[i] record_type=line[0:6] global_line_counter=self.line_counter+local_line_counter+1 structure_builder.set_line_counter(global_line_counter) if(record_type=='ATOM ' or record_type=='HETATM'): # Initialize the Model - there was no explicit MODEL record if not model_open: structure_builder.init_model(current_model_id) current_model_id+=1 model_open=1 fullname=line[12:16] # get rid of whitespace in atom names split_list=fullname.split() if len(split_list)!=1: # atom name has internal spaces, e.g. " N B ", so # we do not strip spaces name=fullname else: # atom name is like " CA ", so we can strip spaces name=split_list[0] altloc=line[16:17] resname=line[17:20] chainid=line[21:22] try: serial_number=int(line[6:11]) except: serial_number=0 resseq=int(line[22:26].split()[0]) # sequence identifier icode=line[26:27] # insertion code if record_type=='HETATM': # hetero atom flag if resname=="HOH" or resname=="WAT": hetero_flag="W" else: hetero_flag="H" else: hetero_flag=" " residue_id=(hetero_flag, resseq, icode) # atomic coordinates try: x=float(line[30:38]) y=float(line[38:46]) z=float(line[46:54]) except: #Should we allow parsing to continue in permissive mode? #If so what coordindates should we default to? Easier to abort! raise PDBContructionError("Invalid or missing coordinate(s) at line %i." \ % global_line_counter) coord=numpy.array((x, y, z), 'f') # occupancy & B factor try: occupancy=float(line[54:60]) except: self._handle_PDB_exception("Invalid or missing occupancy", global_line_counter) occupancy = 0.0 #Is one or zero a good default? try: bfactor=float(line[60:66]) except: self._handle_PDB_exception("Invalid or missing B factor", global_line_counter) bfactor = 0.0 #The PDB use a default of zero if the data is missing segid=line[72:76] element=line[76:78].strip() if current_segid!=segid: current_segid=segid structure_builder.init_seg(current_segid) if current_chain_id!=chainid: current_chain_id=chainid structure_builder.init_chain(current_chain_id) current_residue_id=residue_id current_resname=resname try: structure_builder.init_residue(resname, hetero_flag, resseq, icode) except PDBConstructionException, message: self._handle_PDB_exception(message, global_line_counter) elif current_residue_id!=residue_id or current_resname!=resname: current_residue_id=residue_id current_resname=resname try: structure_builder.init_residue(resname, hetero_flag, resseq, icode) except PDBConstructionException, message: self._handle_PDB_exception(message, global_line_counter) # init atom try: structure_builder.init_atom(name, coord, bfactor, occupancy, altloc, fullname, serial_number, element) except PDBConstructionException, message: self._handle_PDB_exception(message, global_line_counter)
def get_structure(self, structure_id, filename): self._mmcif_dict=MMCIF2Dict(filename) self._structure_builder=StructureBuilder() self._build_structure(structure_id) return self._structure_builder.get_structure()
class MMCIFParser: def get_structure(self, structure_id, filename): self._mmcif_dict=MMCIF2Dict(filename) self._structure_builder=StructureBuilder() self._build_structure(structure_id) return self._structure_builder.get_structure() def _build_structure(self, structure_id): mmcif_dict=self._mmcif_dict atom_id_list=mmcif_dict["_atom_site.label_atom_id"] residue_id_list=mmcif_dict["_atom_site.label_comp_id"] seq_id_list=mmcif_dict["_atom_site.label_seq_id"] chain_id_list=mmcif_dict["_atom_site.label_asym_id"] x_list=map(float, mmcif_dict["_atom_site.Cartn_x"]) y_list=map(float, mmcif_dict["_atom_site.Cartn_y"]) z_list=map(float, mmcif_dict["_atom_site.Cartn_z"]) alt_list=mmcif_dict["_atom_site.label_alt_id"] b_factor_list=mmcif_dict["_atom_site.B_iso_or_equiv"] occupancy_list=mmcif_dict["_atom_site.occupancy"] fieldname_list=mmcif_dict["_atom_site.group_PDB"] try: aniso_u11=mmcif_dict["_atom_site.aniso_U[1][1]"] aniso_u12=mmcif_dict["_atom_site.aniso_U[1][2]"] aniso_u13=mmcif_dict["_atom_site.aniso_U[1][3]"] aniso_u22=mmcif_dict["_atom_site.aniso_U[2][2]"] aniso_u23=mmcif_dict["_atom_site.aniso_U[2][3]"] aniso_u33=mmcif_dict["_atom_site.aniso_U[3][3]"] aniso_flag=1 except KeyError: # no anisotropic B factors aniso_flag=0 # if auth_seq_id is present, we use this. # Otherwise label_seq_id is used. if mmcif_dict.has_key("_atom_site.auth_seq_id"): seq_id_list=mmcif_dict["_atom_site.auth_seq_id"] else: seq_id_list=mmcif_dict["_atom_site.label_seq_id"] # Now loop over atoms and build the structure current_chain_id=None current_residue_id=None current_model_id=0 structure_builder=self._structure_builder structure_builder.init_structure(structure_id) structure_builder.init_model(current_model_id) structure_builder.init_seg(" ") for i in xrange(0, len(atom_id_list)): x=x_list[i] y=y_list[i] z=z_list[i] resname=residue_id_list[i] chainid=chain_id_list[i] altloc=alt_list[i] if altloc==".": altloc=" " resseq=seq_id_list[i] name=atom_id_list[i] tempfactor=b_factor_list[i] occupancy=occupancy_list[i] fieldname=fieldname_list[i] if fieldname=="HETATM": hetatm_flag="H" else: hetatm_flag=" " if current_chain_id!=chainid: current_chain_id=chainid structure_builder.init_chain(current_chain_id) current_residue_id=resseq icode, int_resseq=self._get_icode(resseq) structure_builder.init_residue(resname, hetatm_flag, int_resseq, icode) elif current_residue_id!=resseq: current_residue_id=resseq icode, int_resseq=self._get_icode(resseq) structure_builder.init_residue(resname, hetatm_flag, int_resseq, icode) coord=numpy.array((x, y, z), 'f') structure_builder.init_atom(name, coord, tempfactor, occupancy, altloc, name) if aniso_flag==1: u=(aniso_u11[i], aniso_u12[i], aniso_u13[i], aniso_u22[i], aniso_u23[i], aniso_u33[i]) mapped_anisou=map(float, u) anisou_array=numpy.array(mapped_anisou, 'f') structure_builder.set_anisou(anisou_array) # Now try to set the cell try: a=float(mmcif_dict["_cell.length_a"]) b=float(mmcif_dict["_cell.length_b"]) c=float(mmcif_dict["_cell.length_c"]) alpha=float(mmcif_dict["_cell.angle_alpha"]) beta=float(mmcif_dict["_cell.angle_beta"]) gamma=float(mmcif_dict["_cell.angle_gamma"]) cell=numpy.array((a, b, c, alpha, beta, gamma), 'f') spacegroup=mmcif_dict["_symmetry.space_group_name_H-M"] spacegroup=spacegroup[1:-1] # get rid of quotes!! if spacegroup==None: raise Exception structure_builder.set_symmetry(spacegroup, cell) except: pass # no cell found, so just ignore def _get_icode(self, resseq): """Tries to return the icode. In MMCIF files this is just part of resseq! In PDB files, it's a separate field.""" last_resseq_char=resseq[-1] if last_resseq_char in letters: icode=last_resseq_char int_resseq=int(resseq[0:-1]) else: icode=" " int_resseq=int(resseq) return icode, int_resseq
def get_structure(self, structure_id, filename): self._mmcif_dict = MMCIF2Dict(filename) self._structure_builder = StructureBuilder() self._build_structure(structure_id) return self._structure_builder.get_structure()
class MMCIFParser: def get_structure(self, structure_id, filename): self._mmcif_dict = MMCIF2Dict(filename) self._structure_builder = StructureBuilder() self._build_structure(structure_id) return self._structure_builder.get_structure() def _build_structure(self, structure_id): mmcif_dict = self._mmcif_dict atom_id_list = mmcif_dict["_atom_site.label_atom_id"] residue_id_list = mmcif_dict["_atom_site.label_comp_id"] seq_id_list = mmcif_dict["_atom_site.label_seq_id"] chain_id_list = mmcif_dict["_atom_site.label_asym_id"] x_list = map(float, mmcif_dict["_atom_site.Cartn_x"]) y_list = map(float, mmcif_dict["_atom_site.Cartn_y"]) z_list = map(float, mmcif_dict["_atom_site.Cartn_z"]) alt_list = mmcif_dict["_atom_site.label_alt_id"] b_factor_list = mmcif_dict["_atom_site.B_iso_or_equiv"] occupancy_list = mmcif_dict["_atom_site.occupancy"] fieldname_list = mmcif_dict["_atom_site.group_PDB"] try: aniso_u11 = mmcif_dict["_atom_site.aniso_U[1][1]"] aniso_u12 = mmcif_dict["_atom_site.aniso_U[1][2]"] aniso_u13 = mmcif_dict["_atom_site.aniso_U[1][3]"] aniso_u22 = mmcif_dict["_atom_site.aniso_U[2][2]"] aniso_u23 = mmcif_dict["_atom_site.aniso_U[2][3]"] aniso_u33 = mmcif_dict["_atom_site.aniso_U[3][3]"] aniso_flag = 1 except KeyError: # no anisotropic B factors aniso_flag = 0 # if auth_seq_id is present, we use this. # Otherwise label_seq_id is used. if mmcif_dict.has_key("_atom_site.auth_seq_id"): seq_id_list = mmcif_dict["_atom_site.auth_seq_id"] else: seq_id_list = mmcif_dict["_atom_site.label_seq_id"] # Now loop over atoms and build the structure current_chain_id = None current_residue_id = None current_model_id = 0 structure_builder = self._structure_builder structure_builder.init_structure(structure_id) structure_builder.init_model(current_model_id) structure_builder.init_seg(" ") for i in xrange(0, len(atom_id_list)): x = x_list[i] y = y_list[i] z = z_list[i] resname = residue_id_list[i] chainid = chain_id_list[i] altloc = alt_list[i] if altloc == ".": altloc = " " resseq = seq_id_list[i] name = atom_id_list[i] tempfactor = b_factor_list[i] occupancy = occupancy_list[i] fieldname = fieldname_list[i] if fieldname == "HETATM": hetatm_flag = "H" else: hetatm_flag = " " if current_chain_id != chainid: current_chain_id = chainid structure_builder.init_chain(current_chain_id) current_residue_id = resseq icode, int_resseq = self._get_icode(resseq) structure_builder.init_residue(resname, hetatm_flag, int_resseq, icode) elif current_residue_id != resseq: current_residue_id = resseq icode, int_resseq = self._get_icode(resseq) structure_builder.init_residue(resname, hetatm_flag, int_resseq, icode) coord = numpy.array((x, y, z), 'f') structure_builder.init_atom(name, coord, tempfactor, occupancy, altloc, name) if aniso_flag == 1: u = (aniso_u11[i], aniso_u12[i], aniso_u13[i], aniso_u22[i], aniso_u23[i], aniso_u33[i]) mapped_anisou = map(float, u) anisou_array = numpy.array(mapped_anisou, 'f') structure_builder.set_anisou(anisou_array) # Now try to set the cell try: a = float(mmcif_dict["_cell.length_a"]) b = float(mmcif_dict["_cell.length_b"]) c = float(mmcif_dict["_cell.length_c"]) alpha = float(mmcif_dict["_cell.angle_alpha"]) beta = float(mmcif_dict["_cell.angle_beta"]) gamma = float(mmcif_dict["_cell.angle_gamma"]) cell = numpy.array((a, b, c, alpha, beta, gamma), 'f') spacegroup = mmcif_dict["_symmetry.space_group_name_H-M"] spacegroup = spacegroup[1:-1] # get rid of quotes!! if spacegroup == None: raise Exception structure_builder.set_symmetry(spacegroup, cell) except: pass # no cell found, so just ignore def _get_icode(self, resseq): """Tries to return the icode. In MMCIF files this is just part of resseq! In PDB files, it's a separate field.""" last_resseq_char = resseq[-1] if last_resseq_char in letters: icode = last_resseq_char int_resseq = int(resseq[0:-1]) else: icode = " " int_resseq = int(resseq) return icode, int_resseq