Modernize print statements with str.format()

This commit is contained in:
Nathan Baker
2020-05-28 20:31:03 -07:00
parent ba67f5149d
commit 87347a7d60
5 changed files with 70 additions and 59 deletions

View File

@@ -113,7 +113,7 @@ class Protonate:
i = 1 i = 1
for bonded in heavy_atom.bonded_atoms: for bonded in heavy_atom.bonded_atoms:
if bonded.element == 'H': if bonded.element == 'H':
bonded.name += '%d' % i bonded.name += str(i)
i += 1 i += 1
def set_number_of_protons_to_add(self, atom): def set_number_of_protons_to_add(self, atom):
@@ -125,15 +125,16 @@ class Protonate:
debug('*'*10) debug('*'*10)
debug('Setting number of protons to add for', atom) debug('Setting number of protons to add for', atom)
atom.number_of_protons_to_add = 8 atom.number_of_protons_to_add = 8
debug(' %4d' % 8) debug(" 8")
atom.number_of_protons_to_add -= self.valence_electrons[atom.element] atom.number_of_protons_to_add -= self.valence_electrons[atom.element]
debug('Valence eletrons: %4d' % -self.valence_electrons[atom.element]) debug('Valence electrons: {0:>4d}'.format(
-self.valence_electrons[atom.element]))
atom.number_of_protons_to_add -= len(atom.bonded_atoms) atom.number_of_protons_to_add -= len(atom.bonded_atoms)
debug('Number of bonds: %4d' % -len(atom.bonded_atoms)) debug('Number of bonds: {0:>4d}'.format(-len(atom.bonded_atoms)))
atom.number_of_protons_to_add -= atom.num_pi_elec_2_3_bonds atom.number_of_protons_to_add -= atom.num_pi_elec_2_3_bonds
debug('Pi electrons: %4d' % -atom.num_pi_elec_2_3_bonds) debug('Pi electrons: {0:>4d}'.format(-atom.num_pi_elec_2_3_bonds))
atom.number_of_protons_to_add += int(atom.charge) atom.number_of_protons_to_add += int(atom.charge)
debug('Charge: %4.1f' % atom.charge) debug('Charge: {0:>4.1f}'.format(atom.charge))
debug('-'*10) debug('-'*10)
debug(atom.number_of_protons_to_add) debug(atom.number_of_protons_to_add)
@@ -149,35 +150,37 @@ class Protonate:
debug('='*10) debug('='*10)
debug('Setting steric number and lone pairs for', atom) debug('Setting steric number and lone pairs for', atom)
atom.steric_number = 0 atom.steric_number = 0
debug('%65s: %4d' % ('Valence electrons', debug('{0:>65s}: {1:>4d}'.format(
self.valence_electrons[atom.element])) 'Valence electrons', self.valence_electrons[atom.element]))
atom.steric_number += self.valence_electrons[atom.element] atom.steric_number += self.valence_electrons[atom.element]
debug('%65s: %4d' % ('Number of bonds', debug('{0:>65s}: {1:>4d}'.format(
len(atom.bonded_atoms))) 'Number of bonds', len(atom.bonded_atoms)))
atom.steric_number += len(atom.bonded_atoms) atom.steric_number += len(atom.bonded_atoms)
debug('%65s: %4d' % ('Number of hydrogen atoms to add', debug('{0:>65s}: {1:>4d}'.format(
atom.number_of_protons_to_add)) 'Number of hydrogen atoms to add', atom.number_of_protons_to_add))
atom.steric_number += atom.number_of_protons_to_add atom.steric_number += atom.number_of_protons_to_add
debug('%65s: %4d' % ('Number of pi-electrons in double ' debug('{0:>65s}: {1:>4d}'.format(
'and triple bonds(-)', 'Number of pi-electrons in double and triple bonds(-)',
atom.num_pi_elec_2_3_bonds)) atom.num_pi_elec_2_3_bonds))
atom.steric_number -= atom.num_pi_elec_2_3_bonds atom.steric_number -= atom.num_pi_elec_2_3_bonds
debug('%65s: %4d' % ('Number of pi-electrons in conjugated double and ' debug('{0:>65s}: {1:>4d}'.format(
'triple bonds(-)', 'Number of pi-electrons in conjugated double and triple bonds(-)',
atom.num_pi_elec_conj_2_3_bonds)) atom.num_pi_elec_conj_2_3_bonds))
atom.steric_number -= atom.num_pi_elec_conj_2_3_bonds atom.steric_number -= atom.num_pi_elec_conj_2_3_bonds
debug('%65s: %4d' % ('Number of donated co-ordinated bonds', 0)) debug('{0:>65s}: {1:>4d}'.format(
'Number of donated co-ordinated bonds', 0))
atom.steric_number += 0 atom.steric_number += 0
debug('%65s: %4.1f' % ('Charge(-)', atom.charge)) debug('{0:>65s}: {1:>4.1f}'.format(
'Charge(-)', atom.charge))
atom.steric_number -= atom.charge atom.steric_number -= atom.charge
atom.steric_number = math.floor(atom.steric_number/2.0) atom.steric_number = math.floor(atom.steric_number/2.0)
atom.number_of_lone_pairs = (atom.steric_number atom.number_of_lone_pairs = (
- len(atom.bonded_atoms) atom.steric_number-len(atom.bonded_atoms)-atom.number_of_protons_to_add)
- atom.number_of_protons_to_add)
debug('-'*70) debug('-'*70)
debug('%65s: %4d' % ('Steric number', atom.steric_number)) debug('{0:>65s}: {1:>4d}'.format(
debug('%65s: %4d' % ('Number of lone pairs', 'Steric number', atom.steric_number))
atom.number_of_lone_pairs)) debug('{0:>65s}: {1:>4d}'.format(
'Number of lone pairs', atom.number_of_lone_pairs))
atom.steric_num_lone_pairs_set = True atom.steric_num_lone_pairs_set = True
def add_protons(self, atom): def add_protons(self, atom):
@@ -191,8 +194,8 @@ class Protonate:
if atom.steric_number in list(self.protonation_methods.keys()): if atom.steric_number in list(self.protonation_methods.keys()):
self.protonation_methods[atom.steric_number](atom) self.protonation_methods[atom.steric_number](atom)
else: else:
warning('Do not have a method for protonating', warning('Do not have a method for protonating', atom,
atom, '(steric number: %d)' % atom.steric_number) '(steric number: {0:d})'.format(atom.steric_number))
def trigonal(self, atom): def trigonal(self, atom):
"""Add hydrogens in trigonal geometry. """Add hydrogens in trigonal geometry.
@@ -200,7 +203,7 @@ class Protonate:
Args: Args:
atom: atom to protonate atom: atom to protonate
""" """
debug('TRIGONAL - %d bonded atoms' % len(atom.bonded_atoms)) debug('TRIGONAL - {0:d} bonded atoms'.format(len(atom.bonded_atoms)))
rot_angle = math.radians(120.0) rot_angle = math.radians(120.0)
cvec = Vector(atom1=atom) cvec = Vector(atom1=atom)
# 0 bonds # 0 bonds
@@ -258,7 +261,8 @@ class Protonate:
Args: Args:
atom: atom to protonate. atom: atom to protonate.
""" """
debug('TETRAHEDRAL - %d bonded atoms' % len(atom.bonded_atoms)) debug(
'TETRAHEDRAL - {0:d} bonded atoms'.format(len(atom.bonded_atoms)))
# TODO - might be good to move tetrahedral angle to constant # TODO - might be good to move tetrahedral angle to constant
rot_angle = math.radians(109.5) rot_angle = math.radians(109.5)
cvec = Vector(atom1=atom) cvec = Vector(atom1=atom)
@@ -304,7 +308,7 @@ class Protonate:
new_h = propka.atom.Atom() new_h = propka.atom.Atom()
new_h.set_property( new_h.set_property(
numb=None, numb=None,
name='H%s' % atom.name[1:], name='H{0:s}'.format(atom.name[1:]),
res_name=atom.res_name, res_name=atom.res_name,
chain_id=atom.chain_id, chain_id=atom.chain_id,
res_num=atom.res_num, res_num=atom.res_num,
@@ -327,14 +331,15 @@ class Protonate:
atom.number_of_protons_to_add -= 1 atom.number_of_protons_to_add -= 1
atom.conformation_container.add_atom(new_h) atom.conformation_container.add_atom(new_h)
# update names of all protons on this atom # update names of all protons on this atom
new_h.residue_label = "%-3s%4d%2s" % (new_h.name, new_h.res_num, new_h.residue_label = "{0:<3s}{1:>4d}{2:>2s}".format(
new_h.chain_id) new_h.name, new_h.res_num, new_h.chain_id)
no_protons = atom.count_bonded_elements('H') no_protons = atom.count_bonded_elements('H')
if no_protons > 1: if no_protons > 1:
i = 1 i = 1
for proton in atom.get_bonded_elements('H'): for proton in atom.get_bonded_elements('H'):
proton.name = 'H%s%d' % (atom.name[1:], i) proton.name = 'H{0:s}{1:d}'.format(
proton.residue_label = "%-3s%4d%2s" % ( atom.name[1:], i)
proton.residue_label = "{0:<3s}{1:>4d}{2:>2s}".format(
proton.name, proton.res_num, proton.chain_id) proton.name, proton.res_num, proton.chain_id)
i += 1 i += 1
debug('added', new_h, 'to', atom) debug('added', new_h, 'to', atom)
@@ -352,8 +357,9 @@ class Protonate:
if element in list(self.bond_lengths.keys()): if element in list(self.bond_lengths.keys()):
dist = self.bond_lengths[element] dist = self.bond_lengths[element]
else: else:
str_ = ('Bond length for %s not found, using the standard value ' str_ = (
'of %f' % (element, dist)) 'Bond length for {0:s} not found, using the standard value '
'of {1:f}'.format(element, dist))
warning(str_) warning(str_)
bvec = bvec.rescale(dist) bvec = bvec.rescale(dist)
return bvec return bvec

View File

@@ -34,7 +34,7 @@ def single(pdbfile, optargs=None):
options = loadOptions(*optargs) options = loadOptions(*optargs)
pdbfile = options.filenames.pop(0) pdbfile = options.filenames.pop(0)
if len(options.filenames) > 0: if len(options.filenames) > 0:
_LOGGER.warning("Ignoring filenames: %s", options.filenames) _LOGGER.warning("Ignoring filenames: {0:s}".format(options.filenames))
my_molecule = Molecular_container(pdbfile, options) my_molecule = Molecular_container(pdbfile, options)
my_molecule.calculate_pka() my_molecule.calculate_pka()
my_molecule.write_pka() my_molecule.write_pka()

View File

@@ -58,7 +58,7 @@ class Vector:
elif type(other) in [int, float]: elif type(other) in [int, float]:
return Vector(self.x * other, self.y * other, self.z * other) return Vector(self.x * other, self.y * other, self.z * other)
else: else:
info('%s not supported' % type(other)) info('{0:s} not supported'.format(type(other)))
raise TypeError raise TypeError
def __rmul__(self, other): def __rmul__(self, other):
@@ -85,7 +85,8 @@ class Vector:
return math.sqrt(self.sq_length()) return math.sqrt(self.sq_length())
def __str__(self): def __str__(self):
return '%10.4f %10.4f %10.4f'%(self.x, self.y, self.z) return '{0:>10.4f} {1:>10.4f} {2:>10.4f}'.format(
self.x, self.y, self.z)
def __repr__(self): def __repr__(self):
return '<vector>' return '<vector>'
@@ -100,9 +101,7 @@ class Vector:
def rescale(self, new_length): def rescale(self, new_length):
""" Rescale vector to new length while preserving direction """ """ Rescale vector to new length while preserving direction """
frac = new_length/(self.length()) frac = new_length/(self.length())
res = Vector(xi=self.x*frac, res = Vector(xi=self.x*frac, yi=self.y*frac, zi=self.z*frac)
yi=self.y*frac,
zi=self.z*frac)
return res return res
@@ -296,7 +295,8 @@ class MultiVector:
keys2 = get_sorted_configurations(atom2.configurations.keys()) keys2 = get_sorted_configurations(atom2.configurations.keys())
if self.keys != keys2: if self.keys != keys2:
str_ = ('Cannot make multi vector: Atomic configurations ' str_ = ('Cannot make multi vector: Atomic configurations '
'mismatch for\n %s\n %s\n' % (atom1, atom2)) 'mismatch for\n {0:s}\n {1:s}\n'.format(
atom1, atom2))
raise KeyError(str_) raise KeyError(str_)
for key in self.keys: for key in self.keys:
atom1.setConfiguration(key) atom1.setConfiguration(key)
@@ -314,7 +314,7 @@ class MultiVector:
def __str__(self): def __str__(self):
res = '' res = ''
for i, key in enumerate(self.keys): for i, key in enumerate(self.keys):
res += '%s %s\n' % (key, self.vectors[i]) res += '{0:s} {1:s}\n'.format(key, self.vectors[i])
return res return res
def do_job(self, job): def do_job(self, job):
@@ -350,8 +350,9 @@ class MultiVector:
for i in range(len(self.vectors)): for i in range(len(self.vectors)):
self.result.vectors.append( self.result.vectors.append(
# TODO - eliminate eval() or entire class # TODO - eliminate eval() or entire class
eval('self.vectors[%d] %s other.vectors[%d]' eval(
% (i, operation, i))) 'self.vectors[{0:d}] {1:s} other.vectors[{2:d}]'.format(
i, operation, i)))
self.result.keys.append(self.keys[i]) self.result.keys.append(self.keys[i])
def __add__(self, other): def __add__(self, other):

View File

@@ -31,7 +31,7 @@ class Version:
Raises: Raises:
NotImplementedError NotImplementedError
""" """
err = "Called an empty Version function with args %s" % args err = "Called an empty Version function with args {0:s}".format(args)
raise NotImplementedError(err) raise NotImplementedError(err)
def calculate_desolvation(self, group): def calculate_desolvation(self, group):

View File

@@ -48,8 +48,9 @@ def get_test_dirs():
if test_path.is_dir(): if test_path.is_dir():
path_dict[key] = test_path path_dict[key] = test_path
else: else:
errstr = ("Can't find %s test files in %s" errstr = (
% (key, [TEST_DIR / path, path])) "Can't find {0:s} test files in {1:s}".format(
key, [TEST_DIR / path, path]))
raise FileNotFoundError(errstr) raise FileNotFoundError(errstr)
return path_dict return path_dict
@@ -65,8 +66,9 @@ def run_propka(options, pdb_path, tmp_path):
options += [str(pdb_path)] options += [str(pdb_path)]
args = propka.lib.loadOptions(options) args = propka.lib.loadOptions(options)
try: try:
_LOGGER.warning("Working in tmpdir %s because of PROPKA file output; " _LOGGER.warning(
"need to fix this.", tmp_path) "Working in tmpdir {0:s} because of PROPKA file output; "
"need to fix this.".format(str(tmp_path)))
cwd = Path.cwd() cwd = Path.cwd()
os.chdir(tmp_path) os.chdir(tmp_path)
molecule = propka.molecular_container.Molecular_container( molecule = propka.molecular_container.Molecular_container(
@@ -93,7 +95,7 @@ def compare_output(pdb, tmp_path, ref_path):
ref_data.append(float(line)) ref_data.append(float(line))
test_data = [] test_data = []
pka_path = Path(tmp_path) / ("%s.pka" % pdb) pka_path = Path(tmp_path) / ("{0:s}.pka".format(pdb))
with open(pka_path, "rt") as pka_file: with open(pka_path, "rt") as pka_file:
at_pka = False at_pka = False
for line in pka_file: for line in pka_file:
@@ -106,8 +108,9 @@ def compare_output(pdb, tmp_path, ref_path):
match = re.search(r'([0-9]+\.[0-9]+)', line) match = re.search(r'([0-9]+\.[0-9]+)', line)
value = float(match.group(0)) value = float(match.group(0))
test_data.append(value) test_data.append(value)
errstr = ("Error exceeds maximum allowed value (%d decimal places)" errstr = (
% MAX_ERR_DECIMALS) "Error exceeds maximum allowed value ({0:d} decimal places)".format(
MAX_ERR_DECIMALS))
assert_almost_equal( assert_almost_equal(
test_data, ref_data, decimal=MAX_ERR_DECIMALS, err_msg=errstr, test_data, ref_data, decimal=MAX_ERR_DECIMALS, err_msg=errstr,
verbose=True) verbose=True)
@@ -126,17 +129,18 @@ def compare_output(pdb, tmp_path, ref_path):
def test_regression(pdb, options, tmp_path): def test_regression(pdb, options, tmp_path):
"""Basic regression test of PROPKA functionality.""" """Basic regression test of PROPKA functionality."""
path_dict = get_test_dirs() path_dict = get_test_dirs()
ref_path = path_dict["results"] / ("%s.dat" % pdb) ref_path = path_dict["results"] / ("{0:s}.dat".format(pdb))
if ref_path.is_file(): if ref_path.is_file():
ref_path = ref_path.resolve() ref_path = ref_path.resolve()
else: else:
_LOGGER.warning("Missing results file for comparison: %s", ref_path) _LOGGER.warning("Missing results file for comparison: {0:s}".format(
str(ref_path)))
ref_path = None ref_path = None
pdb_path = path_dict["pdbs"] / ("%s.pdb" % pdb) pdb_path = path_dict["pdbs"] / ("{0:s}.pdb".format(pdb))
if pdb_path.is_file(): if pdb_path.is_file():
pdb_path = pdb_path.resolve() pdb_path = pdb_path.resolve()
else: else:
errstr = "Missing PDB file: %s" % pdb_path errstr = "Missing PDB file: {0:s}".format(pdb_path)
raise FileNotFoundError(errstr) raise FileNotFoundError(errstr)
tmp_path = Path(tmp_path).resolve() tmp_path = Path(tmp_path).resolve()