Skip to content

Commit

Permalink
Merge pull request #411 from kiyoon/refactor/ruff-lint-rules
Browse files Browse the repository at this point in the history
refactor: fix lint and some type issues
  • Loading branch information
sobolevnrm authored Dec 15, 2024
2 parents ba9624c + b1ad798 commit 2e8b98f
Show file tree
Hide file tree
Showing 30 changed files with 211 additions and 223 deletions.
6 changes: 1 addition & 5 deletions pdb2pqr/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,11 @@
"""

import logging
from sys import version_info

from pdb2pqr.main import main

assert version_info >= (3, 5)


_LOGGER = logging.getLogger(__name__)
logging.captureWarnings(True)
logging.captureWarnings(capture=True)


if __name__ == "__main__":
Expand Down
1 change: 1 addition & 0 deletions pdb2pqr/_version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""PDB2PQR Version number.
Store the version here so:
* we don't load dependencies by storing it in :file:`__init__.py`
Expand Down
16 changes: 5 additions & 11 deletions pdb2pqr/aa.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,6 @@ def set_state(self):
self.ffname = f"NEUTRAL-C{self.ffname}"
else:
self.ffname = f"C{self.ffname}"
return

def rebuild_tetrahedral(self, atomname):
"""Rebuild a tetrahedral hydrogen group.
Expand Down Expand Up @@ -167,7 +166,7 @@ def rebuild_tetrahedral(self, atomname):
for bond in self.reference.map[bondname].bonds:
if bond.startswith("H"):
hcount += 1
elif bond != "C-1" and bond != "N+1":
elif bond not in ("C-1", "N+1"):
nextatomname = bond
# Check if this is a tetrahedral group
if hcount != 3 or nextatomname is None:
Expand Down Expand Up @@ -275,7 +274,7 @@ def __init__(self, atoms, ref):
Amino.__init__(self, atoms, ref)
self.reference = ref

