Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix "Prefer format() over string interpolation operator" issue #592

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions package/MDAnalysis/analysis/align.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ def rms_fit_trj(traj, reference, select='all', filename=None, rmsdfile=None, pre
ref_atoms, traj_atoms = get_matching_atoms(ref_atoms, traj_atoms,
tol_mass=tol_mass, strict=strict)

logger.info("RMS-fitting on %d atoms." % len(ref_atoms))
logger.info("RMS-fitting on {0:d} atoms.".format(len(ref_atoms)))
if mass_weighted:
# if performing a mass-weighted alignment/rmsd calculation
weight = ref_atoms.masses / ref_atoms.masses.mean()
Expand Down Expand Up @@ -667,8 +667,8 @@ def fasta2select(fastafilename, is_aligned=False,
raise
with open(alnfilename) as aln:
alignment = Bio.AlignIO.read(aln, "clustal", alphabet=protein_gapped)
logger.info("Using clustalw sequence alignment %r" % alnfilename)
logger.info("ClustalW Newick guide tree was also produced: %r" % treefilename)
logger.info("Using clustalw sequence alignment {0!r}".format(alnfilename))
logger.info("ClustalW Newick guide tree was also produced: {0!r}".format(treefilename))

nseq = len(alignment)
if nseq != 2:
Expand Down Expand Up @@ -922,9 +922,8 @@ def get_atoms_byres(g, match_mask=np.logical_not(mismatch_mask)):

logger.error("Atoms: reference | trajectory")
for ar, at in itertools.izip(ag1[mismatch_atomindex], ag2[mismatch_atomindex]):
logger.error("%4s %3d %3s %3s %6.3f | %4s %3d %3s %3s %6.3f" %
(ar.segid, ar.resid, ar.resname, ar.name, ar.mass,
at.segid, at.resid, at.resname, at.name, at.mass,))
logger.error("{0:4s} {1:3d} {2:3s} {3:3s} {4:6.3f} | {5:4s} {6:3d} {7:3s} {8:3s} {9:6.3f}".format(ar.segid, ar.resid, ar.resname, ar.name, ar.mass,
at.segid, at.resid, at.resname, at.name, at.mass))
errmsg = ("Inconsistent selections, masses differ by more than {0}; " + \
"mis-matching atoms are shown above.").format(tol_mass)
logger.error(errmsg)
Expand Down
17 changes: 8 additions & 9 deletions package/MDAnalysis/analysis/contacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def __init__(self, topology, trajectory, ref1=None, ref2=None, radius=8.0,
# don't bother if trajectory is empty (can lead to segfaults so better catch it)
stats = os.stat(trajectory)
if stats.st_size == 0:
warnings.warn('trajectory = %(trajectory)s is empty, skipping...' % vars())
warnings.warn('trajectory = {trajectory!s} is empty, skipping...'.format(**vars()))
self._skip = True
return
# under normal circumstances we do not skip
Expand Down Expand Up @@ -320,7 +320,7 @@ def run(self, store=True, force=False):
if self._skip or self.output_exists(force=force):
import warnings

warnings.warn("File %(output)r or %(output_bz2)r already exists, loading %(trajectory)r." % vars(self))
warnings.warn("File {output!r} or {output_bz2!r} already exists, loading {trajectory!r}.".format(**vars(self)))
try:
self.load(self.output)
except IOError:
Expand All @@ -329,8 +329,7 @@ def run(self, store=True, force=False):

outbz2 = bz2.BZ2File(self.output_bz2, mode='w', buffering=8192)
try:
outbz2.write("# q1-q2 analysis\n# nref1 = %d\n# nref2 = %d\n"
% (self.nref[0], self.nref[1]))
outbz2.write("# q1-q2 analysis\n# nref1 = {0:d}\n# nref2 = {1:d}\n".format(self.nref[0], self.nref[1]))
outbz2.write("# frame q1 q2 n1 n2\n")
records = []
for ts in self.u.trajectory:
Expand All @@ -343,7 +342,7 @@ def run(self, store=True, force=False):

if store:
records.append((frame, q1, q2, n1, n2))
outbz2.write("%(frame)4d %(q1)8.6f %(q2)8.6f %(n1)5d %(n2)5d\n" % vars())
outbz2.write("{frame:4d} {q1:8.6f} {q2:8.6f} {n1:5d} {n2:5d}\n".format(**vars()))
finally:
outbz2.close()
if store:
Expand Down Expand Up @@ -608,7 +607,7 @@ def run(self, store=True, force=False, start_frame=1, end_frame=None, step_value
return None

with openany(self.output, 'w') as out:
out.write("# q1 analysis\n# nref = %d\n" % (self.nref))
out.write("# q1 analysis\n# nref = {0:d}\n".format((self.nref)))
out.write("# frame q1 n1\n")
records = []
self.qavg *= 0 # average contact existence
Expand All @@ -627,7 +626,7 @@ def run(self, store=True, force=False, start_frame=1, end_frame=None, step_value
self.qavg += self.q
if store:
records.append((frame, q1, n1))
out.write("%(frame)4d %(q1)8.6f %(n1)5d\n" % vars())
out.write("{frame:4d} {q1:8.6f} {n1:5d}\n".format(**vars()))
if store:
self.timeseries = np.array(records).T
n_frames = len(range(total_frames)[start_frame:end_frame:step_value])
Expand Down Expand Up @@ -758,8 +757,8 @@ def plot_qavg(self, filename=None, **kwargs):
xlim(min(x), max(x))
ylim(min(y), max(y))

xlabel("residue from %r" % self.selection_strings[0])
ylabel("residue from %r" % self.selection_strings[1])
xlabel("residue from {0!r}".format(self.selection_strings[0]))
ylabel("residue from {0!r}".format(self.selection_strings[1]))

colorbar()

Expand Down
20 changes: 7 additions & 13 deletions package/MDAnalysis/analysis/density.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,8 +370,7 @@ def convert_density(self, unit='Angstrom'):
try:
self.grid *= units.get_conversion_factor('density', self.units['density'], unit)
except KeyError:
raise ValueError("The name of the unit (%r supplied) must be one of:\n%r" %
(unit, units.conversion_factor['density'].keys()))
raise ValueError("The name of the unit ({0!r} supplied) must be one of:\n{1!r}".format(unit, units.conversion_factor['density'].keys()))
self.units['density'] = unit

def __repr__(self):
Expand Down Expand Up @@ -478,8 +477,7 @@ def current_coordinates():
return group.coordinates()

coord = current_coordinates()
logger.info("Selected %d atoms out of %d atoms (%s) from %d total." %
(coord.shape[0], len(u.select_atoms(atomselection)), atomselection, len(u.atoms)))
logger.info("Selected {0:d} atoms out of {1:d} atoms ({2!s}) from {3:d} total.".format(coord.shape[0], len(u.select_atoms(atomselection)), atomselection, len(u.atoms)))

# mild warning; typically this is run on RMS-fitted trajectories and
# so the box information is rather meaningless
Expand Down Expand Up @@ -509,8 +507,7 @@ def current_coordinates():
h = grid.copy()

for ts in u.trajectory:
print("Histograming %6d atoms in frame %5d/%d [%5.1f%%]\r" % \
(len(coord), ts.frame, u.trajectory.n_frames, 100.0 * ts.frame / u.trajectory.n_frames),)
print("Histograming {0:6d} atoms in frame {1:5d}/{2:d} [{3:5.1f}%]\r".format(len(coord), ts.frame, u.trajectory.n_frames, 100.0 * ts.frame / u.trajectory.n_frames),)
coord = current_coordinates()
if len(coord) == 0:
continue
Expand Down Expand Up @@ -758,8 +755,7 @@ def __init__(self, pdb, delta=1.0, atomselection='resname HOH and name O',
u = as_Universe(pdb)
group = u.select_atoms(atomselection)
coord = group.coordinates()
logger.info("Selected %d atoms (%s) out of %d total." %
(coord.shape[0], atomselection, len(u.atoms)))
logger.info("Selected {0:d} atoms ({1!s}) out of {2:d} total.".format(coord.shape[0], atomselection, len(u.atoms)))
smin = np.min(coord, axis=0) - padding
smax = np.max(coord, axis=0) + padding

Expand Down Expand Up @@ -788,7 +784,7 @@ def __init__(self, pdb, delta=1.0, atomselection='resname HOH and name O',
else:
# histogram 'delta functions'
grid, self.edges = np.histogramdd(coord, bins=bins, range=arange, normed=False)
logger.info("Histogrammed %6d atoms from pdb." % len(group.atoms))
logger.info("Histogrammed {0:6d} atoms from pdb.".format(len(group.atoms)))
# just a convolution of the density with a Gaussian
self.g = self._smear_sigma(grid, sigma)

Expand Down Expand Up @@ -824,8 +820,7 @@ def _smear_sigma(self, grid, sigma):
for iwat in xrange(len(pos[0])): # super-ugly loop
p = tuple([wp[iwat] for wp in pos])
g += grid[p] * np.fromfunction(self._gaussian, grid.shape, dtype=np.int, p=p, sigma=sigma)
print("Smearing out atom position %4d/%5d with RMSF %4.2f A\r" % \
(iwat + 1, len(pos[0]), sigma),)
print("Smearing out atom position {0:4d}/{1:5d} with RMSF {2:4.2f} A\r".format(iwat + 1, len(pos[0]), sigma),)
return g

def _smear_rmsf(self, coordinates, grid, edges, rmsf):
Expand All @@ -838,8 +833,7 @@ def _smear_rmsf(self, coordinates, grid, edges, rmsf):
continue
g += np.fromfunction(self._gaussian_cartesian, grid.shape, dtype=np.int,
c=coord, sigma=rmsf[iwat])
print("Smearing out atom position %4d/%5d with RMSF %4.2f A\r" % \
(iwat + 1, N, rmsf[iwat]),)
print("Smearing out atom position {0:4d}/{1:5d} with RMSF {2:4.2f} A\r".format(iwat + 1, N, rmsf[iwat]),)
return g

def _gaussian(self, i, j, k, p, sigma):
Expand Down
31 changes: 15 additions & 16 deletions package/MDAnalysis/analysis/hbonds/hbond_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,8 +536,8 @@ def __init__(self, universe, selection1='protein', selection2='all', selection1_
"heuristic": self._get_bonded_hydrogens_list, # pre 0.7.6
}
if not detect_hydrogens in self._get_bonded_hydrogens_algorithms:
raise ValueError("detect_hydrogens must be one of %r" %
self._get_bonded_hydrogens_algorithms.keys())
raise ValueError("detect_hydrogens must be one of {0!r}".format(
self._get_bonded_hydrogens_algorithms.keys()))
self.detect_hydrogens = detect_hydrogens

self.u = universe
Expand Down Expand Up @@ -566,7 +566,7 @@ def __init__(self, universe, selection1='protein', selection2='all', selection1_
if not (self.selection1 and self.selection2):
raise ValueError('HydrogenBondAnalysis: invalid selections')
elif self.selection1_type not in ('both', 'donor', 'acceptor'):
raise ValueError('HydrogenBondAnalysis: Invalid selection type %s' % self.selection1_type)
raise ValueError('HydrogenBondAnalysis: Invalid selection type {0!s}'.format(self.selection1_type))

self.timeseries = None # final result
self.timesteps = None # time for each frame
Expand Down Expand Up @@ -679,8 +679,7 @@ def _get_bonded_hydrogens_dist(self, atom):
"""
try:
return atom.residue.select_atoms(
"(name H* or name 1H* or name 2H* or name 3H* or type H) and around %f name %s" %
(self.r_cov[atom.name[0]], atom.name))
"(name H* or name 1H* or name 2H* or name 3H* or type H) and around {0:f} name {1!s}".format(self.r_cov[atom.name[0]], atom.name))
except NoDataError:
return []

Expand Down Expand Up @@ -760,18 +759,18 @@ def _update_selection_2(self):
self._s2_acceptors = {}
if self.selection1_type in ('donor', 'both'):
self._s2_acceptors = self._s2.select_atoms(
' or '.join(['name %s' % i for i in self.acceptors]))
self.logger_debug("Selection 2 acceptors: %d" % len(self._s2_acceptors))
' or '.join(['name {0!s}'.format(i) for i in self.acceptors]))
self.logger_debug("Selection 2 acceptors: {0:d}".format(len(self._s2_acceptors)))
if self.selection1_type in ('acceptor', 'both'):
self._s2_donors = self._s2.select_atoms(
' or '.join(['name %s' % i for i in self.donors]))
' or '.join(['name {0!s}'.format(i) for i in self.donors]))
self._s2_donors_h = {}
for i, d in enumerate(self._s2_donors):
tmp = self._get_bonded_hydrogens(d)
if tmp:
self._s2_donors_h[i] = tmp
self.logger_debug("Selection 2 donors: %d" % len(self._s2_donors))
self.logger_debug("Selection 2 donor hydrogens: %d" % len(self._s2_donors_h))
self.logger_debug("Selection 2 donors: {0:d}".format(len(self._s2_donors)))
self.logger_debug("Selection 2 donor hydrogens: {0:d}".format(len(self._s2_donors_h)))

def logger_debug(self, *args):
if self.verbose:
Expand Down Expand Up @@ -881,11 +880,11 @@ def _get_timestep():
dist = self.calc_eucl_distance(donor_atom, a)
if angle >= self.angle and dist <= self.distance:
self.logger_debug(
"S1-D: %s <-> S2-A: %s %f A, %f DEG" % (h.index + 1, a.index + 1, dist, angle))
"S1-D: {0!s} <-> S2-A: {1!s} {2:f} A, {3:f} DEG".format(h.index + 1, a.index + 1, dist, angle))
#self.logger_debug("S1-D: %r <-> S2-A: %r %f A, %f DEG" % (h, a, dist, angle))
frame_results.append(
[h.index + 1, a.index + 1, '%s%s:%s' % (h.resname, repr(h.resid), h.name),
'%s%s:%s' % (a.resname, repr(a.resid), a.name), dist, angle])
[h.index + 1, a.index + 1, '{0!s}{1!s}:{2!s}'.format(h.resname, repr(h.resid), h.name),
'{0!s}{1!s}:{2!s}'.format(a.resname, repr(a.resid), a.name), dist, angle])
already_found[(h.index + 1, a.index + 1)] = True
if self.selection1_type in ('acceptor', 'both') and len(self._s1_acceptors) > 0:
self.logger_debug("Selection 1 Acceptors <-> Donors")
Expand All @@ -904,11 +903,11 @@ def _get_timestep():
dist = self.calc_eucl_distance(donor_atom, a)
if angle >= self.angle and dist <= self.distance:
self.logger_debug(
"S1-A: %s <-> S2-D: %s %f A, %f DEG" % (a.index + 1, h.index + 1, dist, angle))
"S1-A: {0!s} <-> S2-D: {1!s} {2:f} A, {3:f} DEG".format(a.index + 1, h.index + 1, dist, angle))
#self.logger_debug("S1-A: %r <-> S2-D: %r %f A, %f DEG" % (a, h, dist, angle))
frame_results.append(
[h.index + 1, a.index + 1, '%s%s:%s' % (h.resname, repr(h.resid), h.name),
'%s%s:%s' % (a.resname, repr(a.resid), a.name), dist, angle])
[h.index + 1, a.index + 1, '{0!s}{1!s}:{2!s}'.format(h.resname, repr(h.resid), h.name),
'{0!s}{1!s}:{2!s}'.format(a.resname, repr(a.resid), a.name), dist, angle])
self.timeseries.append(frame_results)

logger.info("HBond analysis: complete; timeseries with %d hbonds in %s.timeseries",
Expand Down
Loading