Skip to content

Support PDB charges in Atom class - #3857

Open
markf94 wants to merge 2 commits into
biopython:masterfrom
ProteinQure:atom_charges
Open

markf94 wants to merge 2 commits into
biopython:masterfrom
ProteinQure:atom_charges

Conversation

@markf94

@markf94 markf94 commented Feb 9, 2022 •

Copy link
Copy Markdown

The Atom class previously only supported atom/element charges for PQR
file formats. However, charges can also be indicated at the very end of
a line in PDB files such as:

ATOM      1  N   THR A   1     -17.147  31.805 -43.528  1.00  0.46           N1+

This MR enables parsing of these charges and also takes them into
consideration when writing PDB files using the PDBIO class. This leads
to more consistent results if a user reads a PDB file and then exports
it as PDB again (since they will expect the same ATOM lines). Closes #3856

To verify that this MR does what it is supposed to do, you can simply repeat the steps outlined in #3856 and verify that example-out.pdb now indeed contains the 1+ charge on the nitrogen atom.

Additionally, I added an if statement which throws a PDBConstructionException in case of duplicate atoms in PDB files. This is required since the current Biopython code silently deletes them without informing the user which can lead to difficult-to-debug scenarios and unexpected behaviours.

  • I hereby agree to dual licence this and any previous contributions under both
    the Biopython License Agreement AND the BSD 3-Clause License.

  • I have read the CONTRIBUTING.rst file, have run pre-commit
    locally, and understand that continuous integration checks will be used to
    confirm the Biopython unit tests and style checks pass with these changes.

  • I have added my name to the alphabetical contributors listings in the files
    NEWS.rst and CONTRIB.rst as part of this pull request, am listed
    already, or do not wish to be listed. (This acknowledgement is optional.)

@markf94

markf94 commented Feb 9, 2022

Copy link
Copy Markdown
Author

Will fix the tests once you signal interest in this contribution!

The Atom class previously only supported atom/element charges for PQR
file formats. However, charges can also be indicated at the very end of
a line in PDB files such as:

```
ATOM      1  N   THR A   1     -17.147  31.805 -43.528  1.00  0.46           N1+
```

This commit enables parsing of these charges and also takes them into
consideration when writing PDB files using the `PDBIO` class. This leads
to more consistent results if a user reads a PDB file and then exports
it as PDB again (since they will expect the same ATOM lines).
Duplicate atoms in residues happen frequently and Biopython used to
simply delete them silently without informing the user. This behaviour
is unexpected and leads to difficult to debug problems. This commit adds
an `if` statement which raises a `PDBConstructionException` in case of
duplicate atoms with same names.
@peterjc

peterjc commented Feb 11, 2022

Copy link
Copy Markdown
Member

There's a lot of test failures, quoting AppVeyor (Windows) here:

======================================================================
FAIL: test_disordered_cog (test_PDB_Disordered.TestDisordered)
Calculate DisorderedAtom center of geometry.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\projects\biopython\Tests\test_PDB_Disordered.py", line 137, in test_disordered_cog
    self.assertTrue(np.allclose(res_cog, [59.555, 21.033, 25.954], atol=1e-3))
AssertionError: False is not true
======================================================================
FAIL: test_remove_disordered_atom (test_PDB_Disordered.TestDisordered)
Remove altlocs from DisorderedAtom entities.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\projects\biopython\Tests\test_PDB_Disordered.py", line 185, in test_remove_disordered_atom
    self.assertEqual(disres.is_disordered(), 1)
AssertionError: 0 != 1
======================================================================
FAIL: test_structure_w_disordered_com (test_PDB_Disordered.TestDisordered)
Calculate center of mass of structure including DisorderedAtoms.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\projects\biopython\Tests\test_PDB_Disordered.py", line 121, in test_structure_w_disordered_com
    self.assertTrue(np.allclose(com, [54.545, 19.868, 31.212], atol=1e-3))