def letter_code(self):
def letter_code(self) -> str:
"""Return letter code for amino acid.
:return: amino acid 1-letter code
Expand Down Expand Up @@ -407,9 +406,7 @@ def set_state(self):
If SS-bonded, use CYX. If negatively charged, use CYM. If HG is not
present, use CYX.
"""
if "CYX" in self.patches or self.name == "CYX":
self.ffname = "CYX"
elif self.ss_bonded:
if "CYX" in self.patches or self.name == "CYX" or self.ss_bonded:
self.ffname = "CYX"
elif "CYM" in self.patches or self.name == "CYM":
self.ffname = "CYM"
Expand Down Expand Up @@ -548,10 +545,7 @@ def set_state(self):
elif (
self.get_atom("NE2").hdonor
and not self.get_atom("NE2").hacceptor
):
if self.has_atom("HD1"):
self.remove_atom("HD1")
elif (
) or (
self.get_atom("ND1").hacceptor
and not self.get_atom("ND1").hdonor
):
Expand All @@ -568,7 +562,7 @@ def set_state(self):
self.ffname = "HIE"
else:
errstr = (
f"Invalid type for {str(self)}! Missing both HD1 and HE2 "
f"Invalid type for {self!s}! Missing both HD1 and HE2 "
"atoms. If you receive this error while using the "
"--assign-only option you can only resolve it by adding HD1, "
"HE2 or both to this residue."
Expand Down
65 changes: 36 additions & 29 deletions pdb2pqr/biomolecule.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,23 +55,27 @@ def __init__(self, pdblist, definition):
num_chains += 1
for record in pdblist:
if isinstance(record, (pdb.ATOM, pdb.HETATM)):
if record.chain_id == "":
if num_chains > 1 and record.res_name not in [
if (
record.chain_id == ""
and num_chains > 1
and record.res_name
not in [
"WAT",
"HOH",
]:
# Assign a chain ID
try:
record.chain_id = (
string.ascii_uppercase
+ string.ascii_lowercase
+ string.digits
)[count]
except IndexError:
raise Exception(
"Too many chains exist in biomolecule. "
"Consider preparing subsets."
)
]
):
# Assign a chain ID
try:
record.chain_id = (
string.ascii_uppercase
+ string.ascii_lowercase
+ string.digits
)[count]
except IndexError:
raise Exception(
"Too many chains exist in biomolecule. "
"Consider preparing subsets."
)

chain_id = record.chain_id
res_seq = record.res_seq
Expand Down Expand Up @@ -221,7 +225,7 @@ def set_hip(self):
if isinstance(residue, aa.HIS):
self.apply_patch("HIP", residue)

def set_termini(self, neutraln=False, neutralc=False):
def set_termini(self, *, neutraln=False, neutralc=False):
"""Set the termini for a protein.
First set all known termini by looking at the ends of the chain. Then
Expand All @@ -237,7 +241,7 @@ def set_termini(self, neutraln=False, neutralc=False):
# First assign the known termini
chain = None
for chain in self.chains:
self.assign_termini(chain, neutraln, neutralc)
self.assign_termini(chain, neutraln=neutraln, neutralc=neutralc)
# Now determine if there are any hidden chains
letters = string.ascii_uppercase + string.ascii_lowercase
ch_num = 0
Expand All @@ -255,11 +259,12 @@ def set_termini(self, neutraln=False, neutralc=False):
if isinstance(residue, aa.Amino):
if residue.has_atom("OXT") and not residue.is_c_term:
fixflag = 1
elif isinstance(residue, na.Nucleic):
if (
residue.has_atom("H3T") or residue.name.endswith("3")
) and not residue.is3term:
fixflag = 1
elif (
isinstance(residue, na.Nucleic)
and (residue.has_atom("H3T") or residue.name.endswith("3"))
and not residue.is3term
):
fixflag = 1
if fixflag:
# Get an available chain ID
chainid = letters[0]
Expand All @@ -284,8 +289,12 @@ def set_termini(self, neutraln=False, neutralc=False):
newchain.add_residue(res)
chain.residues.remove(res)
res.set_chain_id(chainid[0])
self.assign_termini(chain, neutraln, neutralc)
self.assign_termini(newchain, neutraln, neutralc)
self.assign_termini(
chain, neutraln=neutraln, neutralc=neutralc
)
self.assign_termini(
newchain, neutraln=neutraln, neutralc=neutralc
)
reslist = []
ch_num += 1
ch_num += 1
Expand Down Expand Up @@ -459,9 +468,7 @@ def set_reference_distance(self):
atom.refdistance = -1
elif residue.is_c_term and atom.name == "HO":
atom.refdistance = 3
elif residue.is_n_term and (
atom.name == "H3" or atom.name == "H2"
):
elif residue.is_n_term and (atom.name in ("H3", "H2")):
atom.refdistance = 2
else:
path = util.shortest_path(map_, atom, caatom)
Expand All @@ -482,7 +489,7 @@ def remove_hydrogens(self):
if atom.is_hydrogen:
residue.remove_atom(atom.name)

def assign_termini(self, chain, neutraln=False, neutralc=False):
def assign_termini(self, chain, *, neutraln=False, neutralc=False):
"""Assign the termini for the given chain.
Assignment made by looking at the start and end residues.
Expand Down Expand Up @@ -612,7 +619,7 @@ def update_bonds(self):
res2.peptide_c = None
res1.peptide_n = None

def apply_patch(self, patchname, residue):
def apply_patch(self, patchname: str, residue: residue_.Residue):
"""Apply a patch to the given residue.
This is one of the key functions in PDB2PQR. A similar function
Expand Down
10 changes: 6 additions & 4 deletions pdb2pqr/debump.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def get_bump_score_atom(self, atom):
cutoff = atom_size + other_size
if dist < cutoff:
bumpscore += 1000.0
_LOGGER.debug(f"BUMPSCORE {str(bumpscore)}")
_LOGGER.debug(f"BUMPSCORE {bumpscore!s}")
return bumpscore

def debump_biomolecule(self):
Expand All @@ -159,7 +159,9 @@ def debump_biomolecule(self):
if not isinstance(residue, aa.Amino):
continue
# Initialize variables
conflict_names = self.find_residue_conflicts(residue, True)
conflict_names = self.find_residue_conflicts(
residue, write_conflict_info=True
)
if not conflict_names:
continue
# Otherwise debump the residue
Expand All @@ -177,7 +179,7 @@ def debump_biomolecule(self):
_LOGGER.warning(text)
_LOGGER.debug("Done checking if we must debump any residues.")

def find_residue_conflicts(self, residue, write_conflict_info=False):
def find_residue_conflicts(self, residue, *, write_conflict_info=False):
"""Find conflicts between residues.
:param residue: residue to check
Expand Down Expand Up @@ -269,7 +271,7 @@ def debump_residue(self, residue, conflict_names):
if score == 0:
if not self.find_residue_conflicts(residue):
_LOGGER.debug(
f"No conflicts found at angle {repr(newangle)}"
f"No conflicts found at angle {newangle!r}"
)
return True
else:
Expand Down
4 changes: 2 additions & 2 deletions pdb2pqr/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ def __str__(self):
text += f"Apply to: {self.applyto}\n"
text += "Atoms to add: \n"
for atom in self.map:
text += f"\t{str(self.map[atom])}\n"
text += f"\t{self.map[atom]!s}\n"
text += "Atoms to remove: \n"
for remove in self.remove:
text += f"\t{remove}\n"
Expand All @@ -249,7 +249,7 @@ def __str__(self):
text = f"{self.name}\n"
text += "Atoms: \n"
for atom in self.map:
text += f"\t{str(self.map[atom])}\n"
text += f"\t{self.map[atom]!s}\n"
text += "Dihedrals: \n"
for dihedral in self.dihedrals:
text += f"\t{dihedral}\n"
Expand Down
11 changes: 5 additions & 6 deletions pdb2pqr/forcefield.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ def __init__(self, map_, reference):

@classmethod
def update_map(cls, toname, fromname, map_):
"""Update the given map by adding a pointer from a new name to an
object.
"""Update the given map by adding a pointer from a new name to an object.
.. todo:: Should this be a staticmethod instead of classmethod?
Expand Down Expand Up @@ -195,7 +194,7 @@ def __init__(self, ff_name, definition, userff, usernames=None):
self.name = str(ff_name)
defpath = ""
defpath = io.test_dat_file(ff_name) if userff is None else userff
with open(defpath, "rt", encoding="utf-8") as ff_file:
with open(defpath, encoding="utf-8") as ff_file:
lines = ff_file.readlines()
for line in lines:
if not line.startswith("#"):
Expand Down Expand Up @@ -243,7 +242,7 @@ def __init__(self, ff_name, definition, userff, usernames=None):
raise ValueError("Unable to identify .names file.")
handler = ForcefieldHandler(self.map, definition.map)
sax.make_parser()
with open(names_path, "rt", encoding="utf-8") as namesfile:
with open(names_path, encoding="utf-8") as namesfile:
sax.parseString(namesfile.read(), handler)

def has_residue(self, resname):
Expand Down Expand Up @@ -1048,11 +1047,11 @@ def get(self, name):
"""
try:
return getattr(self, name)
except AttributeError:
except AttributeError as e:
message = (
f'Unable to access object "{name}" in class ForcefieldAtom'
)
raise KeyError(message)
raise KeyError(message) from e

def __str__(self):
txt = f"{self.name}:\n"
Expand Down
Loading

0 comments on commit 2e8b98f

Please sign in to comment.