AssertionError: False is not true
======================================================================
ERROR: test_point_mutations_fast (test_PDB_MMCIFParser.ParseReal)
Test if FastMMCIFParser can parse point mutations correctly.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\projects\biopython\Tests\test_PDB_MMCIFParser.py", line 273, in test_point_mutations_fast
    self._run_point_mutation_tests(FastMMCIFParser(QUIET=True))
  File "C:\projects\biopython\Tests\test_PDB_MMCIFParser.py", line 277, in _run_point_mutation_tests
    structure = parser.get_structure("example", "PDB/3JQH.cif")
  File "C:\projects\biopython\build\lib.win32-3.9\Bio\PDB\MMCIFParser.py", line 397, in get_structure
    self._build_structure(structure_id, handle)
  File "C:\projects\biopython\build\lib.win32-3.9\Bio\PDB\MMCIFParser.py", line 592, in _build_structure
    structure_builder.init_atom(
  File "C:\projects\biopython\build\lib.win32-3.9\Bio\PDB\StructureBuilder.py", line 234, in init_atom
    raise PDBConstructionException(
Bio.PDB.PDBExceptions.PDBConstructionException: Duplicate atom CA in residue (' ', 3, ' ')
======================================================================
ERROR: test_point_mutations_main (test_PDB_MMCIFParser.ParseReal)
Test if MMCIFParser parse point mutations correctly.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\projects\biopython\Tests\test_PDB_MMCIFParser.py", line 269, in test_point_mutations_main
    self._run_point_mutation_tests(MMCIFParser(QUIET=True))
  File "C:\projects\biopython\Tests\test_PDB_MMCIFParser.py", line 277, in _run_point_mutation_tests
    structure = parser.get_structure("example", "PDB/3JQH.cif")
  File "C:\projects\biopython\build\lib.win32-3.9\Bio\PDB\MMCIFParser.py", line 74, in get_structure
    self._build_structure(structure_id)
  File "C:\projects\biopython\build\lib.win32-3.9\Bio\PDB\MMCIFParser.py", line 300, in _build_structure
    structure_builder.init_atom(
  File "C:\projects\biopython\build\lib.win32-3.9\Bio\PDB\StructureBuilder.py", line 234, in init_atom
    raise PDBConstructionException(
Bio.PDB.PDBExceptions.PDBConstructionException: Duplicate atom CA in residue (' ', 3, ' ')
======================================================================
ERROR: test_with_anisotrop (test_PDB_MMCIFParser.ParseReal)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\projects\biopython\Tests\test_PDB_MMCIFParser.py", line 150, in test_with_anisotrop
    structure = parser.get_structure("example", "PDB/4CUP.cif")
  File "C:\projects\biopython\build\lib.win32-3.9\Bio\PDB\MMCIFParser.py", line 74, in get_structure
    self._build_structure(structure_id)
  File "C:\projects\biopython\build\lib.win32-3.9\Bio\PDB\MMCIFParser.py", line 300, in _build_structure
    structure_builder.init_atom(
  File "C:\projects\biopython\build\lib.win32-3.9\Bio\PDB\StructureBuilder.py", line 234, in init_atom
    raise PDBConstructionException(
Bio.PDB.PDBExceptions.PDBConstructionException: Duplicate atom N in residue (' ', 1880, ' ')
======================================================================
FAIL: test_1_flawedpdb_permissive (test_PDB_PDBParser.FlawedPDB_tests)
Parse a flawed PDB file in permissive mode: check warnings.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\projects\biopython\Tests\test_PDB_PDBParser.py", line 55, in test_1_flawedpdb_permissive
    self.assertEqual(len(w), 15)
AssertionError: 38 != 15
======================================================================
FAIL: test_comparison_entities (test_PDB_SMCRA.SortingTests)
Test comparing and sorting the several SMCRA objects.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\projects\biopython\Tests\test_PDB_SMCRA.py", line 235, in test_comparison_entities
    self.assertEqual(atoms, ["A", "B"])
AssertionError: Lists differ: ['B'] != ['A', 'B']
First differing element 0:
'B'
'A'
Second list contains 1 additional elements.
First extra element 1:
'B'
- ['B']
+ ['A', 'B']
======================================================================
ERROR: test_bad_charge (test_PQR.ParseSimplePQR)
Test if missing or malformed charge case is handled correctly.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\projects\biopython\Tests\test_PQR.py", line 69, in test_bad_charge
    self.assertIsNone(atom.get_charge())
AttributeError: 'Atom' object has no attribute 'get_charge'
======================================================================
ERROR: test_single_input (test_PQR.ParseSimplePQR)
Test if a single ATOM entry correctly parsed.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\projects\biopython\Tests\test_PQR.py", line 36, in test_single_input
    self.assertEqual(atom.get_charge(), -0.1)
AttributeError: 'Atom' object has no attribute 'get_charge'
----------------------------------------------------------------------
Ran 534 tests in 384.461 seconds

Also something in the tests needs to silence PDBConstructionWarning while it is doing whatever it is doing (there are examples of this already using the warnings module context manager).

@peterjc

peterjc commented Feb 11, 2022

Copy link
Copy Markdown
Member

Not having looked at the file contents, this is likely a naive question - but do we really need pdb_charge and pqr_charge, can they not be combined?

@markf94

markf94 commented Mar 4, 2022

Copy link
Copy Markdown
Author

Not having looked at the file contents, this is likely a naive question - but do we really need pdb_charge and pqr_charge, can they not be combined?

@peterjc I don't think these can be combined since the pqr_charge is a of a different format and only defined when ingesting a .pqr file rather than a .pdb file. As you can see in this explanation a PQR file charge is of type float. However, in the definition of the PDB file format the charge is an int/str e.g., 2+, 1-.

I haven't had time to fix the tests yet but will definitely do next week!

@JoaoRodrigues

Copy link
Copy Markdown
Member

PQR charges are partial charges, while PDB charges are formal charges (integers). They've got different meanings.

@peterjc

peterjc commented Mar 6, 2022

Copy link
Copy Markdown
Member

Thanks for the clarification - adding something like that to the docstrings would be great 👍

@linminhtoo

Copy link
Copy Markdown

hello, may I enquire on the status of this? this is a much needed feature for my use-case, and I'll be happy to help if possible

@peterjc

peterjc commented Nov 21, 2022

Copy link
Copy Markdown
Member

Perhaps you (@linminhtoo) can pickup where @markf94 left off? The tests need working on, and I'd like the meaning of the two different charges explained in the docstring.

Are you familiar enough with git to handle updating a copy of this branch with the changes on the master branch?

@rob-miller rob-miller mentioned this pull request Nov 22, 2022
3 tasks done
@Vlad-o-S

Vlad-o-S commented Oct 4, 2024 •

Copy link
Copy Markdown

For those eager to have the PDB charge available as atom (and residue) attribute, you can use the following function. Its' pretty self explanatory. Both atom and residue objects will have attribute charge. So, access as atom.charge or residue.charge. The residue charge is the sum of corresponding atom charges. We presuppose that you have correct charges in your pdb_file, otherwise all will be zeros.

The alt_loc was added for my purposes - you may want to handle it specifically to your needs. But as long as you don't have alternate locations, this will work.

`
def Add_pdb_charge_biopy(pdb_file, structure, alt_loc='A'):
'''
Add attribute charge to atom and residue objects in Bio.PBD
class structure.
We presuppose there is no discontinuous chains (A, B, again A,...).

Parameters
----------
pdb_file : str
    The pdb file that corresponds to parameter 'structure'.
   
structure : Bio.PDB.Structure.Structure class, holds the PDB stucture in this biopython object.
    https://biopython.org/wiki/The_Biopython_Structural_Bioinformatics_FAQ

alt_loc : str, 
    character for alternate location, by default location ' ', and A is accepted

Returns
-------
structure : Bio.PDB.Structure.Structure class
    atom object and residue object have attribute charge.
'''

AQ = []

with open(pdb_file) as file:
    for line in file:
        if line[0:6] == 'ATOM  ' or line[0:6] == 'HETATM':
            
            loc = line[16:17]
                
            if loc == ' ' or loc == alt_loc:
                
                    q = line[78].strip()
                    s = line[79].strip()
                    #print('-',s+q,'-')
                    
                    try:
                        ch = int(s+q)
                    except:
                        ch = 0
                
                    AQ.append(ch)

file.close()

# Set atom charge as in PDB file - not supported !!!
# Atom will have new attibute 'charge' as opposed to 
# pqr_charge, which is reserved for PQR charges.
# https://github.com/biopython/biopython/pull/3857
for i, atm in enumerate(structure.get_atoms()):
    atm.charge = AQ[i]

# Estimate residue charge and set as attribute
for res in structure.get_residues():
    tmp = []
    for atm in res.get_atoms():
        tmp.append(atm.charge)
    #print(tmp)
    res.charge = sum(tmp)

return structure

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PDB atom charges are not supported

5 participants